Spring Security中,接口AuthenticationManager用于抽象建模认证管理器,用于处理一个认证请求,也就是Spring Security中的Authentication认证令牌。
AuthenticationManager接口只定义了一个方法:
Authentication authenticate(Authentication authentication) throws AuthenticationException;
该方法接收一个认证令牌对象,也就是认证请求作为参数,如果其中的信息匹配到目标账号,则该方法返回同一个认证令牌对象,不过其中被认证过程填充了更多的账号信息,比如授权和用户详情等。
AuthenticationManager在认证过程中必须按以下顺序处理以下认证异常AuthenticationException :
DisabledException– 账号被禁用时抛出LockedException– 账号被锁定时抛出BadCredentialsException– 密码错误时抛出
Spring Security框架提供了AuthenticationManager的缺省实现ProviderManager。ProviderManager管理了多个身份管理源,或者叫做认证提供者AuthenticationProvider,用于认证用户。它自身不实现身份验证,而是逐一使用认证提供者进行认证,直到某一个认证提供者能够成功地验证该用户的身份(或者是已经尝试完了该集合中所有的认证提供者仍然不能认证该用户的身份)。通过ProviderManager,Spring Security能够为单个应用程序提供多种认证机制。
AuthenticationManager会在Spring Security应用配置阶段被构建,比如被某个WebSecurityConfigurerAdapter构建,然后在工作阶段被使用。比如一个基于用户名密码认证机制的Spring Web MVC + Spring Security应用,应用/容器启动过程中,AuthenticationManager构建后会被设置到基于用户名密码进行认证的安全过滤器UsernamePasswordAuthenticationFilter上,缺省情况下,当请求为访问地址/login的POST请求时,UsernamePasswordAuthenticationFilter就会认为这是一个用户认证请求,从而获取请求中的用户名/密码信息,使用AuthenticationManager认证该请求用户的身份。
源代码
源代码版本 : Spring Security Config 5.1.4.RELEASE
package org.springframework.security.authentication;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
/**
* Processes an Authentication request.
*
* @author Ben Alex
*/
public interface AuthenticationManager {
/**
* Attempts to authenticate the passed Authentication object, returning a
* fully populated Authentication object (including granted authorities)
* if successful.
*
* An AuthenticationManager must honour the following contract concerning
* exceptions:
*
* A DisabledException must be thrown if an account is disabled and the
* AuthenticationManager can test for this state.
* A LockedException must be thrown if an account is locked and the
* AuthenticationManager can test for account locking.
* A BadCredentialsException must be thrown if incorrect credentials are
* presented. Whilst the above exceptions are optional, an
* AuthenticationManager must always test credentials.
*
* Exceptions should be tested for and if applicable thrown in the order expressed
* above (i.e. if an account is disabled or locked, the authentication request is
* immediately rejected and the credentials testing process is not performed). This
* prevents credentials being tested against disabled or locked accounts.
*
* @param authentication the authentication request object
*
* @return a fully authenticated object including credentials
*
* @throws AuthenticationException if authentication fails
*/
Authentication authenticate(Authentication authentication)
throws AuthenticationException;
}
本文介绍SpringSecurity中的核心组件AuthenticationManager,用于处理认证请求并管理认证流程。文章详细解释了其工作原理,包括如何通过ProviderManager整合多种认证机制,并概述了认证过程中可能遇到的异常。
2021

被折叠的 条评论
为什么被折叠?



