SpringSecurity认证的源码解析

SpringSecurity认证的源码解析

认证处理流程

认证过程涉及到的类

在UsernamePasswordAuthenticationFilter类的处理

1.首先经过的是一个UsernamePasswordAuthenticationFilter过滤器,该过滤器在获取到用户名和密码之后就去构建一个 UsernamePasswordAuthenticationToken的对象,该对象是Authentication(即用户的认证信息) UsernamePasswordAuthenticationFilter.java

UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

UsernamePasswordAuthenticationToken.java

 public UsernamePasswordAuthenticationToken(Object principal, Object credentials) {
 		// 这个地方调用父类的该AbstractAuthenticationToken(Collection<? extends GrantedAuthority> authorities),但是该方法需要传递一组权限进来,在验证玩之前还是没有任何权限信息的,所以传递一个空进来。
		super((Collection)null);
		//对应用户名
		this.principal = principal;
		//对应密码
		this.credentials = credentials;
		//表示信息没经过任何认证,所以是false
		this.setAuthenticated(false);
	}

UsernamePasswordAuthenticationFilter.java

//将请求的信息放入上面生成的UsernamePasswordAuthenticationToken里面
this.setDetails(request, authRequest);

在AuthenticationManager里面处理的流程

直接调用了它的子类(ProviderManager)的authenticate方法return this.getAuthenticationManager().authenticate(authRequest);

ProviderManager的处理流程

   public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Class<? extends Authentication> toTest = authentication.getClass();
		AuthenticationException lastException = null;
		Authentication result = null;
		boolean debug = logger.isDebugEnabled();
		Iterator var6 = this.getProviders().iterator();
		//遍历是否支持当前的校验方式
		while(var6.hasNext()) {
			AuthenticationProvider provider = (AuthenticationProvider)var6.next();
			//对校验方式进行判断。
			if (provider.supports(toTest)) {
				if (debug) {
					logger.debug("Authentication attempt using " + provider.getClass().getName());
				}

				try {
					result = provider.authenticate(authentication);
					if (result != null) {
						this.copyDetails(authentication, result);
						break;
					}
				} catch (AccountStatusException var11) {
					this.prepareException(var11, authentication);
					throw var11;
				} catch (InternalAuthenticationServiceException var12) {
					this.prepareException(var12, authentication);
					throw var12;
				} catch (AuthenticationException var13) {
					lastException = var13;
				}
			}
		}

		if (result == null && this.parent != null) {
			try {
				result = this.parent.authenticate(authentication);
			} catch (ProviderNotFoundException var9) {
				;
			} catch (AuthenticationException var10) {
				lastException = var10;
			}
		}

		if (result != null) {
			if (this.eraseCredentialsAfterAuthentication && result instanceof CredentialsContainer) {
				((CredentialsContainer)result).eraseCredentials();
			}

			this.eventPublisher.publishAuthenticationSuccess(result);
			return result;
		} else {
			if (lastException == null) {
				lastException = new ProviderNotFoundException(this.messages.getMessage("ProviderManager.providerNotFound", new Object[]{toTest.getName()}, "No AuthenticationProvider found for {0}"));
			}

			this.prepareException((AuthenticationException)lastException, authentication);
			throw lastException;
		}
	}

这段代码遍历循环判断是否支持该认证方式。

result = provider.authenticate(authentication);

在AbstractUserDetailsAuthenticationProvider.java里面

  public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
		String username = authentication.getPrincipal() == null ? "NONE_PROVIDED" : authentication.getName();
		boolean cacheWasUsed = true;
		UserDetails user = this.userCache.getUserFromCache(username);
		if (user == null) {
			cacheWasUsed = false;

			try {
			//获取到用户的信息(UserDetails)
				user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
			} catch (UsernameNotFoundException var6) {
				this.logger.debug("User '" + username + "' not found");
				if (this.hideUserNotFoundExceptions) {
					throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
				}

				throw var6;
			}

			Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
		}

		try {
			this.preAuthenticationChecks.check(user);
			this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
		} catch (AuthenticationException var7) {
			if (!cacheWasUsed) {
				throw var7;
			}

			cacheWasUsed = false;
			user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
			this.preAuthenticationChecks.check(user);
			this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
		}

		this.postAuthenticationChecks.check(user);
		if (!cacheWasUsed) {
			this.userCache.putUserInCache(user);
		}

		Object principalToReturn = user;
		if (this.forcePrincipalAsString) {
			principalToReturn = user.getUsername();
		}

		return this.createSuccessAuthentication(principalToReturn, authentication, user);
	}

result = provider.authenticate(authentication)调用的实际上是调用DaoAuthenticationProvider的authenticate(authentication),该方法里面调用了 loadedUser = this.getUserDetailsService().loadUserByUsername(username);实际上是调用我们自己写的UserDetailService的实现类。这个时候就获取到了UserDetail对象了: MyDetailService.java

@Component//TODO 使之成为用户的bean
public class MyDetailService implements UserDetailsService {
	@Autowired
	PasswordEncoder passwordEncoder;

	Logger logger = LoggerFactory.getLogger(MyDetailService.class);
	[@Override](https://my.oschina.net/u/1162528)
	public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
		//TODO 根据用户名查找用户信息
		logger.info("登陆用户名:"+s);
		String encode = passwordEncoder.encode("123456");
		logger.info("登陆用户名:"+encode);
		return new User(s,encode,true,true,true,true, AuthorityUtils.createAuthorityList("admin"));
	}
}

AbstractUserDetailsAuthenticationProvider.java里面进行前置,附加,后置检查。

	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		Assert.isInstanceOf(UsernamePasswordAuthenticationToken.class, authentication, this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.onlySupports", "Only UsernamePasswordAuthenticationToken is supported"));
		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 = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
			} catch (UsernameNotFoundException var6) {
				this.logger.debug("User '" + username + "' not found");
				if (this.hideUserNotFoundExceptions) {
					throw new BadCredentialsException(this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
				}

				throw var6;
			}

			Assert.notNull(user, "retrieveUser returned null - a violation of the interface contract");
		}

		try {
			//预检查
			this.preAuthenticationChecks.check(user);
			//附加检查
			this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
		} catch (AuthenticationException var7) {
			if (!cacheWasUsed) {
				throw var7;
			}

			cacheWasUsed = false;
			user = this.retrieveUser(username, (UsernamePasswordAuthenticationToken)authentication);
			this.preAuthenticationChecks.check(user);
			this.additionalAuthenticationChecks(user, (UsernamePasswordAuthenticationToken)authentication);
		}
		//后置检查
		this.postAuthenticationChecks.check(user);
		if (!cacheWasUsed) {
			this.userCache.putUserInCache(user);
		}

		Object principalToReturn = user;
		if (this.forcePrincipalAsString) {
			principalToReturn = user.getUsername();
		}
		//成功创建
		return this.createSuccessAuthentication(principalToReturn, authentication, user);
	}

this.createSuccessAuthentication(principalToReturn, authentication, user)方法如下:

   protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
		UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(), this.authoritiesMapper.mapAuthorities(user.getAuthorities()));
		result.setDetails(authentication.getDetails());
		return result;
	}

该方法从新创建了一个UsernamePasswordAuthenticationToken对象,该对象已经带有认证的信息。

此时调用的构造函数如下

	public UsernamePasswordAuthenticationToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
		//此时具备了权限了信息
		super(authorities);
		this.principal = principal;
		this.credentials = credentials;
		//此时已经校验通过了。
		super.setAuthenticated(true);
	}

到这里已经完成认证获取到了我们需要的Authentication实例对象,需要沿着图返回去。

在AbstractAuthenticationProcessingFilter.java的public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)里面调用了successfulAuthentication(request, response, chain, authResult);这个方法就是调用我们自己写的成功处理器。如果期间出错就会调用我们自己创建的失败处理器。

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
		throws IOException, ServletException {

	HttpServletRequest request = (HttpServletRequest) req;
	HttpServletResponse response = (HttpServletResponse) res;

	if (!requiresAuthentication(request, response)) {
		chain.doFilter(request, response);

		return;
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Request is to process authentication");
	}

	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);
	}
	catch (InternalAuthenticationServiceException failed) {
		logger.error(
				"An internal error occurred while trying to authenticate the user.",
				failed);
		unsuccessfulAuthentication(request, response, failed);

		return;
	}
	catch (AuthenticationException failed) {
		// Authentication failed
		unsuccessfulAuthentication(request, response, failed);

		return;
	}

	// Authentication success
	if (continueChainBeforeSuccessfulAuthentication) {
		chain.doFilter(request, response);
	}

	successfulAuthentication(request, response, chain, authResult);
}

protected void successfulAuthentication(HttpServletRequest request,
		HttpServletResponse response, FilterChain chain, Authentication authResult)
		throws IOException, 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(new InteractiveAuthenticationSuccessEvent(
				authResult, this.getClass()));
	}
	//调用我们自己的处理器
	successHandler.onAuthenticationSuccess(request, response, authResult);
}

认证结果在多个请求之间共享

认证请求缓存的过程

认证流程中SecurityPersistenceFilter的位置

protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {

	if (logger.isDebugEnabled()) {
		logger.debug("Authentication success. Updating SecurityContextHolder to contain: "
				+ authResult);
	}
	//将认证放入了SecurityContext类中然后将SecurityContext放入SecurityContextHolder里面。
	SecurityContextHolder.getContext().setAuthentication(authResult);

	rememberMeServices.loginSuccess(request, response, authResult);

	// Fire event
	if (this.eventPublisher != null) {
		eventPublisher.publishEvent(new InteractiveAuthenticationSuccessEvent(
				authResult, this.getClass()));
	}

	successHandler.onAuthenticationSuccess(request, response, authResult);
}

SecurityContext类实际上是Authentication的包装。

SecurityContextHolder实际上是ThreadLocal的实现,使得认证的信息在线程的其他方法都可以获取。

SecurityContextPersistenceFilter进来的时候检查session是否有认证信息,有就放入线程,后面的类,方法都可以使用,没有就直接进入后的过滤器进行校验。响应的时候就检查线程是否有有验证信息,有就放入session

获取用户信息

@GetMapping("getAuthentication")
 public Authentication getAuthentication(){
	return SecurityContextHolder.getContext().getAuthentication();
}

	@GetMapping("getAuthentication2")
	public Object getAuthentication2(@AuthenticationPrincipal UserDetails userDetails){
		return userDetails;
	}

猜你喜欢

转载自my.oschina.net/u/3474937/blog/2965723