无标题文章
Spring Security认证系统浅析
标签:安全发布于 2017-05-26 12:42:47
Spring Security是个安全框架众所周知,同时也提供了一整套基于Web的认证机制和安全服务,当然如果你要通过其他协议的来实现安全服务,你也可以使用SpringSecurity来帮助你。
今天主要是讲解基于web端的安全认证机制,其他的留着以后有空再整理成博文。
首先SpringSecurity Web是基于它所提供的一整套Filter链来实现的,我们来看下它所提供的有哪些Filter:
在列表中可以看到,这些Filter链是有序的,而且自身所提供的Filter是无法更改顺序的,so what???当然,你都能任意更改顺序了,那我怎么能保证在不同的filter中拿到正确的数据呢,是吧?这些filter是SpringSecurity在启动时会默认注入到容器中的,你可以根据自身业务的需要在这些filter的before或after插入自己设计的filter。
那每一个Filter具体是做了什么工作,大家自行去查阅,这不是今天讲的重点,今天着重讲基于web的认证机制。
先来看看SpringSecurity中认证时的几个关键类:
org.springframework.security.web.context.SecurityContextRepository
org.springframework.security.web.context.SecurityContextPersistenceFilter
org.springframework.security.core.context.SecurityContextHolder
org.springframework.security.core.context.SecurityContextHolderStrategy
org.springframework.security.core.Authentication
首先来看下作为用户在login时的交互图,这个图确实太大了,已经尽量缩小了,但还是很大。
从图中我们可以看到,用户在请求服务时,首先会经过图中的SecurityContextPersistenceFilter(其实这个类在Filter链中是第二个被处理的),这个类是干嘛的呢,主要就是用于设置SecurityContext到SecurityContextHolder中,具体的我们通过图和源码一点点分析
首先看看SecurityContextPersistenceFilter.class
Authentication authResult;
try{
authResult = attemptAuthentication(request, response);
if(authResult ==null) {
// return immediately as subclass has indicated that it hasn't completed
// authentication
return;
}
sessionStrategy.onAuthentication(authResult, request, response);
}
successfulAuthentication(request, response, chain, authResult);
protectedvoidsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain, Authentication authResult)
throwsIOException, ServletException {
if(logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
+ authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if(this.eventPublisher !=null) {
eventPublisher.publishEvent(newInteractiveAuthenticationSuccessEvent(
authResult,this.getClass()));
}
successHandler.onAuthenticationSuccess(request, response, authResult);
}
Usernamepasswordauthenticationfilter代码
publicSecurityContextPersistenceFilter() {
this(newHttpSessionSecurityContextRepository());
}
publicSecurityContextPersistenceFilter(SecurityContextRepository repo) {
this.repo = repo;
}
我们可以看到这个类的构造方法是需要设置SecurityContextRepository的,默认会设置为HttpSessionSecurityContextRepository.class,这个东西是拿来干嘛的?是用于设置SecurityContext的存储机制的,这个类对于你每次使用SecurityContextHolder在getContext时是否能拿到正确的context起到了关键性的作用。可以看到默认使用HttpSession来实现SecutiryContext的存储。
接下来我们看看doFilter中干了些什么事:
HttpRequestResponseHolder holder =newHttpRequestResponseHolder(request,response);
// 这里可以看到从repo中取得SecurityContext,默认是从HttpSession里获取
SecurityContext contextBeforeChainExecution = repo.loadContext(holder);
try{
// 同时在这里将创建好的SecurityContext设置到SecurityContextHolder中 SecurityContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
}
再来看一下repo.loadCotext的实现。
// 先从Session里去读取是否存在SecurityContext
SecurityContext context = readSecurityContextFromSession(httpSession);
// 如果不存在将创建一个空的SecurityContext
if(context ==null) {
context = generateNewContext();
}
returncontext;
protectedSecurityContext generateNewContext() {
returnSecurityContextHolder.createEmptyContext();
}
privateSecurityContext readSecurityContextFromSession(HttpSession httpSession) {
Object contextFromSession = httpSession.getAttribute(springSecurityContextKey);
}
在这里可以看到如果Session是一个新的话,这里的ScurityContext会从SecurityContextHolder中去创建,在SecurityContextHolder中可以看到默认会通过ThreadLocalSecurityContextHolderStrategy创建一个基于ThreadLocal存储线程安全的SecurityContext,那当前线程中所拿到的SecurityContext均是同一个实例。
现在知道了SecurityContext是如何创建了之后,再回头来看SecurityContextPersistenceFilter中的doFilter实现
try{
// 在这里将创建好的SecurityContext设置到SecurityContextHolder中
SecurityContextHolder.setContext(contextBeforeChainExecution);
chain.doFilter(holder.getRequest(), holder.getResponse());
}
现在已经在chain.doFilter()之前已经完成了对SecurityContext的设置,接下来过滤器链继续执行,如果你在配置SecurityConfig中使用了UsernamePasswordAuthenticationFilter.class来实现对用户的认证,那我们将会进入到UsernamePasswordAuthenticationFilter的doFilter来实现认证
Authentication authResult;
try{
authResult = attemptAuthentication(request, response);
if(authResult ==null) {
// return immediately as subclass has indicated that it hasn't completed
// authentication
return;
}
sessionStrategy.onAuthentication(authResult, request, response);
}
successfulAuthentication(request, response, chain, authResult);
protectedvoidsuccessfulAuthentication(HttpServletRequest request,
HttpServletResponse response, FilterChain chain, Authentication authResult)
throwsIOException, ServletException {
if(logger.isDebugEnabled()) {
logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
+ authResult);
}
SecurityContextHolder.getContext().setAuthentication(authResult);
rememberMeServices.loginSuccess(request, response, authResult);
// Fire event
if(this.eventPublisher !=null) {
eventPublisher.publishEvent(newInteractiveAuthenticationSuccessEvent(
authResult,this.getClass()));
}
successHandler.onAuthenticationSuccess(request, response, authResult);
}
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);
}
一旦attemptAuthentication认证通过之后,可以在successfulAuthentication方法中可以看到调用了SecurityContextHolder.getContext().setAuthentication(authResult)来完成对用户的认证,到这里已经完成了基于SpringSecurity所提供的一套web完整的认证过程。
在这里就不对UsernamePasswordAuthenticationFilter里的认证机制做详细的阐述了,大家有兴趣的话自己去翻源码查看吧。还是比较简单里,里面设计到了AuthenticationManager、AuthenticationProvider、UserDetailsService等相关的类。
如果你使用的restful接口来实现认证的话,你也可以在验证之后构造一个Authentication实例,再通过SecurityContextHolder.getContext().setAuthentication( authentication )来实现对SpringSecurity的认证。