首页
在线工具
搜索
1
Kuboard与KubeSphere的区别:Kubernetes管理平台对比
2
ShardingSphere使用中的重点问题剖析
3
Flowable工作流引擎源码深度解析
4
用AI生成的原型设计稿效果还可以
5
如何将Virtualbox和VMware虚拟机相互转换
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
Search
标签搜索
Angular
Docker
Phabricator
SpringBoot
Java
Chrome
SpringSecurity
SpringCloud
DDD
Git
Mac
K8S
Kubernetes
ESLint
SSH
高并发
Eclipse
Javascript
Vim
Centos
Jonathan
累计撰写
86
篇文章
累计收到
0
条评论
首页
栏目
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
页面
搜索到
27
篇与
的结果
2018-11-13
Spring Security OAuth2 源码阅读笔记
Spring Security OAuth2 源码阅读笔记 一、架构概述 Spring Security OAuth2 是基于Spring Security构建的OAuth2实现,提供了完整的授权服务器、资源服务器和客户端支持。通过阅读源码,我们可以深入理解OAuth2的工作原理和Spring的实现方式。 1.1 主要模块 Authorization Server: 授权服务器,负责颁发令牌 Resource Server: 资源服务器,负责保护资源 Client: OAuth2客户端,用于请求访问受保护的资源 1.2 核心接口 TokenStore: 令牌存储 ClientDetailsService: 客户端详情服务 UserDetailsService: 用户详情服务 TokenGranter: 令牌授予器 OAuth2RequestFactory: OAuth2请求工厂 二、授权服务器源码分析 2.1 AuthorizationServerSecurityConfigurer public final class AuthorizationServerSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { private AuthenticationManager authenticationManager; private AuthenticationEntryPoint authenticationEntryPoint; private PasswordEncoder passwordEncoder; private String realm = "oauth2/client"; private boolean allowFormAuthenticationForClients = false; private String tokenKeyAccess = "denyAll()"; private String checkTokenAccess = "denyAll()"; // ... @Override public void configure(HttpSecurity http) throws Exception { // 配置/oauth/token_key和/oauth/check_token端点的安全性 ClientDetailsService clientDetailsService = clientDetailsServiceBuilder.build(); clientDetailsService = new ClientDetailsUserDetailsService(clientDetailsService); // ... // 设置OAuth2的客户端认证过滤器 http.addFilterBefore(new ClientCredentialsTokenEndpointFilter(http.getSharedObject(AuthenticationManager.class)), BasicAuthenticationFilter.class); // ... } // ... } AuthorizationServerSecurityConfigurer配置授权服务器的安全性,包括客户端身份验证、端点访问控制等。 2.2 AuthorizationServerEndpointsConfigurer public final class AuthorizationServerEndpointsConfigurer { private AuthenticationManager authenticationManager; private List<AuthorizationServerConfigurer> configurers = Collections.emptyList(); private TokenStore tokenStore; private TokenGranter tokenGranter; private ConsumerTokenServices consumerTokenServices; private AuthorizationCodeServices authorizationCodeServices; private UserDetailsService userDetailsService; private OAuth2RequestFactory requestFactory; // ... public TokenGranter getTokenGranter() { if (tokenGranter == null) { tokenGranter = new CompositeTokenGranter(getDefaultTokenGranters()); } return tokenGranter; } private List<TokenGranter> getDefaultTokenGranters() { ClientDetailsService clientDetails = clientDetailsService(); AuthorizationServerTokenServices tokenServices = tokenServices(); List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>(); tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetails, this.requestFactory)); tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetails, this.requestFactory)); tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetails, this.requestFactory)); tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetails, this.requestFactory)); if (authenticationManager != null) { tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetails, this.requestFactory)); } return tokenGranters; } // ... } AuthorizationServerEndpointsConfigurer配置授权服务器的端点,包括令牌授予器、令牌服务等。 2.3 TokenEndpoint @FrameworkEndpoint public class TokenEndpoint extends AbstractEndpoint { @RequestMapping(value = "/oauth/token", method=RequestMethod.POST) public ResponseEntity<OAuth2AccessToken> postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException { if (!(principal instanceof Authentication)) { throw new InsufficientAuthenticationException( "There is no client authentication. Try adding an appropriate authentication filter."); } String clientId = getClientId(principal); ClientDetails authenticatedClient = getClientDetailsService().loadClientByClientId(clientId); TokenRequest tokenRequest = getOAuth2RequestFactory().createTokenRequest(parameters, authenticatedClient); // ... OAuth2AccessToken token = getTokenGranter().grant(tokenRequest.getGrantType(), tokenRequest); if (token == null) { throw new UnsupportedGrantTypeException("Unsupported grant type: " + tokenRequest.getGrantType()); } return getResponse(token); } // ... } TokenEndpoint是OAuth2 /oauth/token端点的实现,负责处理令牌请求。 2.4 CompositeTokenGranter public class CompositeTokenGranter implements TokenGranter { private final List<TokenGranter> tokenGranters; public CompositeTokenGranter(List<TokenGranter> tokenGranters) { this.tokenGranters = new ArrayList<TokenGranter>(tokenGranters); } public OAuth2AccessToken grant(String grantType, TokenRequest tokenRequest) { for (TokenGranter granter : tokenGranters) { OAuth2AccessToken grant = granter.grant(grantType, tokenRequest); if (grant != null) { return grant; } } return null; } // ... } CompositeTokenGranter是一个组合模式的实现,它包含多个TokenGranter,用于支持不同的授权类型。 2.5 DefaultTokenServices public class DefaultTokenServices implements AuthorizationServerTokenServices, ResourceServerTokenServices, ConsumerTokenServices { private TokenStore tokenStore; private ClientDetailsService clientDetailsService; private TokenEnhancer accessTokenEnhancer; private AuthenticationManager authenticationManager; private boolean supportRefreshToken = false; private boolean reuseRefreshToken = true; private int refreshTokenValiditySeconds = 60 * 60 * 24 * 30; // default 30 days. private int accessTokenValiditySeconds = 60 * 60 * 12; // default 12 hours. @Override public OAuth2AccessToken createAccessToken(OAuth2Authentication authentication) throws AuthenticationException { OAuth2AccessToken existingAccessToken = tokenStore.getAccessToken(authentication); OAuth2RefreshToken refreshToken = null; if (existingAccessToken != null) { if (existingAccessToken.isExpired()) { if (existingAccessToken.getRefreshToken() != null) { refreshToken = existingAccessToken.getRefreshToken(); // The token store could remove the refresh token when the // access token is removed, but we want to // be sure... tokenStore.removeRefreshToken(refreshToken); } tokenStore.removeAccessToken(existingAccessToken); } else { // Re-store the access token in case the authentication has changed tokenStore.storeAccessToken(existingAccessToken, authentication); return existingAccessToken; } } // 创建刷新令牌 if (refreshToken == null) { refreshToken = createRefreshToken(authentication); } // But the refresh token itself might need to be re-issued if it has // expired. else if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiring = (ExpiringOAuth2RefreshToken) refreshToken; if (System.currentTimeMillis() > expiring.getExpiration().getTime()) { refreshToken = createRefreshToken(authentication); } } // 创建访问令牌 OAuth2AccessToken accessToken = createAccessToken(authentication, refreshToken); tokenStore.storeAccessToken(accessToken, authentication); refreshToken = accessToken.getRefreshToken(); if (refreshToken != null) { tokenStore.storeRefreshToken(refreshToken, authentication); } return accessToken; } // ... } DefaultTokenServices是令牌服务的默认实现,负责创建、刷新和存储令牌。 三、资源服务器源码分析 3.1 ResourceServerSecurityConfigurer public final class ResourceServerSecurityConfigurer extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> { private AuthenticationManager authenticationManager; private ResourceServerTokenServices resourceTokenServices; private TokenStore tokenStore; private String resourceId = "oauth2-resource"; private AuthenticationEntryPoint authenticationEntryPoint = new OAuth2AuthenticationEntryPoint(); @Override public void configure(HttpSecurity http) throws Exception { // 配置OAuth2AuthenticationProcessingFilter // ... } // ... } ResourceServerSecurityConfigurer配置资源服务器的安全性,包括令牌服务、资源ID等。 3.2 OAuth2AuthenticationProcessingFilter public class OAuth2AuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { private AuthenticationManager authenticationManager; private AuthenticationEntryPoint authenticationEntryPoint; private TokenExtractor tokenExtractor = new BearerTokenExtractor(); private OAuth2AuthenticationDetails.TokenExtractor tokenDetailsExtractor = new OAuth2AuthenticationDetails.TokenExtractor(); private AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource = new OAuth2AuthenticationDetailsSource(); @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { OAuth2Authentication authentication = loadAuthentication(request); if (authentication == null) { throw new BadCredentialsException("Invalid token"); } return authentication; } protected OAuth2Authentication loadAuthentication(HttpServletRequest request) { final OAuth2AccessToken token = tokenExtractor.extract(request); if (token == null) { throw new InvalidTokenException("Token not found"); } OAuth2Authentication auth = tokenServices.loadAuthentication(token.getValue()); if (auth == null) { throw new InvalidTokenException("Invalid token: " + token.getValue()); } return auth; } // ... } OAuth2AuthenticationProcessingFilter负责从请求中提取令牌并验证其有效性。 3.3 BearerTokenExtractor public class BearerTokenExtractor implements TokenExtractor { private static final Pattern AUTHORIZATION_PATTERN = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-._~+/]+=*)$", Pattern.CASE_INSENSITIVE); @Override public OAuth2AccessToken extract(HttpServletRequest request) { String tokenValue = extractToken(request); if (tokenValue != null) { return new OAuth2AccessToken(tokenValue); } return null; } protected String extractToken(HttpServletRequest request) { // 从Authorization头部中提取Bearer令牌 String header = request.getHeader("Authorization"); if (header != null) { Matcher matcher = AUTHORIZATION_PATTERN.matcher(header); if (matcher.matches()) { return matcher.group("token"); } } // 从请求参数中提取令牌 String param = request.getParameter("access_token"); if (param != null) { return param; } return null; } // ... } BearerTokenExtractor从请求中提取Bearer令牌。 四、OAuth2客户端源码分析 4.1 OAuth2ClientContextFilter public class OAuth2ClientContextFilter extends OncePerRequestFilter { private OAuth2ClientContext clientContext; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { HttpServletRequest servletRequest = (HttpServletRequest) request; HttpServletResponse servletResponse = (HttpServletResponse) response; // 存储当前请求和响应,以便后续使用 request.setAttribute(OAuth2AuthenticationDetails.ACCESS_TOKEN_VALUE, null); try { // 清除现有上下文 OAuth2ClientContext context = new DefaultOAuth2ClientContext(clientContext); OAuth2ClientContextHolder.setContext(context); // 执行过滤器链 filterChain.doFilter(servletRequest, servletResponse); } catch (OAuth2Exception e) { // 处理OAuth2异常 if (e instanceof UserRedirectRequiredException) { UserRedirectRequiredException redirect = (UserRedirectRequiredException) e; String redirectUri = redirect.getRedirectUri(); // 保存当前请求信息,用于重定向后恢复 // 重定向到授权服务器 // ... } else { throw e; } } finally { // 清除上下文 OAuth2ClientContextHolder.clearContext(); } } // ... } OAuth2ClientContextFilter管理OAuth2客户端上下文,处理重定向等操作。 4.2 OAuth2RestTemplate public class OAuth2RestTemplate extends RestTemplate { private final OAuth2ClientContext context; private final AccessTokenProvider accessTokenProvider; private final OAuth2ProtectedResourceDetails resource; @Override protected ClientHttpRequest createRequest(URI uri, HttpMethod method) throws IOException { OAuth2AccessToken accessToken = getAccessToken(); ClientHttpRequest request = super.createRequest(uri, method); request.getHeaders().set("Authorization", "Bearer " + accessToken.getValue()); return request; } protected OAuth2AccessToken getAccessToken() throws UserRedirectRequiredException { OAuth2AccessToken accessToken = context.getAccessToken(); if (accessToken == null || accessToken.isExpired()) { try { accessToken = acquireAccessToken(context); } catch (UserRedirectRequiredException e) { context.setAccessToken(null); throw e; } } return accessToken; } protected OAuth2AccessToken acquireAccessToken(OAuth2ClientContext oauth2Context) throws UserRedirectRequiredException { AccessTokenRequest accessTokenRequest = oauth2Context.getAccessTokenRequest(); // 通过AccessTokenProvider获取令牌 OAuth2AccessToken accessToken = accessTokenProvider.obtainAccessToken(resource, accessTokenRequest); oauth2Context.setAccessToken(accessToken); return accessToken; } // ... } OAuth2RestTemplate是RestTemplate的扩展,自动处理OAuth2令牌的获取和使用。 五、令牌存储实现分析 5.1 InMemoryTokenStore public class InMemoryTokenStore implements TokenStore { private final ConcurrentHashMap<String, OAuth2AccessToken> accessTokenStore = new ConcurrentHashMap<String, OAuth2AccessToken>(); private final ConcurrentHashMap<String, OAuth2Authentication> authenticationStore = new ConcurrentHashMap<String, OAuth2Authentication>(); private final ConcurrentHashMap<String, OAuth2RefreshToken> refreshTokenStore = new ConcurrentHashMap<String, OAuth2RefreshToken>(); private final ConcurrentHashMap<String, String> accessTokenToRefreshToken = new ConcurrentHashMap<String, String>(); private final ConcurrentHashMap<String, String> refreshTokenToAccessToken = new ConcurrentHashMap<String, String>(); private final ConcurrentHashMap<String, Collection<OAuth2AccessToken>> authenticationToAccessTokenStore = new ConcurrentHashMap<String, Collection<OAuth2AccessToken>>(); private final ConcurrentHashMap<String, Collection<OAuth2AccessToken>> clientIdToAccessTokenStore = new ConcurrentHashMap<String, Collection<OAuth2AccessToken>>(); private final ConcurrentHashMap<String, Collection<OAuth2AccessToken>> userNameToAccessTokenStore = new ConcurrentHashMap<String, Collection<OAuth2AccessToken>>(); @Override public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) { // 根据认证信息查找访问令牌 // ... } @Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { // 存储访问令牌 String refreshToken = null; if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } if (refreshToken != null) { // 关联访问令牌和刷新令牌 accessTokenToRefreshToken.put(token.getValue(), refreshToken); refreshTokenToAccessToken.put(refreshToken, token.getValue()); } // 存储令牌和认证信息 accessTokenStore.put(token.getValue(), token); authenticationStore.put(token.getValue(), authentication); // 添加到认证信息、客户端ID和用户名到访问令牌的映射 // ... } @Override public void removeAccessToken(OAuth2AccessToken token) { // 删除访问令牌 // ... } // 其他方法省略 // ... } InMemoryTokenStore是使用内存存储令牌的实现,适用于单实例应用。 5.2 JdbcTokenStore public class JdbcTokenStore implements TokenStore { private final JdbcTemplate jdbcTemplate; private static final String DEFAULT_ACCESS_TOKEN_INSERT_STATEMENT = "insert into oauth_access_token (token_id, token, authentication_id, user_name, client_id, authentication, refresh_token) values (?, ?, ?, ?, ?, ?, ?)"; private static final String DEFAULT_ACCESS_TOKEN_SELECT_STATEMENT = "select token_id, token from oauth_access_token where token_id = ?"; // 其他SQL语句 // ... @Override public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) { String refreshToken = null; if (token.getRefreshToken() != null) { refreshToken = token.getRefreshToken().getValue(); } // 使用JDBC存储访问令牌 jdbcTemplate.update(insertAccessTokenSql, new Object[] { extractTokenKey(token.getValue()), serializeAccessToken(token), authenticationKeyGenerator.extractKey(authentication), authentication.isClientOnly() ? null : authentication.getName(), authentication.getOAuth2Request().getClientId(), serializeAuthentication(authentication), extractTokenKey(refreshToken) }); } @Override public OAuth2AccessToken readAccessToken(String tokenValue) { OAuth2AccessToken accessToken = null; try { accessToken = jdbcTemplate.queryForObject(selectAccessTokenSql, new RowMapper<OAuth2AccessToken>() { public OAuth2AccessToken mapRow(ResultSet rs, int rowNum) throws SQLException { return deserializeAccessToken(rs.getBytes(2)); } }, extractTokenKey(tokenValue)); } catch (EmptyResultDataAccessException e) { // 令牌不存在 } return accessToken; } // 其他方法省略 // ... } JdbcTokenStore使用关系型数据库存储令牌,适用于集群环境。 六、授权类型实现分析 6.1 AuthorizationCodeTokenGranter public class AuthorizationCodeTokenGranter extends AbstractTokenGranter { private final AuthorizationCodeServices authorizationCodeServices; @Override protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { Map<String, String> parameters = tokenRequest.getRequestParameters(); String authorizationCode = parameters.get("code"); String redirectUri = parameters.get("redirect_uri"); // 校验授权码 if (authorizationCode == null) { throw new InvalidRequestException("An authorization code must be supplied."); } // 消费授权码,同时获取认证信息 OAuth2Authentication storedAuth = authorizationCodeServices.consumeAuthorizationCode(authorizationCode); if (storedAuth == null) { throw new InvalidGrantException("Invalid authorization code: " + authorizationCode); } // 校验重定向URI OAuth2Request pendingOAuth2Request = storedAuth.getOAuth2Request(); String pendingClientId = pendingOAuth2Request.getClientId(); String clientId = tokenRequest.getClientId(); if (clientId != null && !clientId.equals(pendingClientId)) { throw new InvalidGrantException("Client ID mismatch"); } String pendingRedirectUri = pendingOAuth2Request.getRedirectUri(); if (pendingRedirectUri != null && redirectUri != null && !pendingRedirectUri.equals(redirectUri)) { throw new RedirectMismatchException("Redirect URI mismatch."); } // 创建新的OAuth2Request,继承原有的OAuth2Request中的参数 OAuth2Request oauth2Request = pendingOAuth2Request.createOAuth2Request(client); // 创建OAuth2Authentication OAuth2Authentication authentication = new OAuth2Authentication(oauth2Request, storedAuth.getUserAuthentication()); // 创建访问令牌 OAuth2AccessToken accessToken = getTokenServices().createAccessToken(authentication); return accessToken; } // ... } AuthorizationCodeTokenGranter实现了授权码授权类型。 6.2 RefreshTokenGranter public class RefreshTokenGranter extends AbstractTokenGranter { @Override protected OAuth2AccessToken getAccessToken(ClientDetails client, TokenRequest tokenRequest) { String refreshTokenValue = tokenRequest.getRequestParameters().get("refresh_token"); if (refreshTokenValue == null) { throw new InvalidRequestException("Missing refresh token"); } // 加载刷新令牌 OAuth2RefreshToken refreshToken = tokenServices.getRefreshToken(refreshTokenValue); if (refreshToken == null) { throw new InvalidGrantException("Invalid refresh token: " + refreshTokenValue); } // 校验刷新令牌是否过期 if (refreshToken instanceof ExpiringOAuth2RefreshToken) { ExpiringOAuth2RefreshToken expiringToken = (ExpiringOAuth2RefreshToken) refreshToken; if (expiringToken.getExpiration() != null && expiringToken.getExpiration().before(new Date())) { tokenServices.removeRefreshToken(refreshToken); throw new InvalidTokenException("Invalid refresh token (expired): " + refreshTokenValue); } } // 获取认证信息 OAuth2Authentication authentication = tokenServices.loadAuthentication(refreshTokenValue); // 校验客户端ID String clientId = authentication.getOAuth2Request().getClientId(); if (clientId != null && !clientId.equals(tokenRequest.getClientId())) { throw new InvalidGrantException("Wrong client for this refresh token: " + refreshTokenValue); } // 创建新的访问令牌 return tokenServices.refreshAccessToken(refreshTokenValue, tokenRequest); } // ... } RefreshTokenGranter实现了刷新令牌授权类型。 七、OAuth2异常处理 7.1 OAuth2Exception public class OAuth2Exception extends RuntimeException { private String summary; private String oAuth2ErrorCode; private int httpStatusCode; // 构造方法和getter/setter方法 // ... } OAuth2Exception是OAuth2错误的基类。 7.2 OAuth2ExceptionRenderer public class DefaultOAuth2ExceptionRenderer implements OAuth2ExceptionRenderer { private List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); @Override public void handleHttpEntityResponse(HttpEntity<?> responseEntity, ServletWebRequest webRequest) throws Exception { if (responseEntity == null) { return; } HttpInputMessage inputMessage = createHttpInputMessage(webRequest); HttpOutputMessage outputMessage = createHttpOutputMessage(webRequest); // 查找适合的消息转换器 Class<?> clazz = responseEntity.getBody().getClass(); List<MediaType> acceptedMediaTypes = webRequest.getRequest().getHeaders("Accept"); MediaType.sortByQualityValue(acceptedMediaTypes); // 使用消息转换器将响应实体输出到响应流中 for (MediaType acceptedMediaType : acceptedMediaTypes) { for (HttpMessageConverter messageConverter : messageConverters) { if (messageConverter.canWrite(clazz, acceptedMediaType)) { messageConverter.write(responseEntity.getBody(), acceptedMediaType, outputMessage); return; } } } // 如果没有找到适合的消息转换器,使用默认的JSON转换器 // ... } // ... } OAuth2ExceptionRenderer负责将OAuth2异常渲染成HTTP响应。 八、总结与心得 通过对Spring Security OAuth2源码的阅读和分析,我对OAuth2的实现机制有了更深入的理解: Spring Security OAuth2通过各种组件(授权服务器、资源服务器、客户端)协同工作,实现完整的OAuth2流程。 令牌的生成、存储和验证是OAuth2的核心功能,Spring Security OAuth2提供了多种令牌存储实现(内存、数据库等)。 授权服务器支持多种授权类型(授权码、隐式授权、密码、客户端凭证、刷新令牌),每种授权类型都有独立的实现类。 Spring Security OAuth2使用过滤器链来处理OAuth2请求,例如TokenEndpointAuthenticationFilter、OAuth2AuthenticationProcessingFilter等。 Spring Security OAuth2的异常处理机制非常完善,针对OAuth2规范中定义的各种错误情况都有相应的处理。
2018年11月13日
2018-11-12
Spring Security 源码阅读笔记
Spring Security 源码阅读笔记 一、核心架构概述 Spring Security的核心是基于过滤器链(Filter Chain)的认证和授权机制。通过分析源码,我们可以看到它的主要组件和执行流程。 1.1 核心组件 SecurityContextHolder: 安全上下文的存储策略 Authentication: 认证信息的抽象 AuthenticationManager: 认证管理器 SecurityFilterChain: 安全过滤器链 UserDetailsService: 用户信息获取服务 PasswordEncoder: 密码编码器 AccessDecisionManager: 访问决策管理器 二、认证流程源码分析 2.1 SecurityContextHolder public class SecurityContextHolder { private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>(); public static SecurityContext getContext() { SecurityContext ctx = contextHolder.get(); if (ctx == null) { ctx = createEmptyContext(); contextHolder.set(ctx); } return ctx; } // 其它方法... } SecurityContextHolder负责存储当前用户的安全上下文,默认使用ThreadLocal存储,确保每个线程都有独立的安全上下文。 2.2 UsernamePasswordAuthenticationFilter public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter { @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { String username = obtainUsername(request); String password = obtainPassword(request); UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password); return this.getAuthenticationManager().authenticate(authRequest); } // 其它方法... } 这个过滤器负责处理表单登录的认证请求,从请求中获取用户名和密码,然后创建认证令牌交给AuthenticationManager处理。 2.3 ProviderManager public class ProviderManager implements AuthenticationManager { private List<AuthenticationProvider> providers; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { Class<? extends Authentication> toTest = authentication.getClass(); AuthenticationException lastException = null; for (AuthenticationProvider provider : getProviders()) { if (!provider.supports(toTest)) { continue; } try { Authentication result = provider.authenticate(authentication); if (result != null) { copyDetails(authentication, result); return result; } } catch (AuthenticationException e) { lastException = e; } } if (lastException != null) { throw lastException; } throw new ProviderNotFoundException("No AuthenticationProvider found for " + toTest.getName()); } // 其它方法... } ProviderManager是AuthenticationManager的实现,它委托一系列AuthenticationProvider来处理认证请求。 2.4 DaoAuthenticationProvider public class DaoAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider { private UserDetailsService userDetailsService; private PasswordEncoder passwordEncoder; @Override protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { if (authentication.getCredentials() == null) { throw new BadCredentialsException("Bad credentials"); } String presentedPassword = authentication.getCredentials().toString(); if (!passwordEncoder.matches(presentedPassword, userDetails.getPassword())) { throw new BadCredentialsException("Bad credentials"); } } @Override protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { 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 notFound) { throw notFound; } catch (Exception repositoryProblem) { throw new InternalAuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem); } } // 其它方法... } DaoAuthenticationProvider通过UserDetailsService获取用户信息,然后使用PasswordEncoder验证密码。 三、授权流程源码分析 3.1 FilterSecurityInterceptor public class FilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter { private static final String FILTER_APPLIED = "__spring_security_filterSecurityInterceptor_filterApplied"; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { invoke(new FilterInvocation(request, response, chain)); } public void invoke(FilterInvocation fi) throws IOException, ServletException { if ((fi.getRequest() != null) && (fi.getRequest().getAttribute(FILTER_APPLIED) != null) && observeOncePerRequest) { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } else { if (fi.getRequest() != null && observeOncePerRequest) { fi.getRequest().setAttribute(FILTER_APPLIED, Boolean.TRUE); } InterceptorStatusToken token = super.beforeInvocation(fi); try { fi.getChain().doFilter(fi.getRequest(), fi.getResponse()); } finally { super.finallyInvocation(token); } super.afterInvocation(token, null); } } // 其它方法... } FilterSecurityInterceptor是过滤器链中最后一个过滤器,负责对请求进行访问控制决策。 3.2 AccessDecisionManager public interface AccessDecisionManager { void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException; boolean supports(ConfigAttribute attribute); boolean supports(Class<?> clazz); } AccessDecisionManager接口定义了授权决策的方法,由具体实现类决定是否允许访问。 3.3 AffirmativeBased public class AffirmativeBased extends AbstractAccessDecisionManager { @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException { int deny = 0; for (AccessDecisionVoter voter : getDecisionVoters()) { int result = voter.vote(authentication, object, configAttributes); switch (result) { case AccessDecisionVoter.ACCESS_GRANTED: return; case AccessDecisionVoter.ACCESS_DENIED: deny++; break; default: break; } } if (deny > 0) { throw new AccessDeniedException(messages.getMessage( "AbstractAccessDecisionManager.accessDenied", "Access is denied")); } // 如果没有voter投赞成票,根据allowIfAllAbstainDecisions决定是否允许访问 checkAllowIfAllAbstainDecisions(); } // 其它方法... } AffirmativeBased是AccessDecisionManager的一个实现,只要有一个投票器投票通过,就允许访问。 四、过滤器链构建过程 4.1 WebSecurity public final class WebSecurity extends AbstractConfiguredSecurityBuilder<Filter, WebSecurity> implements SecurityBuilder<Filter>, ApplicationContextAware { private List<SecurityFilterChain> securityFilterChains = new ArrayList<>(); @Override protected Filter performBuild() throws Exception { // ... int chainSize = this.securityFilterChains.size(); if (chainSize > 0) { return VirtualFilterChain.createChainProxy(this.securityFilterChains); } // ... } // 其它方法... } WebSecurity负责构建过滤器链。 4.2 HttpSecurity public final class HttpSecurity extends AbstractConfiguredSecurityBuilder<DefaultSecurityFilterChain, HttpSecurity> implements SecurityBuilder<DefaultSecurityFilterChain>, HttpSecurityBuilder<HttpSecurity> { @Override protected DefaultSecurityFilterChain performBuild() { filters.sort(comparator); return new DefaultSecurityFilterChain(requestMatcher, filters); } // 其它方法... } HttpSecurity负责配置单个SecurityFilterChain中的过滤器。 五、常见过滤器解析 在Spring Security中,请求会经过一系列过滤器,下面是一些关键过滤器的源码分析: 5.1 SecurityContextPersistenceFilter public class SecurityContextPersistenceFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpRequestResponseHolder holder = new HttpRequestResponseHolder(request, response); SecurityContext contextBeforeChainExecution = repo.loadContext(holder); try { SecurityContextHolder.setContext(contextBeforeChainExecution); chain.doFilter(holder.getRequest(), holder.getResponse()); } finally { SecurityContext contextAfterChainExecution = SecurityContextHolder.getContext(); SecurityContextHolder.clearContext(); repo.saveContext(contextAfterChainExecution, holder.getRequest(), holder.getResponse()); } } // 其它方法... } SecurityContextPersistenceFilter负责在请求处理前加载SecurityContext,在请求处理后保存SecurityContext。 5.2 LogoutFilter public class LogoutFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if (requiresLogout(request, response)) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (logger.isDebugEnabled()) { logger.debug("Logging out user '" + auth + "' and transferring to logout destination"); } this.handler.logout(request, response, auth); logoutSuccessHandler.onLogoutSuccess(request, response, auth); return; } chain.doFilter(request, response); } // 其它方法... } LogoutFilter处理用户退出登录的请求。 六、注解式安全配置实现原理 6.1 @EnableWebSecurity @Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME) @Target(value = { java.lang.annotation.ElementType.TYPE }) @Documented @Import({ WebSecurityConfiguration.class, SpringWebMvcImportSelector.class, OAuth2ImportSelector.class, HttpSecurityConfiguration.class }) @EnableGlobalAuthentication @Configuration public @interface EnableWebSecurity { boolean debug() default false; } @EnableWebSecurity导入了WebSecurityConfiguration等配置类。 6.2 WebSecurityConfiguration @Configuration(proxyBeanMethods = false) public class WebSecurityConfiguration { @Bean(name = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) public Filter springSecurityFilterChain() throws Exception { boolean hasConfigurers = webSecurityConfigurers != null && !webSecurityConfigurers.isEmpty(); if (!hasConfigurers) { WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor.postProcess(new WebSecurityConfigurerAdapter() {}); webSecurity.apply(adapter); } for (SecurityConfigurer<Filter, WebSecurity> webSecurityConfigurer : webSecurityConfigurers) { webSecurity.apply(webSecurityConfigurer); } return webSecurity.build(); } // 其它方法... } WebSecurityConfiguration负责创建springSecurityFilterChain。 6.3 @PreAuthorize源码 @Target({ ElementType.METHOD, ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Inherited @Documented @Repeatable(PreAuthorizes.class) public @interface PreAuthorize { String value(); } @PreAuthorize是方法级的安全注解,用于指定访问控制表达式。 6.4 MethodSecurityInterceptor public class MethodSecurityInterceptor extends AbstractSecurityInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation mi) throws Throwable { InterceptorStatusToken token = super.beforeInvocation(mi); Object result; try { result = mi.proceed(); } finally { super.finallyInvocation(token); } return super.afterInvocation(token, result); } // 其它方法... } MethodSecurityInterceptor拦截带有安全注解的方法调用,进行访问控制决策。 七、OAuth2集成源码分析 7.1 OAuth2LoginConfigurer public final class OAuth2LoginConfigurer<B extends HttpSecurityBuilder<B>> extends AbstractAuthenticationFilterConfigurer<B, OAuth2LoginConfigurer<B>, OAuth2LoginAuthenticationFilter> { @Override public void init(B http) throws Exception { OAuth2LoginAuthenticationFilter authenticationFilter = new OAuth2LoginAuthenticationFilter( this.authorizationRequestRepository, this.authorizationRequestRepository); authenticationFilter.setAuthenticationManager( this.authenticationManager(http)); // 设置各种属性... this.setAuthenticationFilter(authenticationFilter); super.init(http); } // 其它方法... } OAuth2LoginConfigurer配置OAuth2登录流程。 7.2 OAuth2AuthorizationRequestRedirectFilter public class OAuth2AuthorizationRequestRedirectFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String registrationId = this.resolveRegistrationId(request); if (registrationId == null) { filterChain.doFilter(request, response); return; } ClientRegistration clientRegistration = this.clientRegistrationRepository.findByRegistrationId(registrationId); if (clientRegistration == null) { throw new IllegalArgumentException("Invalid Client Registration with Id: " + registrationId); } OAuth2AuthorizationRequest authorizationRequest = this.authorizationRequestResolver .resolve(request, clientRegistration); if (authorizationRequest == null) { throw new IllegalStateException( "Unable to resolve OAuth2 Authorization Request for Client Registration: " + registrationId); } this.authorizationRequestRepository.saveAuthorizationRequest(authorizationRequest, request, response); URI redirectUri = URI.create(authorizationRequest.getAuthorizationRequestUri()); this.authorizationRedirectStrategy.sendRedirect(request, response, redirectUri.toString()); } // 其它方法... } OAuth2AuthorizationRequestRedirectFilter负责处理OAuth2授权请求的重定向。 八、总结与心得 通过对Spring Security源码的阅读和分析,我对其核心工作流程有了更深入的理解: 安全过滤器链是Spring Security的核心,它通过一系列过滤器来处理HTTP请求的安全性。 认证流程主要通过AuthenticationManager和AuthenticationProvider来实现,支持多种认证方式。 授权决策由AccessDecisionManager负责,通过投票机制来决定是否允许访问。 Spring Security的配置非常灵活,可以通过Java配置、XML配置或注解来实现。 Spring Security与OAuth2的集成是通过专门的过滤器和配置类来实现的。
2018年11月12日
2018-03-17
SpringCloud使用中的一下注意事项与问题
Spring Cloud Config 配置的坑 动态配置时,在配置中心修改zuul的 service id ,修改后将无法访问 kafka整合zipkin笔记 参考:https://github.com/niemingming/springcloud-sleuth-kafka-zipkin/tree/71404c9cd1e3f4b7c6ae8dee80ffca31652b03a9 如果使用actuator就无法访问端口spring-boot-starter-actuator o.s.k.support.LoggingProducerListener : Exception thrown when sending a message with key='null' and payload='{-1, 4, 11, 99, 111, 110, 116, 101, 110, 116, 84, 121, 112, 101, 0, 0, 0, 78, 34, 97, 112, 112, 108,...' to topic sleuth: 忘记设置 sleuth: enabled: false 搭建zipkin整合kafka碰到的问题 一个奇怪的issue: 如果application.yml里面配置logging相关的配置,则sleuth无法启动 http://takeip.com/spring-cloud-stream-app-starter-fails-after-10-secs-saying-binderexception-cannot-initialize-binder.html解决方案 如果程序启动到Kafka commitId : f10ef2720b03b247 过一段时间报 Cannot initialize Binder org.springframework.context.ApplicationContextException: Failed to start bean 'outputBindingLifecycle'; nested exception is org.springframework.cloud.stream.binder.BinderException: Cannot initialize binder: 需要修改kafka的配置 server.properties listeners=PLAINTEXT://localhost:9092 一般因为没有监听对应的ip UserRedirectRequiredException: A redirect is required to get the users approval 在spring mvc下无法跳转到统一认证页报错 org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.security.oauth2.client.resource.UserRedirectRequiredException: A redirect is required to get the users approval j 解决方案:缺少两个Spring Security和Oauth2的过滤器: oauth2ClientContextFilter springSecurityFilterChain public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); ctx.register(HelloWorldConfiguration.class); ctx.setServletContext(container); ServletRegistration.Dynamic servlet = container.addServlet( "dispatcher", new DispatcherServlet(ctx)); servlet.setLoadOnStartup(1); servlet.addMapping("/"); // registerProxyFilter(container, "springSecurityFilterChain"); // registerProxyFilter(container, "oauth2ClientContextFilter"); } private void registerProxyFilter(ServletContext servletContext, String name) { DelegatingFilterProxy filter = new DelegatingFilterProxy(name); filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher"); servletContext.addFilter(name, filter).addMappingForUrlPatterns(null, false, "/*"); }
2018年03月17日
2017-09-14
AMqp阅读笔记
@Payload 表示有效的传输数据 每个 RabbitTemplate 只支持一个 ReturnCallback 批次消息 BatchingRabbitTemplate 只有当一个批次完成才会向 RabbitMQ 发送消息 从1.4.2版本开始,引入了 BatchingRabbitTemplate,它是 RabbitTemplate 的子类,覆盖了 send 方法,此方法可根据 BatchingStrategy 来批量发送消息;只有当一个批次完成时才会向 RabbitMQ 发送消息。 public interface BatchingStrategy { MessageBatch addToBatch(String exchange, String routingKey, Message message); Date nextRelease(); Collection<MessageBatch> releaseBatches(); } 警告 成批的数据是保存在内存中的,如果出现系统故障,未发送的消息将会丢失。 @RabbitListener 可以用在类上,监听多个方法 注意,如果有必要,需要在每个方法上指定 @SendTo,在类级上它是不支持的。 检测空闲异步消费者 从1.6版本开始,当没有消息投递时,可配置监听器容器来发布 ListenerContainerIdleEvent 事件。当容器是空闲的,事件会每隔 idleEventInterval 毫秒发布事件。 要配置这个功能,须在容器上设置 idleEventInterval: xml <rabbit:listener-container connection-factory="connectionFactory"...idle-event-interval="60000"... > <rabbit:listener id="container1" queue-names="foo" ref="myListener" method="handle" /> </rabbit:listener-container> Java @Bean public SimpleMessageListenerContainer(ConnectionFactory connectionFactory) { SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); ... container.setIdleEventInterval(60000L); ... return container; } @RabbitListener @Bean public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() { SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory(); factory.setConnectionFactory(rabbitConnectionFactory()); factory.setIdleEventInterval(60000L); ... return factory; } 事件消费 通过实现 ApplicationListener 可捕获这些事件- 要么是一个一般的监听器,要么是一个窄化的只接受特定事件的监听器。 你也可以使用Spring Framework 4.2中引入的 @EventListener。 下面的例子在单个类中组合使用了 @RabbitListener 和 @EventListener 。重点要理解,应用程序监听器会收到所有容器的事件,因此如果你只对某个容器采取措施,那么你需要检查监听器id。你也可以使用 @EventListener 条件来达到此目的。 事件有4个属性: source - 监听容器实例 id - 监听器id(或容器bean名称) idleTime - 当事件发布时,容器已经空闲的时间 queueNames - 容器监听的队列名称 public class Listener { @RabbitListener(id="foo", queues="#{queue.name}") public String listen(String foo) { return foo.toUpperCase(); } @EventListener(condition = "event.listenerId == 'foo'") public void onApplicationEvent(ListenerContainerIdleEvent event) { ... } } 重要 事件监听器会查看所有容器的事件,因此,在上面的例子中,我们根据监听器ID缩小了要接收的事件。 警告 如果你想使用idle事件来停止监听器容器,你不应该在调用监听器的线程上来调用 container.stop() 方法- 它会导致延迟和不必要的日志消息。 相反,你应该把事件交给一个不同的线程,然后可以停止容器。
2017年09月14日
2017-07-02
整合spring security oauth2的时候如果碰到Possible CSRF detected - state parameter was present but no state could be found
解决方案:https://github.com/spring-projects/spring-security-oauth/issues/322 问题所在: The problem is the session then. You have 2 servers running on localhost, on different ports, but cookies don't record the host, only the path, and both are on the root path "/" so they are sharing a cookie. Put one of them in a sub context (e.g. using server.contextPath=/auth for the auth server) and it should work I think. 您有2台服务器在本地主机上运行,不同的端口,但cookie不记录主机,只有路径,并且都在根路径“/”,所以他们共享一个cookie。将其中一个放在子上下文中(例如,使用server.contextPath = / auth进行认证服务器),它应该可以工作。
2017年07月02日
1
2
3
4
...
6