Spring Security3源码分析-RememberMeAuthenticationFilter分析

RememberMeAuthenticationFilter过滤器对应的类路径为
org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter
看主要的doFilter方法

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//判断SecurityContext实例中是否存在Authentication认证信息
//没有认证的情况,才会做autoLogin的操作
if (SecurityContextHolder.getContext().getAuthentication() == null) {
//具体autoLogin过程后面分析,主要返回一个认证实体Authentication
Authentication rememberMeAuth = rememberMeServices.autoLogin(request, response);

if (rememberMeAuth != null) {
// Attempt authenticaton via AuthenticationManager
try {
//通过authenticationManager对该认证实体验证
//之前登录的Filter已经说明了,authenticationManager将
//将具体的认证工作交给provider完成
//而provider只负责自己关心的认证实体
//所以返回的认证实体RememberMeAuthenticationToken由
//RememberMeAuthenticationProvider完成认证的工作
//而这个provider也仅仅判断key是否相同,然后直接返回Authentication
rememberMeAuth = authenticationManager.authenticate(rememberMeAuth);

//设置认证信息到SecurityContext中
SecurityContextHolder.getContext().setAuthentication(rememberMeAuth);
//登录成功后的处理
onSuccessfulAuthentication(request, response, rememberMeAuth);
// Fire event
if (this.eventPublisher != null) {
eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
SecurityContextHolder.getContext().getAuthentication(), this.getClass()));
}
} catch (AuthenticationException authenticationException) {
……
}
}

chain.doFilter(request, response);
} else {
……
chain.doFilter(request, response);
}
}

下面看具体的autoLogin执行过程。
autoLogin是由RememberMeServices接口定义的方法,那么在RememberMeAuthenticationFilter类中的RememberMeServices实例也是通过解析http标签时注入到Filter中的。具体解析过程代码就不分析了。
如果remember-me标签有data-source-ref或token-repository-ref属性,RememberMeServices接口实现类为
PersistentTokenBasedRememberMeServices
其他情况下,没有设置services-ref属性,RememberMeServices接口实现类为
TokenBasedRememberMeServices
这两个实现类都继承了AbstractRememberMeServices抽象类

而autoLogin是AbstractRememberMeServices类完成的,看源码

public final Authentication autoLogin(HttpServletRequest request, HttpServletResponse response) {
//从cookie中获取remember me的相关信息
//cookie名称是SPRING_SECURITY_REMEMBER_ME_COOKIE
//cookie的value实际上是经过Base64做了两次编码算法处理的结果
//对应的是数据库中persistent_logins表中的series、token的数据
//数据库中保存的值是经过一次Base64编码的处理
String rememberMeCookie = extractRememberMeCookie(request);

if (rememberMeCookie == null) {
return null;
}

logger.debug("Remember-me cookie detected");

UserDetails user = null;

try {
//所以这里只要解码一次就可以了
//这个数组中包含两个字符串,分别对应persistent_logins
//表中的series、token的数据
String[] cookieTokens = decodeCookie(rememberMeCookie);
//执行autoLogin的处理
user = processAutoLoginCookie(cookieTokens, request, response);
//账号状态检查,主要检查是否被锁,是否可用等
userDetailsChecker.check(user);

logger.debug("Remember-me cookie accepted");
//返回UserDetails的实现类RememberMeAuthenticationToken
//注意这里构造的不是之前登录的那个UsernamePasswordAuthenticationToken了
return createSuccessfulAuthentication(request, user);
} catch (CookieTheftException cte) {
cancelCookie(request, response);
throw cte;
} catch (UsernameNotFoundException noUser) {
logger.debug("Remember-me login was valid but corresponding user not found.", noUser);
} catch (InvalidCookieException invalidCookie) {
logger.debug("Invalid remember-me cookie: " + invalidCookie.getMessage());
} catch (AccountStatusException statusInvalid) {
logger.debug("Invalid UserDetails: " + statusInvalid.getMessage());
} catch (RememberMeAuthenticationException e) {
logger.debug(e.getMessage());
}

cancelCookie(request, response);
return null;
}


继续跟踪processAutoLoginCookie方法,该方法由具体子类实现,下面的代码从
PersistentTokenBasedRememberMeServices中截取

protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest request, HttpServletResponse response) {

if (cookieTokens.length != 2) {
throw new InvalidCookieException("Cookie token did not contain " + 2 +
" tokens, but contained '" + Arrays.asList(cookieTokens) + "'");
}
final String presentedSeries = cookieTokens[0];
final String presentedToken = cookieTokens[1];
//根据cookie中获取的Series数据从持久化载体(一般为数据库)中
//获取该Series对应的登录信息,构造PersistentRememberMeToken实例
PersistentRememberMeToken token = tokenRepository.getTokenForSeries(presentedSeries);
//此处省略一部分验证……
//重新产生一个token并由当前时间构造新的PersistentRememberMeToken实例
PersistentRememberMeToken newToken = new PersistentRememberMeToken(token.getUsername(),
token.getSeries(), generateTokenData(), new Date());

try {
//根据Series更新persistent_logins
tokenRepository.updateToken(newToken.getSeries(), newToken.getTokenValue(), newToken.getDate());
//重新设置cookie
addCookie(newToken, request, response);
} catch (DataAccessException e) {
logger.error("Failed to update token: ", e);
throw new RememberMeAuthenticationException("Autologin failed due to data access problem");
}
//直接根据username通过UserDetailsService实例的loadUserByUsername方法
//获取UserDetails对象并返回
UserDetails user = getUserDetailsService().loadUserByUsername(token.getUsername());

return user;
}


这里需要注意的是getUserDetailsService方法返回的userDetailsService变量从哪里注入进来的呢?通过解析remember标签构造bean时注入的么?不是的,进一步观察remember标签解析代码

public BeanDefinition parse(Element element, ParserContext pc) {
//此处省略了获取标签属性、判断等代码
boolean isPersistent = dataSourceSet | tokenRepoSet;
//如果配置了data-source-ref或token-repository-ref属性
if (isPersistent) {
Object tokenRepo;
services = new RootBeanDefinition(PersistentTokenBasedRememberMeServices.class);

if (tokenRepoSet) {
tokenRepo = new RuntimeBeanReference(tokenRepository);
} else {
//设置data-source-ref属性的情况
tokenRepo = new RootBeanDefinition(JdbcTokenRepositoryImpl.class);
((BeanDefinition)tokenRepo).getPropertyValues().addPropertyValue("dataSource",
new RuntimeBeanReference(dataSource));
}
//tokenRepository主要处理存储的功能
services.getPropertyValues().addPropertyValue("tokenRepository", tokenRepo);
} else if (!servicesRefSet) {
services = new RootBeanDefinition(TokenBasedRememberMeServices.class);
}

if (services != null) {
//注意:这里仅仅判断是否配置了user-service-ref属性
//如果配置了该属性,就会注入userDetailsService
//实际上很少配置该标签
if (userServiceSet) {
services.getPropertyValues().addPropertyValue("userDetailsService", new RuntimeBeanReference(userServiceRef));
}

if ("true".equals(element.getAttribute(ATT_SECURE_COOKIE))) {
services.getPropertyValues().addPropertyValue("useSecureCookie", true);
}

if (tokenValiditySet) {
Integer tokenValidity = new Integer(tokenValiditySeconds);
if (tokenValidity.intValue() < 0 && isPersistent) {
pc.getReaderContext().error(ATT_TOKEN_VALIDITY + " cannot be negative if using" +
" a persistent remember-me token repository", source);
}
services.getPropertyValues().addPropertyValue("tokenValiditySeconds", tokenValidity);
}
services.setSource(source);
services.getPropertyValues().addPropertyValue("key", key);
servicesName = pc.getReaderContext().generateBeanName(services);
pc.registerBeanComponent(new BeanComponentDefinition(services, servicesName));
} else {
servicesName = rememberMeServicesRef;
}

if (StringUtils.hasText(element.getAttribute(ATT_SERVICES_ALIAS))) {
pc.getRegistry().registerAlias(servicesName, element.getAttribute(ATT_SERVICES_ALIAS));
}

BeanDefinition filter = createFilter(pc, source);
pc.popAndRegisterContainingComponent();

return filter;
}


上面的解析过程已经很明确了,确实没有在这里注入userDetailsService。如果细心的话,会发现在解析http标签时,有这么一段代码

authBldr.createUserServiceInjector();

没错,就是这个方法完成动态注入的了

void createUserServiceInjector() {
BeanDefinitionBuilder userServiceInjector = BeanDefinitionBuilder.rootBeanDefinition(UserDetailsServiceInjectionBeanPostProcessor.class);
userServiceInjector.addConstructorArgValue(x509ProviderId);
userServiceInjector.addConstructorArgValue(rememberMeServicesId);
userServiceInjector.addConstructorArgValue(openIDProviderId);
userServiceInjector.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
pc.getReaderContext().registerWithGeneratedName(userServiceInjector.getBeanDefinition());
}

UserDetailsServiceInjectionBeanPostProcessor实现了两个接口BeanPostProcessor, BeanFactoryAware,既可以动态改变bean,又能直接获取到BeanFactory对象再从ioc容器中获取具体的bean。
主要看postProcessBeforeInitialization方法

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(beanName == null) {
return bean;
}
if (beanName.equals(x509ProviderId)) {
injectUserDetailsServiceIntoX509Provider((PreAuthenticatedAuthenticationProvider) bean);
} else if (beanName.equals(rememberMeServicesId)) {
injectUserDetailsServiceIntoRememberMeServices(bean);
} else if (beanName.equals(openIDProviderId)) {
injectUserDetailsServiceIntoOpenIDProvider(bean);
}

return bean;
}

只对x509ProviderId、rememberMeServicesId、openIDProviderId的bean动态注入userDetailsService实例。

你可能感兴趣的:(Spring,Security)