欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-05 17:13:40
1.概述 在本快速教程中,我们将演示如何在spring boot应用程序中自定义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源码: