介紹
what is Spring Security.png
這是Spring Security官方文檔的一段介紹,大概是講Spring Security為基于Java開(kāi)發(fā)的應(yīng)用程序提供了全面的安全服務(wù)凄诞,建議我們結(jié)合Spring去使用,現(xiàn)在有很多身份驗(yàn)證都是通過(guò)第三方的诈胜,但是Spring Security提供了自己的一組身份驗(yàn)證特性。具體來(lái)說(shuō),Spring Security目前支持所有這些技術(shù)的身份驗(yàn)證集成幔烛;
運(yùn)行原理
security.png
大概畫(huà)了security的主要攔截器的流程圖荆忍。
代碼實(shí)現(xiàn)
-
添加依賴
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-test</artifactId> <scope>test</scope> </dependency>
-
yml配置
server: port: 80 spring: datasource: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/securite?useUnicode=true&characterEncoding=utf8 username: root password: 123 mybatis: configuration: map-underscore-to-camel-case: true
-
數(shù)據(jù)庫(kù)
user.pngroles 表示角色格带,多個(gè)角色用“,”隔開(kāi)刹枉,前綴是ROLE_叽唱。
-
實(shí)體類
@Data public class UserModel { private int id; private String name; private String password; private int age; private String address; private String roles; }
-
mapper層
@Mapper public interface UserMapper { @Select("select * from user where name = #{name}") UserModel getUserByName(String name); }
-
service 層
@Service public class UserService { @Autowired private UserMapper userMapper; public UserModel getUserByName(String name) { return userMapper.getUserByName(name); } }
-
UserDetailsService具體實(shí)現(xiàn)(這里就是具體校驗(yàn)過(guò)程)
@Service public class MyUserDetailsService implements UserDetailsService { @Autowired private UserService userService; @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { UserModel userModel = userService.getUserByName(s); if (userModel == null) { throw new UsernameNotFoundException("用戶不存在"); } return new User(userModel.getName(), userModel.getPassword(), createAuthority(userModel.getRoles())); } //這里是將數(shù)據(jù)庫(kù)的角色分割,構(gòu)造GrantedAuthority private List<SimpleGrantedAuthority> createAuthority(String roles) { String[] roleArray = roles.split(","); List<SimpleGrantedAuthority> authorityList = new ArrayList<>(); for (String role : roleArray) { authorityList.add(new SimpleGrantedAuthority(role)); } return authorityList; } }
-
攔截規(guī)則設(shè)置
@EnableWebSecurity @Configuration public class MyWebSecuriteConfig extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailsService myUserDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()//攔截 .antMatchers("/", "/home").permitAll()//允許/微宝、/home的訪問(wèn) .antMatchers("/user/**").hasAnyRole("USER")//用戶USER角色的用戶訪問(wèn)有關(guān)/user下面的所有 .antMatchers("/admin/**").hasAnyRole("ADMIN")//同上 .anyRequest().authenticated()//其它所有訪問(wèn)都攔截 .and() .formLogin()//添加登陸 .loginPage("/login").permitAll()//登陸頁(yè)面“/login"允許訪問(wèn) .defaultSuccessUrl("/buy")//成功默認(rèn)跳轉(zhuǎn)/buy .permitAll() .and() .logout().logoutUrl("/logout") .logoutSuccessUrl("/login") .permitAll();//同上 } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(myUserDetailsService);//添加實(shí)現(xiàn)的UserDetailsService } }
-
controller
@Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("home"); registry.addViewController("/home").setViewName("home"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/buy").setViewName("buy"); } }
頁(yè)面就不貼出來(lái)了,請(qǐng)看源碼