spring security 自定义登录成功、失败处理

默认自定义配置

一、自定义成功处理器

使用继承SavedRequestAwareAuthenticationSuccessHandler类的方式?因为SavedRequestAwareAuthenticationSuccessHandler这个类记住了你上一次的请求路径,比如:你请求user.html。然后被拦截到了登录页,这时候你输入完用户名密码点击登录,会自动跳转到user.html,而不是主页面。
public class CoreAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
   private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ObjectMapper objectMapper;

	@Autowired
	private SecurityProperties securityProperties;

	private RequestCache requestCache = new HttpSessionRequestCache();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.web.authentication.
	 * AuthenticationSuccessHandler#onAuthenticationSuccess(javax.servlet.http.
	 * HttpServletRequest, javax.servlet.http.HttpServletResponse,
	 * org.springframework.security.core.Authentication)
	 */
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
			Authentication authentication) throws IOException, ServletException {

		logger.info("登录成功");

		if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
			response.setContentType("application/json;charset=UTF-8");
			String type = authentication.getClass().getSimpleName();
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(type)));
		} else {
			// 如果设置了singInSuccessUrl,总是跳到设置的地址上
			// 如果没设置,则尝试跳转到登录之前访问的地址上,如果登录前访问地址为空,则跳到网站根路径上
			if (StringUtils.isNotBlank(securityProperties.getBrowser().getSingInSuccessUrl())) {
				requestCache.removeRequest(request, response);
				setAlwaysUseDefaultTargetUrl(true);
				setDefaultTargetUrl(securityProperties.getBrowser().getSingInSuccessUrl());
			}
			super.onAuthenticationSuccess(request, response, authentication);
		}

	}

}

二、自定义失败处理器

public class CoreAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private ObjectMapper objectMapper;
	
	@Autowired
	private SecurityProperties securityProperties;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.web.authentication.AuthenticationFailureHandler#onAuthenticationFailure(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, org.springframework.security.core.AuthenticationException)
	 */
	@Override
	public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException exception) throws IOException, ServletException {
		
		logger.info("登录失败");
		
		if (LoginResponseType.JSON.equals(securityProperties.getBrowser().getSignInResponseType())) {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			response.setContentType("application/json;charset=UTF-8");
			response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(exception.getMessage())));
		}else{
			super.onAuthenticationFailure(request, response, exception);
		}
		
	}
}

三、处理成功/失败的配置类

@Configuration
public class CoreAuthenticationHandlerConfig {

    /**
     * 成功处理器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "authenticationSuccessHandler")
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
        return new CoreAuthenticationSuccessHandler();
    }

    /**
     * 失败处理器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean(name = "authenticationFailureHandler")
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new CoreAuthenticationFailureHandler();
    }
}

四、安全核心配置

@ConditionalOnProperty(prefix = "security.core.config", value = "enable", matchIfMissing = true)
@Configuration
public class ValidateSecurityCoreConfig extends WebSecurityConfigurerAdapter {
    /**
     * 失败处理器
     */
    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;
    /**
     * 成功处理器
     */
    @Autowired
    AuthenticationSuccessHandler authenticationSuccessHandler;
    

    @Autowired
    private AuthorizeConfigManager authorizeConfigManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin()
            .loginPage(ValidateCodeConstants.DEFAULT_UNAUTHENTICATION_URL)
            .loginProcessingUrl(DefaultLoginProcessingUrlEnum.FORM.url())
            .successHandler(authenticationSuccessHandler)
            .failureHandler(authenticationFailureHandler)
           
            .and()
            // 先加上这句话,否则登录的时候会出现403错误码,Could not verify the provided CSRF token because your session was not found.
            .csrf().disable();

     
    }
}

扩展配置

如果不使用上述默认定义的登录成功/失败处理,还可进行扩展,代码如下

public class AppAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        String username = ((UserDetails) authentication.getPrincipal()).getUsername();
        logger.info("username:【{}】", username);
        
        

        logger.info("登录成功!");

        
            
        // 生成token
        final String token = '生成token';

        // 存到redis
        
        response.setHeader("Authorization", "Bearer " + token);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(new ResponseEntity(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase()).data(authentication)));

    }

  
}
public class AppAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登录失败!");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR.value(), exception.getMessage()).data(null)));
    }
@Configuration
public class AppAuthenticationHandlerConfig {

    @Bean(name = "authenticationSuccessHandler")
    @ConditionalOnProperty(prefix = "security.app.success.handler", name = "enable", matchIfMissing = true)
    public AuthenticationSuccessHandler authenticationSuccessHandler() {
       return new AppAuthenticationSuccessHandler();
    }

    @Bean(name = "authenticationFailureHandler")
    @ConditionalOnProperty(prefix = "security.app.failure.handler", name = "enable", matchIfMissing = true)
    public AuthenticationFailureHandler authenticationFailureHandler() {
        return new AppAuthenticationFailureHandler();
    }
}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值