2023-06-18
原文作者:代码有毒 mrcode 原文地址:https://mrcode.blog.csdn.net/article/details/81502532

个性化用户认证流程2

自定义登录成功处理

security 默认的登录成功处理是跳转到需要授权之前访问的url;
而在一些场景下:比如 前后分离,登录是通过ajax访问,没有办法处理301跳转;
而是登录成功则返回相关的数据即可;

自定义入口还是在表单登录处配置的

    http
            // 定义表单登录 - 身份认证的方式
            .formLogin()
            .loginPage("/authentication/require")
            .loginProcessingUrl("/authentication/form")
            .successHandler(myAuthenticationSuccessHandler)

myAuthenticationSuccessHandler 的编写

    /**
     * .formLogin().successHandler() 中需要的处理器类型
     * @author zhuqiang
     * @version 1.0.1 2018/8/3 16:29
     * @date 2018/8/3 16:29
     * @since 1.0
     */
    @Component("myAuthenticationSuccessHandler")
    public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
        private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    
        //  com.fasterxml.jackson.databind.
        // spring 是使用jackson来进行处理返回数据的
        // 所以这里可以得到他的实例
        @Autowired
        private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
    
        /**
         * @param request
         * @param response
         * @param authentication 封装了所有的认证信息
         * @throws IOException
         * @throws ServletException
         */
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            logger.info("登录成功");
    
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
        }
    }

查看输出的authentication

    {
        "authorities": [
            {
                "authority": "admin"
            }
        ],
        "details": {
            "remoteAddress": "0:0:0:0:0:0:0:1",
            "sessionId": "FE0F33577E7E5D89AF15FCCD6FE5A4B3"
        },
        "authenticated": true,
        "principal": {
            "password": null,
            "username": "admin",
            "authorities": [
                {
                    "authority": "admin"
                }
            ],
            "accountNonExpired": true,
            "accountNonLocked": true,
            "credentialsNonExpired": true,
            "enabled": true
        },
        "credentials": null,
        "name": "admin"
    }
    @Component("myAuthenticationSuccessHandler")
    public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
        private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());
    
        //  com.fasterxml.jackson.databind.
        // spring 是使用jackson来进行处理返回数据的
        // 所以这里可以得到他的实例
        @Autowired
        private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
    
        @Autowired
        private SecurityProperties securityProperties;
    
        /**
         * @param request
         * @param response
         * @param authentication 封装了所有的认证信息
         * @throws IOException
         * @throws ServletException
         */
        @Override
        public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
            logger.info("登录成功");
            if (securityProperties.getBrowser().getLoginType() == LoginType.JSON) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write(objectMapper.writeValueAsString(authentication));
            } else {
                // 把本类实现父类改成 AuthenticationSuccessHandler 的子类 SavedRequestAwareAuthenticationSuccessHandler
                // 之前说spring默认成功是跳转到登录前的url地址
                // 就是使用的这个类来处理的
                super.onAuthenticationSuccess(request, response, authentication);
            }
        }
    }

这样登录成功的就ok了。
对于失败的来说是一样的,继承的父类改成spring默认的处理器

    org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler
阅读全文