• spring security调用过程;及自定义改造


    认证/授权概述

    一般系统都有登录接口来校验用户是否存在,密码是否正确,然后会颁发一个token给客户端,后续客户端就可以带着这个token来请求,代表自己是合法请求。

    在这里插入图片描述

    spring security责任链

    请求->UsernamePasswordAuthenticationFilter(判断用户名密码是否正确)->ExceptionTranslationFilter(认证授权时的异常统一处理)->FilterSecurityInterceptor(判断当前用户是否有访问资源权限)->API接口->响应

    调用链路图如下,一般我们会从db中去获取用户,所以我们要自己实现userDetailService接口,去重写loadUserByUsername。同时因为自带的UsernamePasswordAuthenticationFilter认证完了就结束了,但实际上我们在认证之后还要授权,所以这里的入口也需要替换成我们自己的controller。在认证过程中查询用户信息的时候,顺序把用户权限也查出来塞到redis中,后面在拿到token来请求的时候就可以直接从redis中获取权限缓存了。

    认证授权完了之后,就可以自己再定义个filter,检查请求头里携带的token,解析之后拿到信息封装成
    Authentication对象再塞进SecurityContextHolder里的threadLocal变量中,后面在当前请求线程中就可以直接拿出来用了。
    在这里插入图片描述

    下面来直接上个demo

    就拿ruoyi现成的配置来举例了,上面说我们需要自定义登录和用户查询逻辑,所以需要在springsecurity中给我们自己的登录接口开一个口子。
    在登录完成之后会返回一个token,所以我们还需要自己写一个token过滤器,解析token,并且把用户信息塞到SecurityContextHolder中给security后面的过滤器使用

    配置类

    package com.ruoyi.framework.config;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.http.HttpMethod;
    import org.springframework.security.authentication.AuthenticationManager;
    import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
    import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
    import org.springframework.security.config.http.SessionCreationPolicy;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
    import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
    import org.springframework.security.web.authentication.logout.LogoutFilter;
    import org.springframework.web.filter.CorsFilter;
    import com.ruoyi.framework.config.properties.PermitAllUrlProperties;
    import com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter;
    import com.ruoyi.framework.security.handle.AuthenticationEntryPointImpl;
    import com.ruoyi.framework.security.handle.LogoutSuccessHandlerImpl;
    
    /**
     * spring security配置
     * 
     * @author ruoyi
     */
    @EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter
    {
        /**
         * 自定义用户认证逻辑
         */
        @Autowired
        private UserDetailsService userDetailsService;
        
        /**
         * 认证失败处理类
         */
        @Autowired
        private AuthenticationEntryPointImpl unauthorizedHandler;
    
        /**
         * 退出处理类
         */
        @Autowired
        private LogoutSuccessHandlerImpl logoutSuccessHandler;
    
        /**
         * token认证过滤器
         */
        @Autowired
        private JwtAuthenticationTokenFilter authenticationTokenFilter;
        
        /**
         * 跨域过滤器
         */
        @Autowired
        private CorsFilter corsFilter;
    
        /**
         * 允许匿名访问的地址
         */
        @Autowired
        private PermitAllUrlProperties permitAllUrl;
    
        /**
         * 解决 无法直接注入 AuthenticationManager
         *
         * @return
         * @throws Exception
         */
        @Bean
        @Override
        public AuthenticationManager authenticationManagerBean() throws Exception
        {
            return super.authenticationManagerBean();
        }
    
        /**
         * anyRequest          |   匹配所有请求路径
         * access              |   SpringEl表达式结果为true时可以访问
         * anonymous           |   匿名可以访问
         * denyAll             |   用户不能访问
         * fullyAuthenticated  |   用户完全认证可以访问(非remember-me下自动登录)
         * hasAnyAuthority     |   如果有参数,参数表示权限,则其中任何一个权限可以访问
         * hasAnyRole          |   如果有参数,参数表示角色,则其中任何一个角色可以访问
         * hasAuthority        |   如果有参数,参数表示权限,则其权限可以访问
         * hasIpAddress        |   如果有参数,参数表示IP地址,如果用户IP和参数匹配,则可以访问
         * hasRole             |   如果有参数,参数表示角色,则其角色可以访问
         * permitAll           |   用户可以任意访问
         * rememberMe          |   允许通过remember-me登录的用户访问
         * authenticated       |   用户登录后可访问
         */
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception
        {
            // 注解标记允许匿名访问的url
            ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests();
            permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll());
    
            httpSecurity
                    // CSRF禁用,因为不使用session
                    .csrf().disable()
                    // 禁用HTTP响应标头
                    .headers().cacheControl().disable().and()
                    // 认证失败处理类
                    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                    // 基于token,所以不需要session
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                    // 过滤请求
                    .authorizeRequests()
                    // 对于登录login 注册register 验证码captchaImage 允许匿名访问
                    .antMatchers("/login", "/register", "/captchaImage").permitAll()
                    // 静态资源,可匿名访问
                    .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
                    .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll()
                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated()
                    .and()
                    .headers().frameOptions().disable();
            // 添加Logout filter
            httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler);
            // 添加JWT filter
            httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
            // 添加CORS filter
            httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
            httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class);
        }
    
        /**
         * 强散列哈希加密实现
         */
        @Bean
        public BCryptPasswordEncoder bCryptPasswordEncoder()
        {
            return new BCryptPasswordEncoder();
        }
    
        /**
         * 身份认证接口
         */
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception
        {
            auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148

    token过滤器
    直接拿ruoyi的把

    package com.ruoyi.framework.security.filter;
    
    import java.io.IOException;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
    import org.springframework.stereotype.Component;
    import org.springframework.web.filter.OncePerRequestFilter;
    import com.ruoyi.common.core.domain.model.LoginUser;
    import com.ruoyi.common.utils.SecurityUtils;
    import com.ruoyi.common.utils.StringUtils;
    import com.ruoyi.framework.web.service.TokenService;
    
    /**
     * token过滤器 验证token有效性
     * 
     * @author ruoyi
     */
    @Component
    public class JwtAuthenticationTokenFilter extends OncePerRequestFilter
    {
        @Autowired
        private TokenService tokenService;
    
        @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
                throws ServletException, IOException
        {
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser) && StringUtils.isNull(SecurityUtils.getAuthentication()))
            {
                tokenService.verifyToken(loginUser);
                //三个参数的构造函数会将一个认证参数 set true,代表是已经认证过的。不然还会进入loadUserByUsername方法
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
            chain.doFilter(request, response);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    退出登录

    只需要把redis中的存放的用户信息删除即可,这样在token filter那一层获取不到redis缓存就会报异常。

    自定义权限认证

    先加上注解开启@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
    常用就是@PreAuthorize这个注解了,代表在处理前校验。

    自定义一个权限处理类,在权限验证方法中返回boolean值。

    package com.fchan.service;
    
    import com.fchan.entity.Role;
    import com.fchan.security.model.MyUserDTO;
    import org.springframework.security.core.Authentication;
    import org.springframework.security.core.context.SecurityContextHolder;
    import org.springframework.stereotype.Service;
    
    import java.util.stream.Collectors;
    
    /**
     * ClassName: SpringSecurityPermissionService
     * Description:
     * date: 2022/11/14 20:52
     *
     * @author fchen
     */
    @Service("ss")
    public class SpringSecurityPermissionService {
    
        public boolean hasPermi(String permission){
    
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    
            MyUserDTO myUserDTO = (MyUserDTO) authentication.getPrincipal();
    
            return myUserDTO.getRoles().stream().map(it -> it.getId().toString()).collect(Collectors.toList()).contains(permission);
    
        }
    
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    controller中校验,这里的2就是自定义参数,和当前登录用户信息中的参数进行比较,符合要求就进行放行

    @GetMapping("test")
    @PreAuthorize("@ss.hasPermi('2')")
    public Object test(){
        return "test success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    认证/授权失败异常处理

    认证失败:实现org.springframework.security.web.AuthenticationEntryPoint接口可自定义认证失败
    授权失败:实现org.springframework.security.web.access.AccessDeniedHandler接口可自定义授权失败

    认证失败demo

    package com.ruoyi.framework.security.handle;
    
    import java.io.IOException;
    import java.io.Serializable;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.springframework.security.core.AuthenticationException;
    import org.springframework.security.web.AuthenticationEntryPoint;
    import org.springframework.stereotype.Component;
    import com.alibaba.fastjson2.JSON;
    import com.ruoyi.common.constant.HttpStatus;
    import com.ruoyi.common.core.domain.AjaxResult;
    import com.ruoyi.common.utils.ServletUtils;
    import com.ruoyi.common.utils.StringUtils;
    
    /**
     * 认证失败处理类 返回未授权
     * 
     * @author ruoyi
     */
    @Component
    public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
    {
        private static final long serialVersionUID = -8970718410437077606L;
    
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
                throws IOException
        {
            int code = HttpStatus.UNAUTHORIZED;
            String msg = StringUtils.format("请求访问:{},认证失败,无法访问系统资源", request.getRequestURI());
            renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        }
    
    
     /**
         * 将字符串渲染到客户端
         * 
         * @param response 渲染对象
         * @param string 待渲染的字符串
         */
        public static void renderString(HttpServletResponse response, String string)
        {
            try
            {
                response.setStatus(200);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().print(string);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    鉴权失败(用户没有权限访问)
    同样实现org.springframework.security.web.access.AccessDeniedHandler接口完成方法接口。

    最后需要配置生效

     httpSecurity
                // CSRF禁用,因为不使用session
                .csrf().disable()
                // 禁用HTTP响应标头
                .headers().cacheControl().disable().and()
                // 认证失败处理类
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPointImpl)
                //鉴权失败
                .accessDeniedHandler(accessDeniedHandlerImpl)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    spring security跨域允许

    
        /**
         * 跨域配置
         */
        @Bean
        public CorsFilter corsFilter()
        {
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            // 设置访问源地址
            config.addAllowedOriginPattern("*");
            // 设置访问源请求头
            config.addAllowedHeader("*");
            // 设置访问源请求方法
            config.addAllowedMethod("*");
            // 有效期 1800秒
            config.setMaxAge(1800L);
            // 添加映射路径,拦截一切请求
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", config);
            // 返回新的CorsFilter
            return new CorsFilter(source);
        }
    
    
    //需要添加到sprint security的拦截器之前生效才可以,这里是在自定义的token校验拦截和登出拦截之前
    // 添加CORS filter
    httpSecurity.addFilterBefore(corsFilter(), com.ruoyi.framework.security.filter.JwtAuthenticationTokenFilter.class);
    httpSecurity.addFilterBefore(corsFilter(), org.springframework.security.web.authentication.logout.LogoutFilter.class);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
  • 相关阅读:
    微服务分布式开源架构是什么?
    arp欺骗
    如何通过AI视频智能分析技术,构建着装规范检测/工装穿戴检测系统?
    关于Android键值对存储的方案选择
    var 、let 和 const 的区别
    kafka集群穿透到公网实现过程
    15. Python 赋值运算
    Anaconda使用指南
    从单体迁移至微服务,需要有足够的理由和勇气
    Android 10以上出现的 android Permission denied 读写权限问题解决方法
  • 原文地址:https://blog.csdn.net/weixin_43944305/article/details/127759745