SpringSecurity学习笔记一

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/zyxwvuuvwxyz/article/details/102742298

基于SpringSecurity实现基于用户名、密码登录及原理分析

SpringSecurity以一系列的过滤器链来进行权限的管理,可以自定义新的filter。

Demo实现

定义一个用户,只有该用户成功登陆 才能访问接口,否则自动跳转到登录页面

@Component
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 处理用户获取逻辑 UserDetailService
     * 可以将获取用户信息的逻辑写到loadUserByUserName中
     * 处理用户校验逻辑 UserDetails
     * User是UserDetails的实现 在这里可以为授权 即赋予当前用户 xx角色
     * 处理密码加密解密 PasswordEncoder
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //若填写明文密码,则默认的DaoAuthenticationProvider会进行校验 会使用passwordEncoder进行匹配密码,所以要指定一个passwordEncoder的Bean
        return new User(username, passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
    }
}

SpringSecurity的配置

@Configuration
@EnableWebSecurity
public class WebMvcSecurityConfig  extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //表单登录 任何请求均进行认证
        http.formLogin()
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();
    }
}

以上 即实现了一个简单的基于用户名、密码的登录校验流程,只有登录成功才能访问接口或者直接访问接口时会被拦截住,如果未被认证则跳转到登录页面。

这里的登录页是SpringSecurity默认自带的

SpringSecurity自带登录页面

默认带了两种登录方式,分别是formLogin/formBasic。两者的区别只是交互方式有些不同。

原理分析

SpringSecurity主要由认证、授权两个步骤组成。

先以UserDetailsService开始

/**
 * 加载用户特定数据的核心接口
 * 它在整个框架中都作为用户DAO使用,并且是DaoAuthenticationProvider的策略
 *
 */
public interface UserDetailsService {
	
	/**
	 * 根据用户名找到用户。 在实际的实现中,根据实现实例的配置方式,搜索可能
	 * 区分大小写或不区分大小写。 
	 * 在这种情况下,返回的 UserDetails 对象的用户名可能与实际请求的用户名不同。
	 *
	 * GrantedAuthority
	 */
	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

其中SpringSecurity中UserDetails接口的基本属性含义如下:

  • Authorities 授予用户的权限 不能为空
  • password 认证用户的密码
  • username 认证用户的用户名 不能为空
  • isAccountNonExpired 指明用户的账户是否已经过期,过期账户不能为认证
  • isAccountNonLocked 指明用户账户是否被锁定,锁定的账户不能被认证
  • isCredentialsNonExpired 指示用户的凭据(密码)是否已过期。 已过期凭证阻止身份验证
  • isEnabled 指明用户是启用还是禁用。 禁用的用户不能已验证。

基于用户名、密码的登录方式是由UserNamePasswordauthenticationFilter来处理的

扫描二维码关注公众号,回复: 7606438 查看本文章

UserNamePasswordAuthenticationFilter 监听POST方式 默认路径是/login的登录方式

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);
	}

其中this.getAuthenticationManager() 这里是ProviderManager

ProviderManager

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;
		boolean debug = logger.isDebugEnabled();

		for (AuthenticationProvider provider : getProviders()) {
			if (!provider.supports(toTest)) {
				continue;
			}
		

			try {
				result = provider.authenticate(authentication);

				if (result != null) {
					copyDetails(authentication, result);
					break;
				}
			}
			catch (AccountStatusException e) {
				prepareException(e, authentication);
				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 = parentResult = parent.authenticate(authentication);
			}
			catch (ProviderNotFoundException e) {
			}
			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;
		}

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

			prepareException(lastException, authentication);
		}

		throw lastException;
	}

这里,会从系统中存在的provider中轮询符合要求的provider来进行认证操作。其中以supports方法返回true或false来判断是否符合要求。

通过源码发现,与用户名、密码登录有关的provider是DaoAuthenticationProvider

我们可以先看下DaoAuthenticationProvider中supports方法

public boolean supports(Class<?> authentication) {
//这里 只要认证的类是UsernamePasswordAuthenticationToken或UsernamePasswordAuthenticationToken的实现类
		return (UsernamePasswordAuthenticationToken.class
				.isAssignableFrom(authentication));
	}

通过查看源码发现,DaoAuthenticationProvider关于认证的逻辑是在AbstractUserDetailsAuthenticationProvider

AbstractUserDetailsAuthenticationProvider

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) {
				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);
	}

其中retrieveUser/additionalAuthenticationChecks等方法的实现是在其子类DaoAuthenticationProvider中实现的

DaoAuthenticationProvider

protected final UserDetails retrieveUser(String username,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		prepareTimingAttackProtection();
		try {
			UserDetails loadedUser = this.getUserDetailsService().loadUserByUsername(username);
			if (loadedUser == null) {
				throw new InternalAuthenticationServiceException(
						"UserDetailsService returned null, which is an interface contract violation");
			}
			return loadedUser;
		}
		catch (UsernameNotFoundException ex) {
			mitigateAgainstTimingAttack(authentication);
			throw ex;
		}
		catch (InternalAuthenticationServiceException ex) {
			throw ex;
		}
		catch (Exception ex) {
			throw new InternalAuthenticationServiceException(ex.getMessage(), ex);
		}
	}

可以看到 这里使用到了我们自定义MyUserDetailService#loadUserByUsername

认证完成之后,最终会将用户信息封装好 返回出去,过滤器继续执行进入其他流程。
封装用户信息的方法在createSuccessAuthentication

protected Authentication createSuccessAuthentication(Object principal,
			Authentication authentication, UserDetails user) {
			//user.getAuthorities() 代表给登录用户授予的角色
		UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(
				principal, authentication.getCredentials(),
				authoritiesMapper.mapAuthorities(user.getAuthorities()));
		result.setDetails(authentication.getDetails());

		return result;
	}

获取用户的认证信息
直接调用SecurityContextHolder.getContext().getAuthentication()或者把Authentication参数放到形参上

public Object getUser(Authentication authentication){
  return authentication;
}

如果想要UserDetails信息,可以这样做

public Object getUser(@AuthenticationPrincipal UserDetails user){
  return user;
}

以上是最近学习SpringSecurity的心得,如有问题 请指出。

猜你喜欢

转载自blog.csdn.net/zyxwvuuvwxyz/article/details/102742298