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;
}