springboot 整合oauth2

1、@EnableOAuth2Client:客户端,提供OAuth2RestTemplate,用于客户端访问资源服务。 
简要步骤:客户端访问资源->客户端发现没有资源访问token->客户端根据授权类型生成跳转url->浏览器 302 到认证授权服务进行认证、授权。
2、@EnableOAuth2Sso:应用系统,使用远端认证授权服务,替换应用自身的用户登录鉴权security逻辑,实现单点登录功能。 
简要步骤:访问应用系统资源-> 应用系统发现未登录-> 302 跳转到登录页面(登录页面地址已经与获取token逻辑自动关联)-> 应用系统发现符合获取token条件,根据授权类型拼装url->302 跳转到认证授权地址(认证授权服务提供)进行认证、授权。
3、@EnableAuthorizationServer:认证授权服务,提供用于获取token,解析token相关功能,实现认证、授权功能。
具体见 Spring Security 文章目录中的 Spring Cloud OAuth2 五种授权方式介绍。
4、@EnableResourceServer:资源服务,提供基于token的资源访问功能。

<--认证服务器配置-->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId>
</dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
@Configuration
@EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {@Autowiredprivate DataSource dataSource;@Autowiredprivate AuthenticationManager authenticationManager;@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate RedisConnectionFactory redisConnectionFactory;@Autowiredprivate CodeStoreService codeStoreService;@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {security.allowFormAuthenticationForClients().tokenKeyAccess("isAuthenticated()").checkTokenAccess("isAuthenticated()");}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.jdbc(dataSource).passwordEncoder(passwordEncoder);}@Beanpublic JwtTokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic RedisTokenStore redisTokenStore() {return new RedisTokenStore(redisConnectionFactory);}@Beanpublic AuthorizationServerTokenServices authorizationServerTokenServices() {DefaultTokenServices defaultTokenServices = new DefaultTokenServices();defaultTokenServices.setTokenStore(redisTokenStore());defaultTokenServices.setSupportRefreshToken(true);defaultTokenServices.setRefreshTokenValiditySeconds(30 * 60 * 1000);defaultTokenServices.setAccessTokenValiditySeconds(30 * 69 * 1000);return defaultTokenServices;}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {ClassPathResource resource = new ClassPathResource("user.jks");KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, "123456".toCharArray());JwtAccessTokenConverter jwtTokenConverter = new JwtAccessTokenConverter();jwtTokenConverter.setKeyPair(keyStoreKeyFactory.getKeyPair("xm"));return jwtTokenConverter;}@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {endpoints.allowedTokenEndpointRequestMethods(HttpMethod.POST);endpoints.authenticationManager(authenticationManager);//endpoints.accessTokenConverter(jwtAccessTokenConverter());endpoints.tokenServices(authorizationServerTokenServices());endpoints.authorizationCodeServices(codeStoreService);}
}

spring security 的配置文件

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate CustomUserDetailsService userDetailsService;@Autowiredprivate SuccessAuthentication successAuthentication;@Autowiredprivate FailureAuthentication failureAuthentication;@Autowiredprivate UnauthorizedEntryPoint unauthorizedEntryPoint;@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);}@Override@Beanpublic AuthenticationManager authenticationManagerBean() throws Exception {return super.authenticationManagerBean();}@Overridepublic void configure(WebSecurity web) {web.ignoring().mvcMatchers("/assets/**", "/css/**", "/images/**");}@Overrideprotected void configure(HttpSecurity http) throws Exception {/*http.csrf().disable();http.authorizeRequests().antMatchers( "/oauth/token", "/check/token").permitAll();http.authorizeRequests().antMatchers("/success").hasRole("USER").antMatchers("/success").hasRole("ADMIN").antMatchers("/user/r1").hasRole("USER").antMatchers("/user/r2").hasRole("ADMIN").antMatchers("/user/p1").hasAuthority("p1").antMatchers("/user/p2").hasAuthority("p2").anyRequest().authenticated().and().formLogin().loginPage("/login").successForwardUrl("/success").and().exceptionHandling().accessDeniedHandler(new CustomAccessDecisionHandler()).and().httpBasic();*/http.csrf().disable();http.formLogin().loginPage("/login")//.successHandler(successAuthentication)//.failureHandler(failureAuthentication).and().authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated().and()/*.exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint).and()*/.rememberMe(remember ->remember.rememberMeParameter("remember-me").rememberMeCookieName("remember-me").tokenValiditySeconds(30 * 1000).userDetailsService(userDetailsService));}
}

资源服务器使用spring-boot-starter-oauth2-client

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.security.oauth.boot</groupId><artifactId>spring-security-oauth2-autoconfigure</artifactId></dependency><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><dependency><groupId>org.thymeleaf.extras</groupId><artifactId>thymeleaf-extras-springsecurity5</artifactId><version>3.0.4.RELEASE</version>
</dependency>
spring.security.oauth2.client.registration.user.provider=user
spring.security.oauth2.client.registration.user.client-id=user-service
spring.security.oauth2.client.registration.user.client-secret=root
spring.security.oauth2.client.registration.user.authorization-grant-type=authorization_code
spring.security.oauth2.client.registration.user.redirect-uri=http://localhost:9091/login
spring.security.oauth2.client.registration.user.scope=all
spring.security.oauth2.client.provider.user.authorization-uri=http://localhost:9091/oauth/authorize
spring.security.oauth2.client.provider.user.token-uri=http://localhost:9091/oauth/token
spring.security.oauth2.client.provider.user.user-info-uri=http://localhost:9091/oauth2/userinfo
spring.security.oauth2.client.provider.user.user-name-attribute=sub
spring.security.oauth2.client.provider.user.jwk-set-uri=http://localhost:9091/oauth/token_key
spring.security.oauth2.resourceserver.jwt.jwk-set-uri=http://localhost:9091/oauth/token_key
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().anyRequest().authenticated();http.oauth2ResourceServer(oauth2->oauth2.jwt());// 改成oauth2Login 就是oauth 登录}
}

参考资料

https://www.cnblogs.com/atwood-pan/p/17787904.html

OAuth2 - @EnableResourceServer vs @EnableOAuth2Sso | Baeldung

Spring-Security-OAuth2-Client | zyc的博客

spring oauth2实现单点登录,Vue+spring boot+oauth2前后端分离 - 简书

(二)、Spring Security OAuth2 四个常用注解说明_oauth2clientcontext是什么-CSDN博客

https://www.cnblogs.com/atwood-pan/p/17787904.html

springsecurity oauth2实现前后端分离项目的SSO技术点总结_spring outh2 前后端分离-CSDN博客

【Spring Security OAuth2 Client】基本介绍以及定制开发_spring-boot-starter-oauth2-client-CSDN博客

springboot整合Oauth2_spring-boot-starter-oauth2-client-CSDN博客

https://www.cnblogs.com/simpleito/p/15786122.html

自定义grant_type 以及第三方登录。

总之,这个东西比较复杂,暂且放过
 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/718054.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Dockerfile构建过程详解

Dockerfile介绍 docker是用来构建docker镜像的文件&#xff01;命令参数脚本&#xff01; 构建步骤&#xff1a; 1、编写一个dockerfile文件 2、docker build构建成为一个镜像 3、docker run 运行镜像 …

PDF转Excel的未来:人工智能技术如何提升转换效率和准确性

随着信息技术的快速发展&#xff0c;PDF和Excel作为两种重要的文件格式&#xff0c;在日常生活和工作中扮演着至关重要的角色。PDF以其独特的跨平台阅读特性&#xff0c;成为了文件分享和传输的首选格式&#xff1b;而Excel则以其强大的数据处理能力&#xff0c;成为了数据分析…

【二分查找】【C++算法】378. 有序矩阵中第 K 小的元素

作者推荐 视频算法专题 本文涉及的基础知识点 二分查找算法合集 LeetCode378. 有序矩阵中第 K 小的元素 给你一个 n x n 矩阵 matrix &#xff0c;其中每行和每列元素均按升序排序&#xff0c;找到矩阵中第 k 小的元素。 请注意&#xff0c;它是 排序后 的第 k 小元素&…

机器人持续学习基准LIBERO系列10——文件结构

0.前置 机器人持续学习基准LIBERO系列1——基本介绍与安装测试机器人持续学习基准LIBERO系列2——路径与基准基本信息机器人持续学习基准LIBERO系列3——相机画面可视化及单步移动更新机器人持续学习基准LIBERO系列4——robosuite最基本demo机器人持续学习基准LIBERO系列5——…

力扣日记3.3-【回溯算法篇】332. 重新安排行程

力扣日记&#xff1a;【回溯算法篇】332. 重新安排行程 日期&#xff1a;2023.3.3 参考&#xff1a;代码随想录、力扣 ps&#xff1a;因为是困难题&#xff0c;望而却步了一星期。。。T^T 332. 重新安排行程 题目描述 难度&#xff1a;困难 给你一份航线列表 tickets &#xf…

牛客小白月赛86

A-水盐平衡_牛客小白月赛86 (nowcoder.com) #include<bits/stdc.h> #define endl \n #define int long long using namespace std; int a,b,c,d; void solve() {cin>>a>>b>>c>>d;if((double)a/b>(double)c/d) cout<<S<<endl;els…

关于脉冲负载应用中电阻器,您需要了解的 11 件事?

不幸的是&#xff0c;电阻器在脉冲负载下可能会失效。当脉冲功率耗散到器件的电阻元件时&#xff0c;它会产生热量并增加电阻器的温度。过热会损坏电阻元件&#xff0c;导致电阻变化甚至设备开路。为了避免在设计中出现这种情况&#xff0c;以下是您在选择元件时应了解的有关电…

excel统计分析——拉丁方设计

参考资料&#xff1a;生物统计学 拉丁方设计也是随机区组设计&#xff0c;是对随机区组设计的一种改进。它在行的方向和列的方向都可以看成区组&#xff0c;因此能实现双向误差的控制。在一般的试验设计中&#xff0c;拉丁方常被看作双区组设计&#xff0c;用于提高发现处理效应…

Skipped breakpoint at because it happened inside debugger evaluation亲测可用

问题描述&#xff1a; 在多线程项目中&#xff0c;在idea中打断点时&#xff0c;有时会遇到下面这种情况&#xff1a; idea左下角出现一行红底或者绿底文字提示&#xff1a; Skipped breakpoint at because it happened inside debugger evaluation 然后我们能感受到的就是…

HTML中自定义鼠标右键菜单

今天突然有人跟我提到了HTML中如何自定义鼠标右键菜单&#xff0c;这里大概记录一下吧&#xff0c;方便下次直接复制。免得还去看API文档。 文章目录 HTML中自定义鼠标右键菜单结果如下所示可以稍微改一下鼠标悬浮到右键菜单时的样式结果如下所示 只在某个特定的div才可以显示…

javascript 的eval()和with是干嘛的

原来JavaScript 中的eval() 和 with 是两个强大的功能&#xff0c;但同时它们也具有潜在风险的特性&#xff0c;所以谨慎使用。 首先说说eval() 函数&#xff1a; 它接收一个字符串参数&#xff0c;并将其作为 JavaScript 代码来解析和执行。 这意味着你可以使用 eval() 动态地…

《Scratch等级认证CCF-GESP真题解析》专栏总目录

❤️ 专栏名称:《Scratch等级认证CCF-GESP真题解析》 🌸 专栏介绍:中国计算机学会GESP《CCF编程能力等级认证》Scratch图形化编程(1~4级)历届真题解析。 🚀 订阅专栏:订阅后可阅读专栏内所有真题解析,真题持续更新中,限时9.9元,欢迎订阅! Scratch图形化编程一级 序…

2368. 受限条件下可到达节点的数目

2368. 受限条件下可到达节点的数目 题目链接&#xff1a;2368. 受限条件下可到达节点的数目 代码如下&#xff1a; //深度优先遍历 //参考&#xff1a;https://leetcode.cn/problems/reachable-nodes-with-restrictions/solutions/2662538/shu-shang-dfspythonjavacgojsrust-…

C++自学精简实践教程

一、介绍 1.1 教程特点 一篇文章从入门到就业有图有真相&#xff0c;有测试用例&#xff0c;有作业&#xff1b;提供框架代码&#xff0c;作业只需要代码填空规范开发习惯&#xff0c;培养设计能力 1.2 参考书 唯一参考书《C Primer 第5版》​参考书下载&#xff1a; 蓝奏云…

Acwing---3777. 砖块

砖块 1.题目2.基本思想3.代码实现 1.题目 n 个砖块排成一排&#xff0c;从左到右编号依次为 1∼n。 每个砖块要么是黑色的&#xff0c;要么是白色的。 现在你可以进行以下操作若干次&#xff08;可以是 0 次&#xff09;&#xff1a; 选择两个相邻的砖块&#xff0c;反转它…

STL——stack

目录 stack stack都有哪些接口 模拟实现一个stack stack 1. stack是一种容器适配器&#xff0c;专门用在具有后进先出操作的上下文环境中&#xff0c;其删除只能从容器的一端进行元素的插入与提取操作。 2. stack是作为容器适配器被实现的&#xff0c;容器适配器即…

数据分析-Pandas数据的画图设置

数据分析-Pandas数据的画图设置 数据分析和处理中&#xff0c;难免会遇到各种数据&#xff0c;那么数据呈现怎样的规律呢&#xff1f;不管金融数据&#xff0c;风控数据&#xff0c;营销数据等等&#xff0c;莫不如此。如何通过图示展示数据的规律&#xff1f; 数据表&#x…

春招!启动了

大家好&#xff0c;我是洋子。今年的春招很多企业已经开始招聘了&#xff0c;像美团今年继续发力&#xff0c;24届春招以及25届暑期转正实习一共招聘4000人。另外&#xff0c;阿里&#xff0c;京东&#xff0c;顺丰等公司也已经开始春招&#xff0c;可以说招聘的号角已经正式吹…

GO语言学习笔记(与Java的比较学习)(十)

错误处理与测试 Go 没有像 Java 和 .NET 那样的 try/catch 异常机制&#xff1a;不能执行抛异常操作。但是有一套 defer-panic-and-recover 机制 错误处理 Go 有一个预先定义的 error 接口类型 type error interface {Error() string } errors 包中有一个 errorString 结构…

十二、类与声明

类与声明 什么是类&#xff1f; 前情总结 前面22讲的课基本上就做了两件事 学习C#的基本元素学习类的成员 析构函数&#xff1a; 当对象不再被引用的时候&#xff0c;就会被垃圾回收器gc&#xff0c;回收。而收回的过程当中&#xff0c;如果需要做什么事情&#xff0c;就放在…