自定义权限验证方法

我们也可以定义自己的权限校验方法,在@PreAuthorize注解中使用我们的方法。
这个方法返回boolean类型。true就是可以访问,false就是不可以访问。
怎么在@PreAuthorize中使用自己写的方法呢,我们把自己写的权限验证类,注入到spring容器中,然后用@符号加上spring中这个对象名加点,就能调用这个方法了。注入到spring容器中的对象,默认对象名字就是第一个字母小写。当然也可以自己取个名字。

这是自定义的权限验证方法名。

  1. @Component("ex")
  2. public class SGExpressionRoot {
  3. public boolean hasAuthority(String authority){
  4. //获取当前用户的权限
  5. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  6. LoginUser loginUser = (LoginUser) authentication.getPrincipal();
  7. List<String> permissions = loginUser.getPermissions();
  8. //判断用户权限集合中是否存在authority
  9. return permissions.contains(authority);
  10. }
  11. }

在SPEL表达式中使用 @ex相当于获取容器中bean的名字为ex的对象。然后再调用这个对象的hasAuthority方法

  1. @RequestMapping("/hello")
  2. @PreAuthorize("@ex.hasAuthority('system:dept:list')")
  3. public String hello(){
  4. return "hello";
  5. }

基于配置的权限控制

我们也可以在配置类中使用使用配置的方式对资源进行权限控制。

  1. @Override
  2. protected void configure(HttpSecurity http) throws Exception {
  3. http
  4. //关闭csrf
  5. .csrf().disable()
  6. //不通过Session获取SecurityContext
  7. .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  8. .and()
  9. .authorizeRequests()
  10. // 对于登录接口 允许匿名访问
  11. .antMatchers("/user/login").anonymous()
  12. .antMatchers("/testCors").hasAuthority("system:dept:list222")
  13. // 除上面外的所有请求全部需要鉴权认证
  14. .anyRequest().authenticated();
  15. //添加过滤器
  16. http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
  17. //配置异常处理器
  18. http.exceptionHandling()
  19. //配置认证失败处理器
  20. .authenticationEntryPoint(authenticationEntryPoint)
  21. .accessDeniedHandler(accessDeniedHandler);
  22. //允许跨域
  23. http.cors();
  24. }

CSRF

CSRF是指跨站请求伪造(Cross-site request forgery),是web常见的攻击之一。
https://blog.csdn.net/freeking101/article/details/86537087
SpringSecurity去防止CSRF攻击的方式就是通过csrf_token。后端会生成一个csrf_token,前端发起请求的时候需要携带这个csrf_token,后端会有过滤器进行校验,如果没有携带或者是伪造的就不允许访问。
我们可以发现CSRF攻击依靠的是cookie中所携带的认证信息。但是在前后端分离的项目中我们的认证信息其实是token,而token并不是存储中cookie中,并且需要前端代码去把token设置到请求头中才可以,所以CSRF攻击也就不用担心了。