Spring Security进阶 (4)

service层要实现UserDetailService接口,去获取数据库中的信息做返回

@Service public class UserWnoRoleService implements UserDetailsService { @Autowired private SysUserMapper userMapper; @Autowired private SysRoleMapper roleMapper; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { //根据用户名获取用户 SysUser user = userMapper.selectByUsername(username); System.out.println("==== Service ====="); String roleName = ""; List<GrantedAuthority> list = new ArrayList<>(); System.out.println("User" + user); if (!StringUtils.isEmpty(user)) { //根据用户id获取对应角色 List<SysRole> roles = roleMapper.selectByUserId(user.getId()); for (SysRole role : roles) { //一个用户可能有多个角色,用集合保存,放到用户的集合里 roleName = role.getRole(); GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + roleName); list.add(authority); user.setGrantedAuthorities(list); } //返回的这个user是包含角色的 return user; } //可以返回自定义user,是因为实体类实现了UserDetails这个接口 return user; } } 2.6配置文件 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/库名?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=用户名 spring.datasource.password=密码 mybatis.mapper-locations=classpath:/mapper/*Mapper.xml # 包起别名 mybatis.type-aliases-package=com.huang.security.entity mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl 2.7相关的配置类 @Configuration //@EnableWebSecurity //如果是导入的jar包是spring-boot-starter-security可以不用写 public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { System.out.println("====== MySecurityConfig configure=============="); //匹配"/index","/login.html","/login" 不用验证(permit 许可),和登录相关的要放行 http.authorizeRequests().antMatchers("/index","/login.html","/login").permitAll() //匹配只有相关角色才能访问的路径 .antMatchers("/access/user/**").hasRole("USER") .antMatchers("/access/read/**").hasRole("READ") .antMatchers("/access/admin/**").hasRole("ADMIN") //所有都需要验证 .anyRequest().authenticated() //执行结束 .and() //表单的方式登录 .formLogin() //登录的自定义视图页面 .loginPage("/login.html") //登录访问的地址,表单中action的值 .loginProcessingUrl("/login") .and() //跨域安全的设置,禁用 .csrf().disable(); } @Qualifier("userWnoRoleService") @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //super.configure(auth); // userDetailsService使用的是service层的 UserWnoRoleService,它实现了 UserDetailsService auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } } 2.8html页面 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> 身份验证 <br> <a href="http://www.likecs.com/access/user">zs</a> <br> <a href="http://www.likecs.com/access/read">lisi</a> <br> <a href="http://www.likecs.com/access/admin">admin</a> <br> <a href="http://www.likecs.com/logout">退出</a> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <p>自定义登录页</p> <form action="/login" method="post"> 用户名:<input type="text" value=""><br/> 密&nbsp;&nbsp;&nbsp;码:<input type="password" value=""><br/> <input type="submit" value="登录"> </form> </body> </html> 2.9controller层测试 @Controller public class InitController { @GetMapping("index") public String toIndex() { return "forward:/index.html"; } } @RestController @RequestMapping("/access") public class UserWnoRoleController { @GetMapping("user") public String sayUser() { return "zs 是 user 角色"; } @GetMapping("read") public String sayRead() { return "lisi 是 read 角色"; } @GetMapping("admin") public String sayAdmin() { return "admin 是 user admin 角色"; } }

个人笔记

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zggwfs.html