当我们在使用 Spring Security 时,大多数时可能直接使用了系统默认的实现:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
或者最多按自己的逻辑实现 PasswordEncoder 接口:
public class MyPasswordEncoder implements PasswordEncoder {
private Logger logger = LoggerFactory.getLogger(getClass());
@Override
public String encode(CharSequence rawPassword) {
logger.debug("加密时待加密的密码:" + rawPassword.toString());
return rawPassword.toString() + "abc";
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
logger.debug("校验时待加密的密码:" + rawPassword.toString());
logger.debug("校验时已加密的密码:" + encodedPassword);
return encodedPassword.equals(rawPassword.toString() + "abc");
}
}
上述情况对一般情况都已经满足实际需要了,毕竟密码通常只是密码。
但是楼主遇到一个历史遗留问题,老系统中用户密码在数据库中保存的方式是:前端对明文密码 MD5后,后端接收到以后会拼接用户名后再做 MD5的方式保存到数据库中,先需要使新的认证方式可以支持历史数据的认证,因为不可能逐个修改历史数据,故想想解决方案也只能通过自定义 Spring Security 的认证逻辑下手了。
Spring Security 核心处理逻辑就是一串的过滤器,针对常见的用户名密码登录方式有一个 UsernamePasswordAuthenticationFilter,其核心方法就是:
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String username = obtainUsername(request);
String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
前面部分都只是参数的提取,封装,关键是最后一句 获取一个 AuthenticationManager 实例,并调用其 authenticate 方法进行验证。
AuthenticationManager 接口的实现类 ProviderManager 中实现了 authenticate 方法:
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass();
AuthenticationException lastException = null;
Authentication result = null;
boolean debug = logger.isDebugEnabled();
for (AuthenticationProvider provider : getProviders()) {
if (!provider.supports(toTest)) {
continue;
}
if (debug) {
logger.debug("Authentication attempt using "
+ provider.getClass().getName());
}
try {
result = provider.authenticate(authentication);
if (result != null) {
copyDetails(authentication, result);
break;
}
}
catch (AccountStatusException e) {
prepareException(e, authentication);
// SEC-546: Avoid polling additional providers if auth failure is due to
// invalid account status
throw e;
}
catch (InternalAuthenticationServiceException e) {
prepareException(e, authentication);
throw e;
}
catch (AuthenticationException e) {
lastException = e;
}
}
if (result == null && parent != null) {
// Allow the parent to try.
try {
result = parent.authenticate(authentication);
}
catch (ProviderNotFoundException e) {
// ignore as we will throw below if no other exception occurred prior to
// calling parent and the parent
// may throw ProviderNotFound even though a provider in the child already
// handled the request
}
catch (AuthenticationException e) {
lastException = e;
}
}
if (result != null) {
if (eraseCredentialsAfterAuthentication
&& (result instanceof CredentialsContainer)) {
// Authentication is complete. Remove credentials and other secret data
// from authentication
((CredentialsContainer) result).eraseCredentials();
}
eventPublisher.publishAuthenticationSuccess(result);
return result;
}
// Parent was null, or didn't authenticate (or throw an exception).
if (lastException == null) {
lastException = new ProviderNotFoundException(messages.getMessage(
"ProviderManager.providerNotFound",
new Object[] { toTest.getName() },
"No AuthenticationProvider found for {0}"));
}
prepareException(lastException, authentication);
throw lastException;
}
从方法中可以看到是遍历 AuthenticationProvider,通过 AuthenticationProvider 实例进行具体验证的,在循环时 会判断 AuthenticationProvider 是否和 Authentication 匹配:
if (!provider.supports(toTest)) {
continue;
}
因为 Spring Security 提供多种 Authentication 实现,每种 Authentication 实现都有相应的 AuthenticationProvider 实现对其验证。
通过查找 AuthenticationProvider 的实现类发现
AbstractUserDetailsAuthenticationProvider
抽象类里面有描述是用于 UsernamePasswordAuthenticationToken 的验证的:
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication,
messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.onlySupports",
"Only UsernamePasswordAuthenticationToken is supported"));
// Determine username
String username = (authentication.getPrincipal() == null) ? "NONE_PROVIDED"
: authentication.getName();
boolean cacheWasUsed = true;
UserDetails user = this.userCache.getUserFromCache(username);
if (user == null) {
cacheWasUsed = false;
try {
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (UsernameNotFoundException notFound) {
logger.debug("User '" + username + "' not found");
if (hideUserNotFoundExceptions) {
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
else {
throw notFound;
}
}
Assert.notNull(user,
"retrieveUser returned null - a violation of the interface contract");
}
try {
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
}
catch (AuthenticationException exception) {
if (cacheWasUsed) {
// There was a problem, so try again after checking
// we're using latest data (i.e. not from the cache)
cacheWasUsed = false;
user = retrieveUser(username,
(UsernamePasswordAuthenticationToken) authentication);
preAuthenticationChecks.check(user);
additionalAuthenticationChecks(user,
(UsernamePasswordAuthenticationToken) authentication);
}
else {
throw exception;
}
}
postAuthenticationChecks.check(user);
if (!cacheWasUsed) {
this.userCache.putUserInCache(user);
}
Object principalToReturn = user;
if (forcePrincipalAsString) {
principalToReturn = user.getUsername();
}
return createSuccessAuthentication(principalToReturn, authentication, user);
}
其逻辑就是从数据库加载用户信息,然后调用 additionalAuthenticationChecks 方法进行验证,该方法是抽象方法,由子类实现,其子类是 DaoAuthenticationProvider:
protected void additionalAuthenticationChecks(UserDetails userDetails,
UsernamePasswordAuthenticationToken authentication)
throws AuthenticationException {
Object salt = null;
if (this.saltSource != null) {
salt = this.saltSource.getSalt(userDetails);
}
if (authentication.getCredentials() == null) {
logger.debug("Authentication failed: no credentials provided");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
String presentedPassword = authentication.getCredentials().toString();
if (!passwordEncoder.isPasswordValid(userDetails.getPassword(),
presentedPassword, salt)) {
logger.debug("Authentication failed: password does not match stored value");
throw new BadCredentialsException(messages.getMessage(
"AbstractUserDetailsAuthenticationProvider.badCredentials",
"Bad credentials"));
}
}
看到这里,其实解决方法已经有了,就是提供一个自定义的 AuthenticationProvider
实现类,重写该方法的逻辑, 此处不能通过继承
AbstractUserDetailsAuthenticationProvider 类,因为 只有 Authentication
对象中才有前端表单提交的数据,AbstractUserDetailsAuthenticationProvider 中已经是 UserDetails 了,实际是数据库中的用户信息了。
实现一个自定义的 AuthenticationProvider :
public class MyAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
// TODO
return null;
}
@Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class
.isAssignableFrom(authentication));
}
}
supports 方法必须写匹配 UsernamePasswordAuthenticationToken
配置使用自定义的 AuthenticationProvider:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.authenticationProvider(new MyAuthenticationProvider());
}