SpringSecurity和OAuth2认证授权流程
1、SpringSecurity认证授权流程
1.1、SpringSecurity认证流程
1】用户发起登录请求,请求登录接口 /login(SpringSecurity默认登录接口地址)。
2】过滤器 UsernamePasswordAuthenticationFilter 使用 RequestMatcher 验证当前请求是否是在请求 /login 接口,如果是调用 UsernamePasswordAuthenticationFilter#attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
方法开始认证。
3】attemptAuthentication方法在请求中获取到 username、password 参数封装成一个 UsernamePasswordAuthenticationToken
对象,调用AuthenticationManager#authenticate(Authentication authentication)
方法认证(AuthenticationManager 的默认实现 ProviderManager)ProviderManager认证是由实现了 AuthenticationProvider 接口的各种 provider对象 认证的),这里完成默认认证逻辑的是DaoAuthenticationProvider 对象,默认由DaoAuthenticationProvider#retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
;然后由UserDetailsService#loadUserByUsername(String username)
获取UserDetails对象。
4】进入后面的认证成功或失败处理逻辑。
1.2、SpringSecurity授权流程
1】拦截请求,已认证用户访问受保护的web资源将被SecurityFilterChain中的FilterSecurityInterceptor 的子类拦截。
2】获取资源访问策略,FilterSecurityInterceptor 会从 SecurityMetadataSource 的子类 DefaultFilterInvocationSecurityMetadataSource 获取要访问当前资源所需要的权限 Collection<ConfigAttribute> 。
SecurityMetadataSource其实就是读取访问策略的抽象,而读取的内容,其实就是我们配置的访问规则,读取访问策略如:
http.authorizeRequests().antMatchers(“/r/r1”).hasAuthority(“p1”)…
3】最后,FilterSecurityInterceptor会调用 AccessDecisionManager 进行授权决策:若决策通过,则允许访问资源;否则将禁止访问。
// 通过传递的参数来鉴定用户是否有访问对应受保护资源的权限
public interface AccessDecisionManager {
void decide(Authentication authentication , Object object, Collection<