首页
在线工具
搜索
1
如何将Virtualbox和VMware虚拟机相互转换
2
使用Metrics指标度量工具监控Java应用程序性能(Gauges, Counters, Histograms, Meters和 Timers实例)
3
Markdown正确使用姿势
4
Typora+Picgo图床使用
5
Jumpserver的MFA配置
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
AI人工智能
Search
标签搜索
Angular
Docker
Phabricator
SpringBoot
Java
Chrome
SpringSecurity
SpringCloud
DDD
Git
Mac
K8S
Kubernetes
ESLint
SSH
高并发
Eclipse
Javascript
Vim
Centos
Jonathan
累计撰写
88
篇文章
累计收到
0
条评论
首页
栏目
杂谈与随笔
工具与效率
源码阅读
技术管理
运维
数据库
前端开发
后端开发
AI人工智能
页面
搜索到
88
篇与
的结果
2018-12-29
Git 提交的正确姿势:Commit message 编写指南
Git提交的正确姿势:Commit message编写指南 第一行不超过50个字符 第二行空一行 第三行开始是描述信息,每行长度不超过72个字符,超过了自己换行。 描述信息主要说明: 这个改动为什么是必要的? 这个改动解决了什么问题? 会影响到哪些其他的代码? 最后最好有一个相应ticket的链接 摘要:Git每次提交代码,都要写Commit message(提交说明),否则就不允许提交。 Git每次提交代码,都要写Commit message(提交说明),否则就不允许提交。 $ git commit -m "hello world" 上面代码的-m参数,就是用来指定commit mesage的。 如果一行不够,可以只执行git commit,就会跳出文本编译器,让你写多行。 $ git commit 基本上,你写什么都行(这里,这里和这里)。 Nov 12, 2013 Tenth Commit N nishugames authored 3 months ago Oct 27, 2013 Ninth Commit N nishugames authored 4 months ago Oct 26, 2013 Eighth Commit N nishugames authored 4 months ago Seventh Commit nishugames authored 4 months ago Sixth Commit N nishugames authored 4 months ago Fifth Commit N nishugames authored 4 months ago Oct 24, 2013 Fourth Commit ... N nishugames authored 4 months ago Third commit N nishugames authored 4 months ago 但是,一般来说,commit message应该清晰明了,说明本次提交的目的。 Commits on Jan 5, 2016 docs(error/SrootScope/inprog): add missing "Stimeout" wytesk133 committed with petebacondarwin 10 days ago docs(tutorial/2): add e2e test missing filename monkpit committed with petebacondarwin 3 hours ago revert: feat(Scompile): Allow ES6 classes as controllers with bindTo... petebacondarwin committed 3 hours ago fix(SanimateCss): only (de)register listeners when events have been a.. Narretz committed 25 days ago fix(loader): use 'false' as default value for transclude' in compone... sarod committed with petebacondarwin 18 days ago Commits on Jan 3, 2016 feat(Scompile): Allow ES6 classes as controllers with bind ToControl.. Igalfaso committed 21 days ago chore(*): Updated year in licence leuanG committed with Igalfaso 3 days ago Commits on Jan 1, 2016 docs: reorganize information about interpolation Narretz committed on Dec 6, 2015 docs: add docs for ngPattern, ngMinlength, ngMaxlength Narretz committed on Sep 24, 2015 docs(SinterpolateProvider): remove superfluous ng-app attribute Narretz committed 4 days ago 目前,社区有多种Commit message的写法规范。本文介绍Angular规范(见上图),这是目前使用最广的写法,比较合理和系统化,并且有配套的工具。 一、Commit message的作用 格式化的Commit message,有几个好处。 (1)提供更多的历史信息,方便快速浏览 比如,下面的命令显示上次发布后的变动,每个commit占据一行。你只看行首,就知道某次commit的目的。 $ git log <last tag> HEAD --pretty=format:%s fix(ng-bind-html): watch string value instead of wrapper (4 days ago) chore(sce): remove unused function (4 days ago) <Chirayu Krishnappa> fix(ngInclude): don't break attribute bindings on ngInclude-ed element fix(ngView): IE8 regression due to expando on non-element nodes (4 days docs(ngClass): fix grammar (4 days ago) <Dave Peticolas> docs(ngCloak): fix grammar, clarity (4 days ago) <Dave Peticolas> docs(ngModelController): clarify issue with isolated scope directive docs(input): fix spelling error and reword for clarity(5 days ago) doc(ngApp): fix grammar(5 days ago)<Dave Peticolas> (origin/g3_v1_2) docs($exceptionHandler): add an example of overriding docs(FAQ): update jQuery compatibility (5 days ago) <Pete Bacon Darwin) docs(guide/services): rewording of explanation (5 days ago) <Pete Bacor docs(guide/services): explain services in plain 1anguage (5 days ago) docs(guide/i18n): change non-existent de-ge to de-de (5 days ago) <Maax docs(ngForm): fix grammar and improve explanation (5 days ago) <Dave Pe docs: update sticker ordering info in FAQ (6 days ago)<naomiblack> docs(ngResource): fix typo (6 days ago) <Tim Statler> docs(ngShowHide): fix typo (6 days ago) <Roberto Bonvallet> docs(guide/$location): describe workaround for collocated apps (6 days docs(tutorial/step_03):add info about karma-ng-scenario plug-in (6 day fix(scenario): include "not "in error messages if test is inverted (6 fix($parse): disallow access to window and dom in expressions (7 days (2)可以过滤某些commit(比如文档改动),便于快速查找信息 比如,下面的命令仅仅显示本次发布新增加的功能。 $ git log <last release> HEAD --grep feature (3)可以直接从commit生成Change log Change Log是发布新版本时,用来说明与上一个版本差异的文档,详见后文。 0.0.4 (2015-07-21) Bug Fixes ·glossary: fix bad things in the glossary (9e572e9) ·intro: fix issue with the intro not working (6de0d8a) Features ·part2: add better veggie lorem ipsum text (06912f4) ·part2: add much better lorem ipsum text (7aaf238) BREAKING CHANGES ·Adding better veggie lorem ipsum text is great and all but it breaks all the other meaty components. Be mindful of this when you test. 二、Commit message的格式 每次提交,Commit message都包括三个部分:Header、Body和Footer。 <type>(<scope>): <subject> <空一行> <body> <空一行> <footer> 其中,Header是必需的,Body和Footer可以省略。 不管是哪一个部分,任何一行都不得超过72个字符(或100个字符)。这是为了避免自动换行影响美观。 2.1 Header Header部分只有一行,包括三个字段: type(必需)、scope(可选)和subject (必需)。 (1) type type用于说明commit的类别,只允许使用下面7个标识。 feat: 新功能(feature) fix: 修补bug docs: 文档(documentation) style:格式(不影响代码运行的变动) refactor: 重构 (即不是新增功能,也不是修改bug的代码变动) test:增加测试 chore:构建过程或辅助工具的变动 如果type为feat和fix,则该commit将肯定出现在Change log之中。其他情况(docs、chore、style、refactor、test)由你决定,要不要放入Change log,建议是不要。 (2) scope scope用于说明commit影响的范围,比如数据层、控制层、视图层等等,视项目不同而不同。 (3) subject subject是commit目的的简短描述,不超过50个字符。 以动词开头,使用第一人称现在时,比如change,而不是changed或changes 第一个字母小写 结尾不加句号(.) 2.2 Body Body部分是对本次commit的详细描述,可以分成多行。下面是一个范例。 More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. Further paragraphs come after blank lines. - Bullet points are okay, too - Use a hanging indent 有两个注意点。 使用第一人称现在时,比如使用change而不是changed或changes。 应该说明代码变动的动机,以及与以前行为的对比。 2.3 Footer Footer部分只用于两种情况。 (1)不兼容变动 如果当前代码与上一个版本不兼容,则Footer部分以BREAKING CHANGE开头,后面是对变动的描述、以及变动理由和迁移方法。 BREAKING CHANGE: isolate scope bindings definition has changed. To migrate the code follow the example below: Before: scope:{ myAttr: 'attribute', } After: scope:{ myAttr: } The removed inject' wasn't generally useful for directives so there should be no code using it. (2)关闭Issue 如果当前commit针对某个issue,那么可以在Footer部分关闭这个issue。 Closes #234 也可以一次关闭多个issue。 Closes #123, #245, #992 2.4 Revert 还有一种特殊情况,如果当前commit用于撤销以前的commit,则必须以revert:开头,后面跟着被撤销Commit的Header。 revert: feat(pencil): add 'graphiteWidth' option This reverts commit 667ecc1654a317a13331b17617d973392f415f02. Body部分的格式是固定的,必须写成This reverts commit <hash>.,其中的hash是被撤销commit的SHA标识符。 如果当前commit与被撤销的commit,在同一个发布(release)里面,那么它们都不会出现在Change log里面。如果两者在不同的发布,那么当前commit,会出现在Change log的Reverts小标题下面。 三、Commitizen Commitizen是一个撰写合格Commit message的工具。 安装命令如下。 $ npm install -g commitizen $ npm install -g cz-conventional-changelog 创建初始化package.json { "name": "yjauth", "version": "0.0.1", "description": "Description for yjauth", "private": true, "config":{ "commitizen":{ "path": "cz-conventional-changelog" } }, "dependencies":{ }, "devDependencies":{ }, "engines":{ "node": ">=0.12.0" } } 然后,在项目目录里,运行下面的命令,使其支持Angular的Commit message格式。 $ commitizen init cz-conventional-changelog --save --save-exact 以后,凡是用到git commit命令,一律改为使用git cz。这时,就会出现选项,用来生成符合格式的Commit message。 ng-poopy master x git add. ng-poopy master X git cz All commit message lines will be cropped at 100 characters. ? Select the type of change that you're committing: (Use arrow keys) > feat: A new feature fix: A bug fix docs: Documentation only changes style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc) refactor: A code change that neither fixes a bug or adds a feature perf: A code change that improves performance test: Adding missing tests chore: Changes to the build process or auxiliary tools and libraries such as documentation generation 四、validate-commit-msg validate-commit-msg用于检查Node项目的Commit message是否符合格式。 安装: npm install ghooks --save-dev 接着,把这个脚本加入Git的hook。下面是在package.json里面使用ghooks,把这个脚本加为commit-msg时运行。 "config":{ "ghooks":{ "commit-msg": "./validate-commit-msg.js" } } 然后,每次git commit的时候,这个脚本就会自动检查Commit message是否合格。如果不合格,就会报错。 $ git add -A $ git commit -m "edit markdown" INVALID COMMIT MSG: does not match "<type>(<scope>): <subject>"! was: edit markdown 五、生成Change log 如果你的所有Commit都符合Angular格式,那么发布新版本时,Change log就可以用脚本自动生成(例1, 例2, 例3)。 生成的文档包括以下三个部分。 New features Bug fixes Breaking changes. 每个部分都会罗列相关的commit,并且有指向这些commit的链接。当然,生成的文档允许手动修改,所以发布前,你还可以添加其他内容。 conventional-changelog就是生成Change log的工具,运行下面的命令即可。 $ npm install -g conventional-changelog-cli $ cd my-project $ conventional-changelog -p angular -i CHANGELOG.md -s This will not overwrite any previous changelog. The above generates a changelog based on commits since the last semver tag that match the pattern of a "Feature", "Fix", "Performance Improvement" or "Breaking Changes". If you first time use this tool and want to generate all previous changelog, you could do $ conventional-changelog -p angular -i CHANGELOG.md -s -r 0 上面命令不会覆盖以前的Change log,只会在CHANGELOG.md的头部加上自从上次发布以来的变动。 如果你想生成所有发布的Change log,要改为运行下面的命令。 $ conventional-changelog -p angular -i CHANGELOG.md -w -r 0 为了方便使用,可以将其写入package.json的scripts字段。 { "scripts":{ "changelog": "conventional-changelog -p angular -i CHANGELOG.md -w -r 0" } }
2018年12月29日
2018-12-11
Vimium:提升浏览效率的终极 Chrome 插件
Vimium:提升浏览效率的终极 Chrome 插件 在日常浏览网页时,我们往往依赖鼠标进行点击、滚动、切换标签等操作,但这些动作有时显得低效,特别是对于习惯键盘操作的用户来说。今天要推荐的 Chrome 插件——Vimium,能够帮助你实现高效的无鼠标浏览体验。 Vimium 是什么? Vimium 是一款基于 Vim 快捷键的 Chrome 浏览器插件,它允许用户通过键盘快捷键完成网页导航、标签管理、页面滚动等操作,大大提升浏览效率。Vimium 适合那些喜欢 Vim 编辑器或者希望减少鼠标使用的用户。 Vimium 主要功能 快速跳转链接 按 f 键后,每个可点击的链接都会标注一个快捷键,输入相应的字符即可访问该链接。 标签页管理 J / K:切换到左/右侧的标签页。 t:打开新标签页。 x:关闭当前标签页。 X:恢复最近关闭的标签页。 高效的页面滚动 h / l:左右滚动页面。 j / k:上下滚动页面。 gg / G:跳转到页面顶部/底部。 d / u:向下/向上滚动半屏。 网页搜索 / 进入搜索模式,输入关键词并按 Enter 进行搜索。 n / N:跳转到下一个/上一个匹配结果。 复制与打开 URL yy:复制当前页面 URL。 p:打开剪贴板中的 URL。 Vimium 配置与自定义 Vimium 允许用户自定义快捷键,以适应个人习惯。在 Vimium 的选项页面,你可以修改默认的键位绑定,还可以添加黑名单,防止 Vimium 在某些特定网站上生效。 为什么选择 Vimium? 极大提升浏览效率:使用键盘操作比鼠标更快,尤其是在处理大量网页时。 降低鼠标依赖:减少手部移动,提高使用舒适度。 高度可定制:可以根据个人习惯调整快捷键。 结语 如果你是 Vim 爱好者,或者希望提升网页浏览的效率,那么 Vimium 绝对是一个值得尝试的 Chrome 插件。安装后可能需要一定的时间适应,但一旦掌握,就能大幅提升工作和学习效率。快去 Chrome 网上应用店搜索 "Vimium" 下载体验吧!
2018年12月11日
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日
1
...
7
8
9
...
18