自定义Spring Security的身份验证失败处理

1.概述

在本快速教程中,我们将演示如何在Spring Boot应用程序中自定义Spring Security的身份验证失败处理。目标是使用表单登录方法对用户进行身份验证。

2.认证和授权(Authentication and Authorization)

身份验证和授权通常结合使用,因为它们在授予系统访问权限时起着重要且同样重要的作用

但是,它们具有不同的含义,并在验证请求时应用不同的约束

  • 身份验证 - 在授权之前;它是关于验证收到的凭证;我们验证用户名和密码是否与我们的应用程序识别的用户名和密码相匹配
  • 授权 - 用于验证成功通过身份验证的用户是否有权访问应用程序的某个功能

我们可以自定义身份验证和授权失败处理,但是,在此应用程序中,我们将专注于身份验证失败。

3. Spring Security的AuthenticationFailureHandler

Spring Security提供了一个默认处理身份验证失败的组件。

但是,我们发现于默认行为不足以满足实际要求的情况是很常见的。
如果是这种情况,我们可以创建自己的组件并通过实现AuthenticationFailureHandler接口提供我们想要的自定义行为

public class CustomAuthenticationFailureHandler 
  implements AuthenticationFailureHandler {
  
    private ObjectMapper objectMapper = new ObjectMapper();
 
    @Override
    public void onAuthenticationFailure(
      HttpServletRequest request,
      HttpServletResponse response,
      AuthenticationException exception) 
      throws IOException, ServletException {
  
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Map<String, Object> data = new HashMap<>();
        data.put(
          "timestamp", 
          Calendar.getInstance().getTime());
        data.put(
          "exception", 
          exception.getMessage());
 
        response.getOutputStream()
          .println(objectMapper.writeValueAsString(data));
    }
}

默认情况下,Spring使用包含错误信息的请求参数将用户重定向回登录页面

在此应用程序中,我们将返回401响应,其中包含有关错误的信息以及错误发生的时间戳。

  • DelegatingAuthenticationFailureHandler将AuthenticationException子类委托给不同的AuthenticationFailureHandler,这意味着我们可以为AuthenticationException的不同实例创建不同的行为
  • ExceptionMappingAuthenticationFailureHandler根据AuthenticationException的完整类名将用户重定向到特定的URL
  • 无论AuthenticationException的类型如何,ForwardAuthenticationFailureHandler都会将用户转发到指定的URL
  • SimpleUrlAuthenticationFailureHandler是默认使用的组件,如果指定,它会将用户重定向到failureUrl;否则,它只会返回401响应

现在我们已经创建了自定义AuthenticationFailureHandler,让我们配置我们的应用程序并覆盖Spring的默认处理程序

@Configuration
@EnableWebSecurity
public class SecurityConfiguration 
  extends WebSecurityConfigurerAdapter {
 
    @Override
    protected void configure(AuthenticationManagerBuilder auth) 
      throws Exception {
        auth
          .inMemoryAuthentication()
          .withUser("baeldung")
          .password("baeldung")
          .roles("USER");
    }
 
    @Override
    protected void configure(HttpSecurity http) 
      throws Exception {
        http
          .authorizeRequests()
          .anyRequest()
          .authenticated()
          .and()
          .formLogin()
          .failureHandler(customAuthenticationFailureHandler());
    }
 
    @Bean
    public AuthenticationFailureHandler customAuthenticationFailureHandler() {
        return new CustomAuthenticationFailureHandler();
    }
}

注意failureHandler()调用,我们可以告诉Spring使用我们的自定义组件而不是使用默认组件。

4.结论

在此示例中,我们使用Spring的AuthenticationFailureHandler接口自定义了应用程序的身份验证失败处理程序

在Github项目中找到此示例的实现

在本地运行时,您可以在localhost:8080上访问和测试应用程序.

转载于:https://www.cnblogs.com/xjknight/p/10949636.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security中进行身份验证可以通过以下步骤来实现: 1. 添加Spring Security依赖:在项目的构建文件中添加Spring Security的依赖,例如在Maven项目中可以在pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 2. 配置Spring Security:创建一个配置类,继承自`WebSecurityConfigurerAdapter`,并重写`configure`方法来配置安全策略。在该方法中,你可以定义哪些URL需要进行身份验证,以及使用哪种身份验证方式。例如,可以使用基于表单的身份验证或基于HTTP Basic的身份验证。 3. 定义用户和角色:在配置类中,你可以定义用户和角色,并将其与相应的权限关联起来。可以使用内存存储、数据库存储或自定义的用户存储方式来定义用户和角色。 4. 自定义登录页面:如果你选择使用基于表单的身份验证,可以自定义登录页面。可以创建一个登录页面模板,并在配置类中指定该模板的路径。 5. 处理登录请求:当用户提交登录表单时,Spring Security会自动处理登录请求,并进行身份验证。你可以根据需要自定义登录成功或失败后的处理逻辑。 6. 保护资源:通过配置类,你可以定义哪些URL需要进行身份验证,并指定访问这些URL所需的角色或权限。可以使用注解或配置方式来实现。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值