spring security 整个认证流程

spring security 整个认证流程

==在看本文之前最好能够写一篇Spring security的demo玩玩,否则可能会看不懂的=
几个重要接口介绍

  1. UserDetails:就是我们平时使用的User中比较重要的属性,封装成的接口,在Spring Security中大量操作的都是这个接口

  2. GrantedAuthority:相当于role的概念 在org.springframework.security.core.userdetails.User中有有这么一段创建List的代码

public UserBuilder roles(String... roles) {
			List<GrantedAuthority> authorities = new ArrayList<>(roles.length);
			for (String role : roles) {
				Assert.isTrue(!role.startsWith("ROLE_"), () -> role
						+ " cannot start with ROLE_ (it is automatically added)");
				authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
			}
			return authorities(authorities);
}
  1. Authentication: 代表着一个身份认证请求的令牌的接口,或者是代表着身份认证的一个主体(类似于用户之类的),这个里面储存了用户信息,角色信息等,我们可以查看其相关的实现类,一般实现类都是以token结尾的

Spring security 认证执行过程:

程序在登录的时候首先会调用DelegatingFilterProxy,通过DelegatingFilterProxy首先初始化FilterChainProxy,通过getFilters方法找到SecurityFilterChain中所有满足条件的filter

private List<Filter> getFilters(HttpServletRequest request) {
		for (SecurityFilterChain chain : filterChains) {
			if (chain.matches(request)) {
				return chain.getFilters();
			}
		}

		return null;
	}

然后通过FilterChainProxy的内部类VirtualFilterChain来调用刚才找到的filters的doFilter方法

VirtualFilterChain vfc = new VirtualFilterChain(fwRequest, chain, filters);
vfc.doFilter(fwRequest, fwResponse);

然后就调用各个filter
其中比较重要的一个filter: UsernamePasswordAuthenticationFilter主要就是操作我们认证功能的

以下图片流程就是filter指定的大体流程(图片来自网络)
在这里插入图片描述

UsernamePasswordAuthenticationFilter中执行的主要操作过程:

核心方法attemptAuthentication()找到通过form表单传输的username和password,生成UsernamePasswordAuthenticationToken
再通过AuthenticationManagerauthenticate(Authentication authentication)来认证刚才的token,如果认证成功返回一个Authentication,这个Authentication就是我们需要的在传输的时候的Authentication如果认证失败一般会抛出一个AuthenticationException

AuthenticationManager是一个接口,主要的实现类是ProviderManager,当然还有其他的实现类,但是其他的实现类都是内部类

providerManager其实就是管理AuthenticationProvider的,其中有比较重要的两个成员变量


private List<AuthenticationProvider> providers = Collections.emptyList();
private AuthenticationManager parent;

在ProviderManager中又会遍历providers,
其实最后真正实现认证功能的就是在AuthenticationProvider的authenticate(Authentication authentication),
如果在providers中没有找到可以认证的AuthenticationProvider,那么就会找parent去认证
执行代码如下:

/**
*其实可以看到认证成功就会返回一个Authentication,如果认证失败就是抛出异常
*/
public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		Class<? extends Authentication> toTest = authentication.getClass();
		AuthenticationException lastException = null;
		AuthenticationException parentException = null;
		Authentication result = null;
		Authentication parentResult = null;
		
		for (AuthenticationProvider provider : getProviders()) {
			if (!provider.supports(toTest)) {
				continue;
			}

			try {
                //遍历当前provider去认证
				result = provider.authenticate(authentication);

				if (result != null) {
					copyDetails(authentication, result);
					break;
				}
			}
			catch (AuthenticationException e) {
				lastException = e;
			}
		}

		if (result == null && parent != null) {
			
			try {
                //如果provider没有认证成功,那么久找到parent去认证
				result = parentResult = parent.authenticate(authentication);
			}
			catch (AuthenticationException e) {
				lastException = parentException = e;
			}
		}

		if (result != null) {
			if (eraseCredentialsAfterAuthentication
					&& (result instanceof CredentialsContainer)) {
				((CredentialsContainer) result).eraseCredentials();
			}
			if (parentResult == null) {
				eventPublisher.publishAuthenticationSuccess(result);
			}
			return result;
		}
        //一般不会到这一步,上面两步 result==null 和result!=null将基本情况已经包括进去了
		if (lastException == null) {
			lastException = new ProviderNotFoundException(messages.getMessage(
					"ProviderManager.providerNotFound",
					new Object[] { toTest.getName() },
					"No AuthenticationProvider found for {0}"));
		}
		if (parentException == null) {
			prepareException(lastException, authentication);
		}

		throw lastException;
	}

看到这里其实已经很晕了,饶了很多圈,

核心中的核心就是在AbstractUserDetailsAuthenticationProvider了,

它会委托子类(DaoAuthenticationProvider)做两件事,

  1. 找到数据库中当前用户的信息UserDetails
  2. 匹配当前密码和数据库中的信息是否匹配
    扎到UserDetails是在DaoAuthenticationProvider中的retrieveUser方法
protected final UserDetails retrieveUser(String username,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		prepareTimingAttackProtection();
		try {
            // 找用户信息是通过UserDetailService中的loadUserByUsername(String username)这个方法实现的,所依如果我们需要将自己的数据库和Spring security对接的话,那么就需要我们自己实现这个接口,然后将spring security中的userDetailService,指定为自己实现的userDetailService,具体操作如下
			UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
			if (loadedUser == null) {
				throw new InternalAuthenticationServiceException(
						"UserDetailsService returned null, which is an interface contract violation");
			}
			return loadedUser;
		}	
}

以下是指定自己的userDetailsService,需要在程序中配置的

/**
*security配置类,指定自己实现的UserDetailsService,如果不指定,spring security会从其默认实现类中找
*/
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   public UserDetailsService userDetailsServiceBean() throws Exception {
       return new MyUserDetailsService();
   }

   @Override
   public void configure(WebSecurity web) throws Exception {
       super.configure(web);
   }

   /**
    * 认证的一个过程
    * @param auth
    */
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetailsService());
   }
}

找到了用户详情,接下来就是验证用户密码

委托给子类DaoAuthenticationProvider中的additionalAuthenticationChecks(UserDetails userDetails,UsernamePasswordAuthenticationToken authentication)方法中实现的,代码如下


String presentedPassword = authentication.getCredentials().toString();

if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) {
	logger.debug("Authentication failed: password does not match stored value");
	throw new BadCredentialsException(messages.getMessage(
			"AbstractUserDetailsAuthenticationProvider.badCredentials",
			"Bad credentials"));
}

如果最后认证成功了,那么就会调用createSuccessAuthentication(Object principal,Authentication authentication,UserDetails user),这个方法来生成一个Authentication,否则就会抛出以一个异常
需要注意的是,

在Spring security 5.0 之后,所有的密码都是指定了一个加密方式,默认加密方式是BCryptPasswordEncoder,如果我们在数据库中存储的密码没有加密也会报错的

这样一来整个认证的过程就完成了,流程图如下(图片来自网络),结合图片和上面讲解的应该还是比较好理解的

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值