SpringSecurity+OAuth2.0+JWT实现单点登录应用
gitee项目练习地址:https://gitee.com/xzq25_com/springsecurity.oauth2

OAuth2.0单点登录实践

  • 一、搭建OAuth授权服务器,采用授权码模式+JWT令牌
  • 二、创建服务client:SSOA、SSOB 并进行测试

一、搭建OAuth授权服务器,采用授权码模式+JWT令牌

目录如下:

1,导入依赖:

   <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-oauth2</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-security</artifactId></dependency><dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency></dependencies><dependencyManagement><dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>${spring-cloud.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement>

2,配置AuthorizationServerConfig认证授权服务

/*** @author xzq* @description: 授权服务器* @date 2022/12/5 13:43*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {@Autowiredprivate PasswordEncoder passwordEncoder;@Autowiredprivate TokenStore jwtTokenStore;@Autowiredprivate JwtAccessTokenConverter jwtAccessTokenConverter;@Autowiredprivate JwtTokenEnhancer jwtTokenEnhancer;/*** @description: 使用密码模式所需配置* @author liyonghui* @date 2021/12/5 14:27*/@Overridepublic void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {List<TokenEnhancer> delegates = new ArrayList<>();delegates.add(jwtTokenEnhancer);delegates.add(jwtAccessTokenConverter);//配置JWT内容增强TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();tokenEnhancerChain.setTokenEnhancers(delegates);//配置存储令牌策略endpoints.tokenStore(jwtTokenStore).accessTokenConverter(jwtAccessTokenConverter).tokenEnhancer(tokenEnhancerChain);}@Overridepublic void configure(ClientDetailsServiceConfigurer clients) throws Exception {clients.inMemory()//配置client-id.withClient("super")//配置client-secret.secret(passwordEncoder.encode("xxx"))//配置刷新令牌的有效期.refreshTokenValiditySeconds(6000)//配置redirect-url,用于授权成功后跳转.redirectUris("http://localhost:8081/login","http://localhost:8082/login")//自动授权.autoApprove(true)//配置申请的权限范围.scopes("user","order","payment")//授权类型-使用授权码模式.authorizedGrantTypes("authorization_code","refresh_token");}@Overridepublic void configure(AuthorizationServerSecurityConfigurer security) throws Exception {//获取密钥需要身份认证,使用单点登录时必须配置security.tokenKeyAccess("isAuthenticated()");}
}

3,配置WebSecurityConfigurerAdapter

/*** @author xzq* @description: TODO* @date 2022/12/5 13:35*/
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/oauth/**", "/login/**").permitAll().anyRequest().authenticated().and().formLogin().permitAll();}
}

4,配置JwtTokenStoreConfig

/*** @author xzq* @description: TODO* @date 2022/12/5 15:39*/
@Configuration
public class JwtTokenStoreConfig {@Beanpublic TokenStore jwtTokenStore() {return new JwtTokenStore(jwtAccessTokenConverter());}@Beanpublic JwtAccessTokenConverter jwtAccessTokenConverter() {JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();//配置JWT使用的秘钥jwtAccessTokenConverter.setSigningKey("test_key");return jwtAccessTokenConverter;}
}

5,配置JwtTokenEnhancer:Jwt增强

/*** @author liyonghui* @description: JWT内容增强* @date 2021/12/5 15:58*/
@Component
public class JwtTokenEnhancer implements TokenEnhancer {@Overridepublic OAuth2AccessToken enhance(OAuth2AccessToken oAuth2AccessToken, OAuth2Authentication oAuth2Authentication) {Map<String, Object> objectObjectHashMap = new HashMap<>();objectObjectHashMap.put("enhance", "enhance info");objectObjectHashMap.put("ceshi", "测试一下增强令牌!");((DefaultOAuth2AccessToken) oAuth2AccessToken).setAdditionalInformation(objectObjectHashMap);return oAuth2AccessToken;}
}

6,配置pojo类

/*** @author xzq* @description: TODO* @date 2022/12/5 13:37*/
public class User implements UserDetails {private String username;private String password;private List<GrantedAuthority> authorities;public User(String username, String password, List<GrantedAuthority> authorities) {this.username = username;this.password = password;this.authorities = authorities;}@Overridepublic Collection<? extends GrantedAuthority> getAuthorities() {return null;}@Overridepublic String getPassword() {return null;}@Overridepublic String getUsername() {return null;}@Overridepublic boolean isAccountNonExpired() {return false;}@Overridepublic boolean isAccountNonLocked() {return false;}@Overridepublic boolean isCredentialsNonExpired() {return false;}@Overridepublic boolean isEnabled() {return false;}
}

配置一个用户的账号密码

/*** @author xzq* @description: TODO* @date 2022/12/5 13:34*/
@Service
public class UserService implements UserDetailsService {@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {String password = passwordEncoder.encode("123456");return new User("admin", password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));}
}

二、创建服务client:SSOA、SSOB 并进行测试

创建client:SSOA
目录如下:

1,配置yml文件

server:port: 8081servlet:session:cookie:name: OAUTH2-CLIENT-SESSION01  # 防止cookie冲突security:oauth2:client:client-id: super # appidclient-secret: xxx #appsecretuser-authorization-uri: http://localhost:8080/oauth/authorize #oauth认证地址access-token-uri: http://localhost:8080/oauth/token # 获取access_tokenresource:jwt:key-uri:  http://localhost:8080/oauth/token_key  # 获取和校验JWT(包装获取access_token)

写一个controller

/*** @Author xiaozq* @Date 2022/12/12 9:26* <p>@Description:</p>*/
@RequestMapping
@RestController
public class SystemAController {@GetMapping("/user")public Object userinfo(Authentication authentication){return authentication;}@GetMapping("/info")public Object ssoinfo(Authentication authentication){return  "系统A单点登录";}
}

创建client:SSOB: 复制A系统,改一下yml文件的端口号和cookie名设置,如下:

server:port: 8082servlet:session:cookie:name: OAUTH2-CLIENT-SESSION02  # 防止cookie冲突security:oauth2:client:client-id: super # appidclient-secret: xxx #appsecretuser-authorization-uri: http://localhost:8080/oauth/authorize #oauth认证地址access-token-uri: http://localhost:8080/oauth/token # 获取access_tokenresource:jwt:key-uri:  http://localhost:8080/oauth/token_key  # 获取和校验JWT(包装获取access_token)

开测!!!!
1,启动授权服务器,启动服务器A、B注意授权服务器先启动!!!

2,访问服务器A接口: http://localhost:8081/user


自动跳转到授权服务器的登录页面
输入用户名,密码: admin 123456

点击登录,则重定向回服务A,成功访问接口

上述截图响应的内容josn格式化如下:

{"authorities": [{"authority": "admin"}],"details": {"remoteAddress": "0:0:0:0:0:0:0:1","sessionId": "9143741264A37F6E57C921C0ACCAC86E","tokenValue": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjZXNoaSI6Iua1i-ivleS4gOS4i-WinuW8uuS7pOeJjCEiLCJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbInVzZXIiLCJvcmRlciIsInBheW1lbnQiXSwiZXhwIjoxNjcwODU1MDM2LCJhdXRob3JpdGllcyI6WyJhZG1pbiJdLCJqdGkiOiI1NDc3ZDMzNS01MzMwLTQ4NTQtYWFiMC0xYmU4OTMzZTQxNmEiLCJjbGllbnRfaWQiOiJzdXBlciIsImVuaGFuY2UiOiJlbmhhbmNlIGluZm8ifQ.N2MXqtGFjMkCo5ZaU5TCZdLr1IqfWB3kDmEUO-JH4cA","tokenType": "bearer","decodedDetails": null},"authenticated": true,"userAuthentication": {"authorities": [{"authority": "admin"}],"details": null,"authenticated": true,"principal": "admin","credentials": "N/A","name": "admin"},"clientOnly": false,"oauth2Request": {"clientId": "super","scope": ["user", "order", "payment"],"requestParameters": {"client_id": "super"},"resourceIds": [],"authorities": [],"approved": true,"refresh": false,"redirectUri": null,"responseTypes": [],"extensions": {},"grantType": null,"refreshTokenRequest": null},"credentials": "","principal": "admin","name": "admin"
}

此时在打开一个窗口,访问服务B

自动省略了上面sign in 登录步骤 ,自动重定向到服务B ,成功访问接口

至此,单点登录应用完成!!!!

SpringSecurity+OAuth2.0+JWT实现单点登录应用相关推荐

  1. springsecurity oauth2使用jwt实现单点登录

    Jwt方式已经分享在文章结尾处的百度网盘链接中,redis方式可以看我以前发表的文章. 文章目录 前言 一.springsecurity oauth2 + redis方式的缺点 二.oauth2认证的 ...

  2. springsecurity oauth2.0 集成sso单点登录

    前言 在前两篇中,我们基本上了解springsecurity 的授权码模式和密码模式的工作流程,其实来说,掌握了授权码模式,再基于springsecurity 做单点登录的集成就是一件非常容易的事情 ...

  3. Spring Cloud入门-Oauth2授权之基于JWT完成单点登录(Hoxton版本)

    文章目录 Spring Cloud入门系列汇总 摘要 单点登录简介 创建oauth2-client模块 修改授权服务器配置 网页单点登录演示 调用接口单点登录演示 oauth2-client添加权限校 ...

  4. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离

    在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与权限管理. ...

  5. springBoot整合spring security+JWT实现单点登录与权限管理前后端分离--筑基中期

    写在前面 在前一篇文章当中,我们介绍了springBoot整合spring security单体应用版,在这篇文章当中,我将介绍springBoot整合spring secury+JWT实现单点登录与 ...

  6. [业务流程]JWT实现单点登录(SpringBoot + Vue +axious)

    JWT实现单点登录(SpringBoot + Vue +axious) 准备阶段: **登录所需对象** admin{ "username":"", //作为T ...

  7. 基于Spring Security与JWT实现单点登录

    基于RBAC的权限管理 RBAC(Role-Based Access Control):基于角色的访问控制 当前项目中,RBAC具体的表现为: 管理员表:ams_admin 角色表:ams_role ...

  8. JWT实现单点登录(sso)功能

    单点登录描述: 单点登录主要时应用在微服务架构中,在任意一个子服务中输入用户的用户名,密码进行登录时, 在跳转到其他系统的时候,就无需在进行登录,直接可以识别出用户的身份,权限以及角色等信息 . . ...

  9. 使用Oauth2.0实现微博授权登录

    本文章参考资料: http://blog.csdn.net/highboys/article/details/52139268 http://blog.csdn.net/yypsober/articl ...

最新文章

  1. Android:你好,androidX!再见,android.support
  2. Spring事务——Spring 2.X的事务配置策略
  3. 软工实践——团队作业需求规格说明书——原型UI设计
  4. WebRTC Audio 接收和发送的关键过程
  5. 医学图像处理期末复习(四)
  6. 计蒜客 28437.Big brother said the calculation-线段树+二分-当前第k个位置的数 ( ACM训练联盟周赛 M)...
  7. Myeclipse中左边的项目目录没了
  8. MYSQL函数应用----替换函数replace()用法
  9. SVN如何迁移到Git?
  10. Mavon-editor:获取html内容和text内容
  11. AudioToolbox之AudioQueue.h(二)Creating and Disposing of Audio Queues
  12. python爬取微博评论_详解用python写网络爬虫-爬取新浪微博评论
  13. Energy Vault宣布完成1亿美元C轮融资
  14. win32 - 保存路径对话框(SelectFolderDialog)
  15. orb slam [RGBD-1] process has died解决
  16. CompletableFuture学习
  17. python海龟作图好看图案_海龟作图---用Python绘图
  18. SystemC time
  19. 我的世界服务器头像文件,端游我的世界怎么换头像,端游我的世界怎么换头像框...
  20. 大数据论文_03_BigTable(个人总结)

热门文章

  1. 机械设计中的技术要求
  2. html如何设置table的宽度,互联网常识:HTML怎么设置table宽度
  3. 2023全国两会政府工作报告中的“数据安全”
  4. LOADRUNNER中PACING的设置
  5. 程序员面试金典适合java么,程序员面试金典(java版)
  6. 程序员面试金典1.1
  7. SpringCloudAlibaba - 分布式流量防卫兵Sentinel
  8. java培训班学习该怎么做才能快速入门呢
  9. 基于物品 的协同过滤推荐算法(ItemCF)
  10. SpringCloud技术指南系列(十五)分布式链路跟踪Sleuth与Zipkin实现