自定义权限校验方法、基于配置的权限控制、CSRF

发布时间 2023-04-24 09:34:07作者: 肥宅快乐水~

自定义权限校验方法

我们也可以定义自己的权限校验方法。在@PreAuthorize注解中使用我们的方法。

创建expression包,在该包下创建SGEexpression类

@Component("ex")
public class SGEexpression {

    public boolean hasAuthority(String authority) {
        // 获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        List<String> permissions = loginUser.getPermissions();
        // 判断用户权限集合中是否存在authority
        return permissions.contains(authority);
    }

}

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

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

基于配置的权限控制

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

SecurityConfig配置类

  @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/user/login").anonymous()
                .antMatchers("/testCors").hasAuthority("system:dept:list")
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();

        // 把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        http.exceptionHandling()
                // 配置认证失败处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        // 允许跨域
        http.cors();
    }

CSRF

CSRF是指跨站请求伪造(Cross-site request forgery),是常见的攻击之一。

https://blog.csdn.net/freeking101/article/details/86537087

SpringSecurity去放置CSRF攻击的方式就是通过csrf_token。后端会生成一个csrf_token,前端发起请求的时候需要携带这个csrf_token,后端会有过滤器进行校验,如果没有携带或者是伪造的就不允许访问。

我们可以发现CSRF攻击依靠的是cookie中所携带的认证信息。但是在前后端分离的项目中我们的认证信息其实是token,而token并不是存储到cookie中,并且需要前端代码去把token设置到请求头中才可以,所以CSRF攻击也就不用担心了。