spring-security-权限认识篇

1.授权概念

所谓的授权,就是用户如果要访问某一个资源,我们要去检查用户是否具备这样的权限,如果具备就允许访问,如果不具备,则不允许访问,本例是以基于角色控制权限的。即不同的角色,有不同的权限。

比如

admin可以执行增删改查

user只能查询

1.1 表

  • 用户表

  • 角色表
  • 用户-角色关系表

1.2 登录controller


@Controller
public class LoginController {
@Autowired
AuthenticationManager authenticationManager;
@RequestMapping("login")
public String get(String username,String password){
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
authenticationManager.authenticate(authenticationToken);
return "redirect:hello";//登录成功后
}
}

1.3 资源controller 设置权限

@PreAuthorize("permitAll()")
@GetMapping("/hello")
public String hello(){
return "hello security!!";
}
@PreAuthorize("hasRole('admin')")
@GetMapping("/admin/hello")
public String admin(){
return "hello admin!!";
}
@PreAuthorize("hasRole('admin' or hasRole('user'))")
@GetMapping("/user/hello")
public String user(){
return "hello user!!";
}

@PreAuthorize("permitAll()") --所有登录的人都可以访问
@PreAuthorize(hasRole('ADMIN') --管理员角色可以访问
@PreAuthorize("hasAnyRole('ADMIN','USER')") --同时具有两个角色可以访问
@PreAuthorize("hasAnyRole('ADMIN') or hasAnyRole('user') ")----具有任一角色可以访问

1.4 登录去数据库查询用户信息并封装USER

@Component
public class UserDetailService implements UserDetailsService {
@Autowired
UserService userService;
@Autowired
RedisTemplate redisTemplate;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
QueryWrapper wrapper = new QueryWrapper();
wrapper.eq("username",username);
User user = userService.getOne(wrapper);
if(null==user){
throw new UsernameNotFoundException("无此用户");
}
//获取当前用户的权限
List auths= userService.getAuth(username);
List list = auths.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
redisTemplate.opsForValue().set("AUTH:" + user.getUsername(),list);//redis存储一份
return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),list);
}
}

1.5注意开启权限注解

@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
//密码处理类
@Bean
public PasswordEncoder getPasswordEncoder(){
return new BCryptPasswordEncoder();
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}

8.7 测试

  • 使用admin登录,

  • user登录

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章