canna-cloud【十五】Spring Security 自定义异常返回结果,前后端分离,异常拦截

本文详细介绍了如何在Spring Security中配置异常处理,包括UserNotFoundException的显示、AccessDeniedHandler的自定义及各类AuthenticationException的个性化响应。通过具体代码示例,展示了如何设置DaoAuthenticationProvider以抛出UserNotFoundException,如何自定义AccessDeniedHandler来处理访问被拒绝的情况,以及如何通过CannaAuthenticationFailureHandler类来针对不同类型的AuthenticationException进行定制化的错误响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、UserNotFoundExceptions未抛出

@Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setUserDetailsService(memberDetailsService);
        daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
        return daoAuthenticationProvider;
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider());
    }

注意:

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider());
}

不能修改成:

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(daoAuthenticationProvider()).userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder);
}

2、AccessDeniedHandler异常自定义拦截

.exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler)

3、其余异常自定义拦截,AuthenticationException 自定义处理


public class CannaAuthenticationFailureHandler implements
        AuthenticationFailureHandler {
	public CannaAuthenticationFailureHandler() {
	}

	/**
	 * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise
	 * returns a 401 error code.
	 * <p>
	 * If redirecting or forwarding, {@code saveException} will be called to cache the
	 * exception for use in the target view.
	 */
	public void onAuthenticationFailure(HttpServletRequest request,
			HttpServletResponse response, AuthenticationException authenticationException)
			throws IOException, ServletException {
		response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

		SecurityErrorType securityErrorType = null;
		if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
			securityErrorType = SecurityErrorType.USERNAME_PASSWORD_ERROR;
		} else if (authenticationException instanceof DisabledException) {
			securityErrorType = SecurityErrorType.USER_DISABLE;
		} else if (authenticationException instanceof LockedException) {
			securityErrorType = SecurityErrorType.ACCOUNT_LOCK;
		} else if (authenticationException instanceof AccountExpiredException) {
			securityErrorType = SecurityErrorType.ACCOUNT_EXPIRED;
		} else if (authenticationException instanceof CredentialsExpiredException) {
			securityErrorType = SecurityErrorType.CREDENTIALS_EXPIRED;
		} else {
			securityErrorType = SecurityErrorType.CHECK_AUTH_FAIL;
		}

		ErrorInfo errorJson = securityErrorType.toErrorInfo();
		ResponseUtils.writeResult(response, HttpStatus.INTERNAL_SERVER_ERROR, errorJson);
	}

}

// 类中重新设置错误执行类
    public UsernamePasswordAuthenticationFilter() {
        // do nothing
        super.setAuthenticationFailureHandler(new CannaAuthenticationFailureHandler());
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值