首页
在线工具
搜索
1
使用Metrics指标度量工具监控Java应用程序性能(Gauges, Counters, Histograms, Meters和 Timers实例)
2
如何将Virtualbox和VMware虚拟机相互转换
3
Jumpserver的MFA配置
4
Markdown正确使用姿势
5
Kuboard与KubeSphere的区别:Kubernetes管理平台对比
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
Search
标签搜索
Angular
Docker
Phabricator
SpringBoot
Java
Chrome
SpringSecurity
SpringCloud
DDD
Git
Mac
K8S
Kubernetes
ESLint
SSH
高并发
Eclipse
Javascript
Vim
Centos
Jonathan
累计撰写
86
篇文章
累计收到
0
条评论
首页
栏目
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
页面
搜索到
86
篇与
的结果
2018-11-15
Spring Security OAuth2与Spring Session Redis整合实现微服务会话共享
Spring Security OAuth2与Spring Session Redis整合实现微服务会话共享 引言 在微服务架构中,会话管理是一个常见的挑战。当用户通过OAuth2认证后,如何在多个微服务之间共享会话信息成为一个亟待解决的问题。本文将详细介绍如何利用Spring Security OAuth2结合Spring Session Redis实现微服务架构下的会话共享方案。 技术栈 Spring Boot Spring Security OAuth2 Spring Session Redis Spring Cloud (可选,用于服务发现等) 为什么选择Redis作为会话存储 在分布式系统中,使用Redis存储会话有以下优势: 高性能:Redis是基于内存的数据库,读写速度极快 数据持久化:支持数据持久化,防止数据丢失 丰富的数据结构:支持多种数据类型,适合存储复杂的会话数据 原生的过期机制:便于管理会话生命周期 实现步骤 1. 添加依赖 首先,我们需要在各个微服务的pom.xml文件中添加必要的依赖: <dependencies> <!-- Spring Boot 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Security OAuth2 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency> <!-- Spring Session Redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency> </dependencies> 2. 配置Redis与Spring Session 在每个微服务的application.yml文件中添加Redis和Spring Session的配置: spring: redis: host: localhost port: 6379 password: # 如有密码则填写 database: 0 session: store-type: redis redis: namespace: spring:session # Redis中存储会话的命名空间前缀 timeout: 1800 # 会话超时时间(秒) security: oauth2: client: registration: custom-client: client-id: client-id client-secret: client-secret authorization-grant-type: authorization_code redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}" scope: read,write provider: custom-provider: authorization-uri: http://auth-server/oauth/authorize token-uri: http://auth-server/oauth/token user-info-uri: http://auth-server/userinfo user-name-attribute: name server: servlet: session: cookie: http-only: true secure: true # 在生产环境中应设置为true 3. 启用Spring Session 在主应用类上添加@EnableRedisHttpSession注解: package com.example.microservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession; @SpringBootApplication @EnableRedisHttpSession public class MicroserviceApplication { public static void main(String[] args) { SpringApplication.run(MicroserviceApplication.class, args); } } 4. 配置Spring Security OAuth2 创建Security配置类,配置OAuth2认证: package com.example.microservice.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() ) .oauth2Login(oauth2 -> oauth2 .defaultSuccessUrl("/dashboard") .failureUrl("/login?error=true") ) .logout(logout -> logout .logoutSuccessUrl("/login?logout=true") .invalidateHttpSession(true) .deleteCookies("JSESSIONID") ); return http.build(); } } 5. 创建会话信息存储器 为了确保OAuth2认证信息能够在会话中正确存储和共享,创建自定义的会话信息存储器: package com.example.microservice.session; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Map; @Component public class OAuth2SessionRepository<S extends Session> { private final SessionRepository<S> sessionRepository; public OAuth2SessionRepository(SessionRepository<S> sessionRepository) { this.sessionRepository = sessionRepository; } public void saveOAuth2Authentication(HttpServletRequest request, Authentication authentication) { HttpSession session = request.getSession(false); if (session != null) { String sessionId = session.getId(); S redisSession = sessionRepository.findById(sessionId); if (redisSession != null) { if (authentication instanceof OAuth2AuthenticationToken) { OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication; OAuth2User oauth2User = oauthToken.getPrincipal(); // 存储用户信息和授权信息 redisSession.setAttribute("user_name", oauth2User.getAttribute("name")); redisSession.setAttribute("user_email", oauth2User.getAttribute("email")); redisSession.setAttribute("oauth2_provider", oauthToken.getAuthorizedClientRegistrationId()); // 存储OAuth2授权信息(可根据需求扩展) Map<String, Object> attributes = oauth2User.getAttributes(); for (Map.Entry<String, Object> entry : attributes.entrySet()) { if (entry.getValue() instanceof String) { redisSession.setAttribute("oauth2_attr_" + entry.getKey(), entry.getValue()); } } sessionRepository.save(redisSession); } } } } public OAuth2User getOAuth2User(String sessionId) { S redisSession = sessionRepository.findById(sessionId); if (redisSession != null) { // 根据存储的会话信息重建OAuth2User // 这里仅为示例,实际实现需要根据具体情况调整 return null; // 此处需实现具体逻辑 } return null; } } 6. 创建认证成功处理器 实现一个认证成功处理器,在用户成功认证后将OAuth2信息保存到Redis会话中: package com.example.microservice.handler; import com.example.microservice.session.OAuth2SessionRepository; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Component public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private final OAuth2SessionRepository<?> oAuth2SessionRepository; public CustomAuthenticationSuccessHandler(OAuth2SessionRepository<?> oAuth2SessionRepository) { this.oAuth2SessionRepository = oAuth2SessionRepository; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { // 保存OAuth2认证信息到Redis会话 oAuth2SessionRepository.saveOAuth2Authentication(request, authentication); // 重定向到成功页面 response.sendRedirect("/dashboard"); } } 7. 更新Security配置,使用自定义认证成功处理器 package com.example.microservice.config; import com.example.microservice.handler.CustomAuthenticationSuccessHandler; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { private final CustomAuthenticationSuccessHandler authenticationSuccessHandler; public SecurityConfig(CustomAuthenticationSuccessHandler authenticationSuccessHandler) { this.authenticationSuccessHandler = authenticationSuccessHandler; } @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorize -> authorize .requestMatchers("/public/**").permitAll() .anyRequest().authenticated() ) .oauth2Login(oauth2 -> oauth2 .successHandler(authenticationSuccessHandler) .failureUrl("/login?error=true") ) .logout(logout -> logout .logoutSuccessUrl("/login?logout=true") .invalidateHttpSession(true) .deleteCookies("JSESSIONID") ); return http.build(); } } 8. 创建一个拦截器,用于在请求中恢复认证信息 package com.example.microservice.interceptor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class OAuth2AuthenticationInterceptor implements HandlerInterceptor { private final SessionRepository<? extends Session> sessionRepository; public OAuth2AuthenticationInterceptor(SessionRepository<? extends Session> sessionRepository) { this.sessionRepository = sessionRepository; } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { // 检查是否已经有认证信息 if (SecurityContextHolder.getContext().getAuthentication() == null) { HttpSession httpSession = request.getSession(false); if (httpSession != null) { String sessionId = httpSession.getId(); Session redisSession = sessionRepository.findById(sessionId); if (redisSession != null) { // 从Redis会话中恢复OAuth2认证信息 // 这里需要实现具体的逻辑,根据存储的信息重建OAuth2AuthenticationToken OAuth2User oauth2User = createOAuth2UserFromSession(redisSession); String registrationId = (String) redisSession.getAttribute("oauth2_provider"); if (oauth2User != null && registrationId != null) { OAuth2AuthenticationToken authentication = new OAuth2AuthenticationToken(oauth2User, oauth2User.getAuthorities(), registrationId); SecurityContextHolder.getContext().setAuthentication(authentication); } } } } return true; } private OAuth2User createOAuth2UserFromSession(Session session) { // 根据会话中存储的信息重建OAuth2User对象 // 这里需要实现具体逻辑 return null; // 实际实现中需要返回有效的OAuth2User } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { // 如果需要,可以在这里添加后处理逻辑 } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { // 如果需要,可以在这里添加完成后的逻辑 } } 9. 注册拦截器 package com.example.microservice.config; import com.example.microservice.interceptor.OAuth2AuthenticationInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.session.SessionRepository; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { private final SessionRepository<?> sessionRepository; public WebConfig(SessionRepository<?> sessionRepository) { this.sessionRepository = sessionRepository; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new OAuth2AuthenticationInterceptor(sessionRepository)); } } 测试会话共享 创建一个控制器来测试会话共享功能: package com.example.microservice.controller; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.core.user.OAuth2User; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; @RestController public class TestController { @GetMapping("/api/user-info") public Map<String, Object> getUserInfo(@AuthenticationPrincipal OAuth2User oauth2User, HttpSession session) { Map<String, Object> userInfo = new HashMap<>(); if (oauth2User != null) { userInfo.put("name", oauth2User.getAttribute("name")); userInfo.put("email", oauth2User.getAttribute("email")); userInfo.put("authorities", oauth2User.getAuthorities()); } userInfo.put("sessionId", session.getId()); userInfo.put("creationTime", session.getCreationTime()); userInfo.put("lastAccessedTime", session.getLastAccessedTime()); return userInfo; } @GetMapping("/api/session-test") public Map<String, Object> testSession(HttpSession session) { // 获取或设置会话属性 Object count = session.getAttribute("counter"); int newCount = 1; if (count != null) { newCount = (Integer) count + 1; } session.setAttribute("counter", newCount); Map<String, Object> result = new HashMap<>(); result.put("sessionId", session.getId()); result.put("counter", newCount); result.put("message", "此计数在所有微服务中共享"); return result; } } 部署架构 在实际微服务架构中,通常会通过API网关统一管理认证和会话。这里是一个简化的部署架构图: +----------------+ +----------------+ | API Gateway | | Auth Service | | (Zuul/Spring |---->| (OAuth2 Server)| | Cloud Gateway)| +----------------+ +-------+--------+ | v +-------+--------+ +-------+--------+ | Microservice A |<--->| Redis Session | +----------------+ | Storage | ^ +----------------+ | ^ v | +-------+--------+ | | Microservice B |-------------+ +----------------+ 安全注意事项 在实现会话共享时,需要注意以下安全事项: 确保Redis服务器安全配置,启用密码认证 使用SSL/TLS加密Redis连接 会话ID应使用足够长的随机字符串,防止被猜测 设置合理的会话超时时间 使用secure和httpOnly标志保护会话Cookie 考虑使用JWT等无状态认证方案作为补充 性能优化 为了提高系统性能,可以考虑以下优化措施: 配置Redis连接池 使用Redis集群提高可用性 合理设置会话数据的过期时间 仅存储必要的会话信息,避免存储大量数据 监控Redis性能指标,及时进行扩容 总结 通过Spring Security OAuth2与Spring Session Redis的整合,我们实现了微服务架构下的会话共享方案。这种方案具有以下优势: 统一的认证机制:通过OAuth2提供标准的认证流程 高效的会话存储:利用Redis高性能特性存储会话数据 透明的会话共享:微服务无需感知会话存储细节 良好的扩展性:可以方便地扩展到更多微服务 这种方案适用于大多数微服务架构,特别是那些需要保持用户状态的系统。通过合理配置和优化,可以构建一个安全、高效、可扩展的会话管理系统。
2018年11月15日
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-11-12
FireShot:Chrome 上最强大的网页截图插件推荐
FireShot:Chrome 上最强大的网页截图插件推荐 在日常浏览网页的过程中,我们经常会遇到需要截图的场景,比如保存网页内容、制作教程、分享信息等。而 Chrome 自带的截图功能较为有限,无法满足各种复杂的需求。今天推荐一款功能强大的网页截图插件——FireShot,它能够帮助你轻松截取完整网页,并支持多种格式保存。 FireShot 是什么? FireShot 是一款强大的 Chrome 插件,专门用于捕捉网页截图。它提供比浏览器自带截图工具更丰富的功能,比如截取整个网页、选定区域、可视区域,甚至支持直接编辑和标注截图。 FireShot 的主要功能 1. 多种截图模式 捕捉整个网页:一键截图整个网页,无需手动滚动。 捕捉可见部分:只截取当前屏幕可见的区域。 捕捉选定区域:自由框选需要截图的部分。 捕捉特定元素:自动识别网页上的元素,如图片、文本框等。 2. 强大的编辑功能 FireShot 内置编辑器允许你对截图进行裁剪、标注、添加文本、绘制箭头等操作,方便后续处理和分享。 3. 多种导出格式 截图可以保存为 PNG、JPEG、PDF,还支持直接复制到剪贴板或发送至电子邮件。 4. PDF 转换功能 FireShot 允许用户将整个网页直接转换为 PDF,并且可以选择是否保留超链接。 5. 云存储和分享 截图可以直接上传到 Google Drive、Dropbox、OneNote 或发送到邮件,非常适合团队协作。 FireShot 为什么值得推荐? 一键截图整个网页,无需滚动拼接。 支持多种截图模式,满足不同需求。 内置编辑器,方便直接修改截图。 支持多种格式导出,适用于不同应用场景。 云端同步与分享,适合办公和团队协作。 如何安装 FireShot? 打开 Chrome 浏览器,进入 Chrome 网上应用店。 搜索 "FireShot",找到官方插件。 点击 添加到 Chrome,并按照提示完成安装。 结语 如果你经常需要截取网页,FireShot 绝对是不可或缺的 Chrome 插件。它的全页面截图、编辑功能和多种导出格式,让网页截图变得更加高效便捷。快去安装 FireShot,提升你的截图体验吧!
2018年11月12日
2018-10-16
Phabricator Centos7 安装部署
1. mkdir & download mkdir -p /data/app/pha cd /data/app/pha wget http://www.phabricator.com/rsrc/install/install_rhel-derivs.sh chmod +x install_rhel-derivs.sh ./install_rhel-derivs.sh 2. add nginx config vi /etc/nginx/conf.d/pha.conf server { server_name p.com; root /data/app/pha/phabricator/webroot; location / { index index.php; rewrite ^/(.*)$ /index.php?__path__=/$1 last; } location = /favicon.ico { try_files $uri =204; } location /index.php { fastcgi_pass localhost:9000; fastcgi_index index.php; #required if PHP was built with --enable-force-cgi-redirect fastcgi_param REDIRECT_STATUS 200; #variables to make the $_SERVER populate in PHP fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx/$nginx_version; fastcgi_param REMOTE_ADDR $remote_addr; } } 2. add apache config vi /etc/httpd/conf/httpd.conf <VirtualHost *:80> # Change this to the domain which points to your host. ServerName team.idinu.com # Change this to the path where you put 'phabricator' when you checked it # out from GitHub when following the Installation Guide. # # Make sure you include "/webroot" at the end! DocumentRoot /opt/phabricator/webroot RewriteEngine on RewriteRule ^/rsrc/(.*) - [L,QSA] RewriteRule ^/favicon.ico - [L,QSA] RewriteRule ^(.*)$ /index.php?__path__=$1 [B,L,QSA] </VirtualHost> <Directory "/opt/phabricator/webroot"> Order allow,deny Allow from all Require all granted </Directory> Apache 2.4 and Newer <Directory "/path/to/phabricator/webroot"> Require all granted </Directory> 3. 初始化 phabricator/ $ ./bin/storage upgrade 4. 本机添加默认对应domain vi /etc/hosts 127.0.0.1 ph.xx.com 5. 更新 Updating PhabricatorSince Phabricator is under active development, you should update frequently. To update Phabricator: Stop the webserver (including php-fpm, if you use it). Run git pull in libphutil/, arcanist/ and phabricator/. Run phabricator/bin/storage upgrade. Restart the webserver (and php-fpm, if you stopped it earlier). For more details, see Configuration Guide. You can use a script similar to this one to automate the process: http://www.phabricator.com/rsrc/install/update_phabricator.sh 5. 常见配置问题修复 1. Base URI Not Configured 设置对应的url phabricator/ $ ./bin/config set phabricator.base-uri 'http://p.com/' 2. Phabricator Daemons Are Not Running 通过phd用户启用phd phabricator/ $ ./bin/phd start 详细过程: vi /etc/passwd phd:x:501:501:Phd:/var/tmp/phd:/bin/bash git:x:500:500:Git:/data/app/repo:/bin/bash vi /etc/shadow phd:!!:16135:::::: git:NP:16135:0:99999:7::: visudo ## HTTP: apache ALL=(phd) SETENV: NOPASSWD: /usr/libexec/git-core/git-http-backend ## SSH: git ALL=(phd) SETENV: NOPASSWD: /usr/bin/git-upload-pack, /usr/bin/git-receive-pack, /bin/sh vi /etc/group git:x:500:git phd:x:501:phd ./bin/config set phd.user phd ./bin/config set diffusion.ssh-user git cp /data/app/pha/phabricator/resources/sshd/phabricator-ssh-hook.sh /usr/libexec/phabricator-ssh-hook.sh chown root /usr/libexec/phabricator-ssh-hook.sh chmod 755 /usr/libexec/phabricator-ssh-hook.sh vi /usr/libexec/phabricator-ssh-hook.sh Change VCSUSER="vcs-user" to VCSUSER="git" Change ROOT="/path/to/phabricator" to ROOT="/data/app/pha/phabricator" cp /data/app/pha/phabricator/resources/sshd/sshd_config.phabricator.example /etc/ssh/sshd_config.phabricator vi /etc/ssh/sshd_config.phabricator Change AuthorizedKeysCommand /etc/phabricator-ssh-hook.sh to AuthorizedKeysCommand /usr/libexec/phabricator-ssh-hook.sh Change AuthorizedKeysCommandUser vcs-user to AuthorizedKeysCommandUser git ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key sudo /usr/sbin/sshd -f /etc/ssh/sshd_config.phabricator 需要添加一个服务器的rsa key ssh-keygen -t rsa cat ~/.ssh/id_rsa.pub Go to xx.com Settings->SSH Public Keys -> Upload .. 验证是否成功 echo {} | ssh git@p.com conduit conduit.ping 修改默认ssh端口22到222 vi /etc/ssh/sshd_config Change port 22 to port 222 systemctl restart sshd firewall-cmd --zone=public --add-port=222/tcp --permanent firewall-cmd --reload 用phd用户启动phd mkdir -p /var/tmp/phd chown phd:phd -R /var/tmp/phd ./bin/phd start
2018年10月16日
1
...
7
8
9
...
18