spring security登录成功或失败返回json

前后端分离项目中 交互的往往是json 所以需要通过json告知前段登录是否成功

SpringSecurityConfig

修改SpringSecurityConfig (其他配置已经删除) 在其中配置AuthenticationFailureHandler ,AuthenticationSuccessHandler 

@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    private AuthenticationSuccessHandler customAuthenticationSuccessHandler;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 验证码过滤器
        http.addFilterBefore(imageCodeValidateFilter, UsernamePasswordAuthenticationFilter.class)
            // 跳转前台的地址
            .formLogin().loginPage("/loginPage")
            // 登录调用的接口地址
            .loginProcessingUrl("/login").successHandler(customAuthenticationSuccessHandler).failureHandler()
     
    }
}

AuthenticationFailureHandler与AuthenticationSuccessHandler 

主要就是实现SimpleUrlAuthenticationFailureHandler与CustomSavedRequestAwareAuthenticationSuccessHandler 接口 其余按照楼主的配置即可

@Component("customAuthenticationFailureHandler")
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    /**
     * @param exception 认证失败时抛出异常
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
        String referer = request.getHeader("Referer");
        logger.info("referer:" + referer);
        // 如果下面有值,则认为是多端登录,直接返回一个登录地址
        Object toAuthentication = request.getAttribute("toAuthentication");
        String lastUrl = toAuthentication != null ? /loginPage: StringUtils.substringBefore(referer, "?");
        logger.info("上一次请求的路径 :" + lastUrl);
        super.setDefaultFailureUrl(lastUrl + "?error");
        super.onAuthenticationFailure(request, response, exception);
    }
}
@Component("customAuthenticationSuccessHandler")
public class CustomAuthenticationSuccessHandler extends CustomSavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    Utils utils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SysUser sysUser = (SysUser)authentication.getPrincipal();
        logger.info("|" + "用户" + sysUser.getUsername() + "于" + sd.format(new Date()) + "通过web端登录系统,ip为"
            + utils.getIpAddr() + "。" + "|" + sd.format(new Date()) + "|" + sysUser.getUsername());
        super.onAuthenticationSuccess(request, response, authentication);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_20143059/article/details/113753086