【Spring Security】AuthenticationFailureHandler 用户认证失败后处理


前言

AuthenticationFailureHandler 主要是做用户认证失败后调用的处理器,这里的失败一般是指用户名或密码错误。当出现错误后,该处理器就会被调用,一般在开发中,会自己实现一个处理器,用来给前端返回一些已经商量好的异常码,下面分成两大块,先简单介绍一下官方给的一些用户失败后的处理器,再介绍我们自己实现的自定义处理器。



简单介绍官方默认用户认证失败后处理器

SimpleUrlAuthenticationFailureHandler

当认证失败后,重定向到一个指定的URL。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.failureHandler(authenticationFailureHandler());
}

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
	SimpleUrlAuthenticationFailureHandler handler = new SimpleUrlAuthenticationFailureHandler();
	// 认证失败后重定向的URL
	handler.setDefaultFailureUrl("/login?error=true");
	return handler;
}

ForwardAuthenticationFailureHandler

认证失败后转发到一个指定的URL。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.failureHandler(authenticationFailureHandler());
}

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
	// 认证失败后转发的URL
	return new ForwardAuthenticationFailureHandler("/login-error");
}

ExceptionMappingAuthenticationFailureHandler

认证失败中根据发生的异常类型映射到不同的处理逻辑或URL。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.failureHandler(authenticationFailureHandler());
}

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
	ExceptionMappingAuthenticationFailureHandler handler = new ExceptionMappingAuthenticationFailureHandler();
	
	// 定义异常到URL的映射
	Map<String, String> exceptionMappings = new HashMap<>();
	exceptionMappings.put(IOException.class.getName(), "/login?error=io");
	exceptionMappings.put(RuntimeException.class.getName(), "/login?error=runtime");
	// 更多映射...
	
	handler.setExceptionMappings(exceptionMappings);
	// 当找不到映射时默认的URL
	handler.setDefaultFailureUrl("/login?error=def");
	
	return handler;
}

DelegatingAuthenticationFailureHandler

认证过程中发生的异常来委派给不同的 AuthenticationFailureHandler 实现。

@Override
protected void configure(HttpSecurity http) throws Exception {
	CorsConfiguration configuration = new CorsConfiguration();
	configuration.setAllowCredentials(true);
	http
		// 登录
		.formLogin()
			// 认证失败后处理器
			.failureHandler(authenticationFailureHandler());
}

@Bean
public AuthenticationFailureHandler authenticationFailureHandler() {
	LinkedHashMap<Class<? extends AuthenticationException>, AuthenticationFailureHandler> failureHandlers = new LinkedHashMap<>();
	// 使用重定向
	failureHandlers.put(BadCredentialsException.class, new SimpleUrlAuthenticationFailureHandler("/login?error=bad_credentials"));
	// 使用转发
	failureHandlers.put(LockedException.class, new ForwardAuthenticationFailureHandler("/login-error"));
	// 更多映射...
	        
	return new DelegatingAuthenticationFailureHandler(
                failureHandlers,
                // 默认策略
                new SimpleUrlAuthenticationFailureHandler("/login?error=def"));
}


自定义使用

package com.security.handler.auth;

import com.alibaba.fastjson2.JSON;
import com.security.controller.vo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
@Slf4j
public class AuthenticationFailureHandlerImpl implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.info("AuthenticationFailureHandlerImpl 登录认证失败时调用 ...");
        
        /**
         * 设置响应状态值
         */
        response.setStatus(402);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        String json = JSON.toJSONString(
                ResponseResult.builder()
                        .code(402)
                        .message("认证失败!")
                        .build());

        // JSON信息
        response.getWriter().println(json);
    }

}

SecurityConfiguration 配置

package com.security.config;

import com.security.handler.auth.AuthenticationFailureHandlerImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.web.cors.CorsConfiguration;

@Configuration
@EnableWebSecurity
// 开启限制访问资源所需权限
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfigurationTest extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        http
                // 登录
                .formLogin()
                // 认证失败后处理器
                .failureHandler(authenticationFailureHandler());
    }

    @Bean
    public AuthenticationFailureHandler authenticationFailureHandler() {
    	// 自定义的失败后的处理器
        return new AuthenticationFailureHandlerImpl();
    }
}




End


  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Security 认证失败的原因可能有很多,下面列举一些常见的情况: 1. 用户名或密码错误:请检查用户输入的用户名和密码是否正确。 2. 认证服务器配置错误:请检查认证服务器的 URL 地址是否正确,以及服务器是否正在运行。 3. 证书问题:如果使用 HTTPS 进行认证,请确保服务器证书是有效的。 4. 访问限制:请检查是否存在 IP 地址或用户组限制,限制了该用户的访问权限。 5. 应用程序配置错误:请检查您的应用程序的 Spring Security 配置是否正确,是否启用了正确的认证方法。 如果仍然无法解决问题,建议查看应用程序和服务器的日志,以确定问题的具体原因。 ### 回答2: SpringSecurity认证可能失败的原因有很多,以下列举了一些可能的原因: 1. 用户名或密码错误:在登录时输入的用户名或密码与数据库中存储的用户信息不匹配,导致认证失败。此时需要确认输入的凭证信息是否正确,或者检查数据库中的用户信息是否准确。 2. 密码加密算法不匹配:SpringSecurity默认使用BCrypt算法对用户密码进行加密存储,如果数据库中的存储密码与用户输入的密码加密算法不匹配,会导致认证失败。此时可以尝试将数据库中的密码重新使用BCrypt算法进行加密。 3. 用户被锁定:在一些情况下,系统会对用户进行锁定,例如连续登录失败超过一定次数、账户过期等。当用户被锁定时,即使凭证信息正确,也会导致认证失败。此时需要检查用户是否被锁定,并解除锁定状态。 4. 认证过期:在一些场景下,认证信息可能会设置过期时间,当认证信息过期时,会导致认证失败。此时需要重新进行认证,或者延长认证信息的有效期。 5. 认证方式不匹配:SpringSecurity支持多种认证方式,例如表单认证、基于HTTP的认证、OAuth 2.0等。如果使用的认证方式与配置不匹配,也会导致认证失败。此时需要检查认证方式的配置,并确保与实际使用的方式相符。 以上仅列举了一些可能导致SpringSecurity认证失败的原因,具体失败原因需要根据实际情况进行分析和排查。可以通过查看错误日志、调试代码等方式来定位和解决认证失败的问题。 ### 回答3: Spring Security认证失败可能有多种原因。以下是一些可能导致认证失败的常见原因: 1. 用户名或密码错误:最常见的原因之一是用户提供的用户名或密码与存储在身份验证服务器上的凭据不匹配。在这种情况下,用户需要检查他们输入的凭据是否正确。 2. 用户账号被锁定:有时用户账号可能会被锁定,这可能是由于多次连续的认证失败引起的。在这种情况下,用户可能需要联系系统管理员以解锁账户。 3. 凭据过期或失效:用户的凭据(例如密码)可能已经过期或不再有效。这可能是由于系统要求用户定期更改密码或由于安全问题而导致的。用户需要按照系统要求更改凭据或联系系统管理员以获得有效的凭据。 4. 认证过程配置错误:如果Spring Security配置不正确,可能导致认证失败。这可能涉及到用户提供的凭据无法与配置文件中的凭据验证机制匹配,或者用户权限不正确等问题。用户需要检查Spring Security配置以确保准确性。 5. 服务器问题:在某些情况下,认证失败可能是由于身份验证服务器或相关服务的故障引起的。这可能意味着用户需要等待服务器恢复正常,或者需要联系系统管理员以解决服务器问题。 用户在遇到认证失败时应该首先检查自己提供的凭据是否正确,并尝试解决可能的身份验证问题。如果问题仍然存在,用户应该与系统管理员或支持团队联系以获取进一步的帮助。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值