Spring Security CustomicationFailureHandler
最后修改:2020年8月20日
1.概述
在这个快速的教程中,我们将说明如何自定义Spring Security的在Spring Boot应用程序中处理身份验证失败。其目标是使用表单登录方法。
介绍Spring Security和表格登录在春靴子, 请参阅这和这物品分别。
2.身份验证和授权
验证和授权经常结合使用,因为在授予对系统的访问权限时,它们扮演重要的、同等重要的角色。
但是,当验证请求时,它们具有不同的含义并应用不同的约束:
- 验证- 前面授权;这是关于验金宝搏官网188be证收到的凭据;我们验证了用户名和密码是否与我们的应用程序识别的密码匹配
- 授权-它是关于验金宝搏官网188be证成功经过身份验证的用户是否具有访问应用程序某些功能的权限
我们可以定制两者身份验证和授权然而,在这个应用程序中,我们将重点关注身份验证失败。
3.春天安全AuthenticationFailureHandler
Spring Security提供默认情况下为我们处理身份验证故障的组件。
但是,在默认行为不足以满足要求的情况下,它并不罕见。
如果是这种情况,我们可以创建自己的组件,并通过实现我们想要的自定义行为AuthenticationFailureHandler界面:
公共类CustomAuthenticationFailureHandler实现身份验证FailureHandler {Private ObjectMapper ObjectMapper = New ObjectMapper();@override public void onauthenticationfailure(httpservletrequest请求,httpservletresponse响应,身份验证exception异常)抛出ioException,servletException {response.setstatus(httpstatus.unauthorized.value());地图<字符串,对象>数据= new hashmap <>();data.put(“timestamp”,calendar.getInstance()。GetTime());data.put(“例外”,例外.getmessage());Response.get.getOutputStream().println(objectMapper.writeValueAstring(数据));}}
默认,春天重定向用户返回登录页面请求参数包含有关错误的信息。金宝搏官网188be
在此应用程序中,我们将返回一个包含有关错误信息的401响应,以及其发生的时间戳。金宝搏官网188be
除了默认组件,春天有人可以使用我们可以利用的组件,具体取决于我们想要做的:
- DelegationAuthenticationFailureHandler.代表代表身份验证申请子类别不同AuthenticationFailureHandlers,意味着我们可以为不同的行为创造不同的行为身份验证申请
- ExceptionMappingAuthenticationFailureHandler.根据此文件将用户重定向到特定URLAuthenticationException全班名称名称
- ForwardAuthenticationFailureHandler无论类型的类型如何,都会将用户转发到指定的URL身份验证申请
- SimpleURLAUTHENTICATIONFAILURIUTHANDLER.是默认使用的组件,它将将用户重定向到a失败,如果指定;否则,它将简单地返回401响应
现在我们创造了我们的自定义AuthenticationFailureHandler,让我们配置我们的应用程序并覆盖春天默认处理程序:
@configuration @enableWebrity公共类SecurityConfiguration扩展WebSecurityConfigurerAdapter {@Override受保护的void配置(AuthenticationManagerBuilder Auth)抛出异常{auth.inmemoryauthentication().withuser(“user1”)。密码(passwordencoder.encode(“User1pass”))。角色(“用户”);@Override受保护的void配置(httpsecurity http)抛出异常{http .authorizeRequests().anyRequest().Authenticated().anand().bort().formlogin().failure handler(authenticationfailure handler());@Bean公共认证yailureHandler身份验证文件{return new customauthenticationfailure handler();@bean public passwordencoder passwordencoder(){return new bcryptpasswordencoder();}}
注意FallyHandler()打电话 - 这是我们可以告诉的春天使用我们的自定义组件,而不是使用默认组件。
4。结论
在本例中,我们定制了应用程序的身份验证失败处理程序Spring的身份验证yourureHandler.界面。
可以找到此示例的实现GitHub项目。
在本地运行时,您可以访问和测试应用程序localhost:8080