【Spring-Security】Re14 Oauth2协议P4 整合SSO单点登陆
创建一个SSO单点登陆的客户端工程
需要的依赖和之前的项目基本一致:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.zeal4j</groupId>
<artifactId>sso-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>sso-client</name>
<description>Demo project for Spring Boot</description> <properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.SR2</spring-cloud.version>
</properties> <dependencies> <dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies> <dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version><!--<version>Greenwich.SR2</version>-->
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
YML配置:
server:
port: 8081 # 防止和服务端的端口冲突
servlet:
session:
cookie:
name: 'SSO-CLIENT-SESSION-ID' # 防止COOKIE冲突
# 授权服务器地址:
oauth2-server-url: http://localhost:8080
# 授权服务器的相关配置
security:
oauth2:
resource:
jwt:
key-uri: ${oauth2-server-url}/oauth/token_key
client:
client-id: admin
client-secret: 112233
user-authorization-uri: ${oauth2-server-url}/oauth/authorize
access-token-uri: ${oauth2-server-url}/oauth/token
客户端启动类打上支持SSO单点登陆注解

然后写一个简单的信息获取接口
package cn.zeal4j.controller; import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-SSO-Client
* @create 2020 09 30 0:38
*/
@Controller
@RequestMapping("user")
public class UserController { /**
* user/getCurrentUser
* @param authentication
* @return
*/
@RequestMapping("getCurrentUser")
@ResponseBody
public Object getCurrentUser(Authentication authentication) {
return authentication.getPrincipal();
}
}
回到服务端,设置跳转的地址是客户端IP位置:
package cn.zeal4j.configuration; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import java.util.ArrayList;
import java.util.List; /**
* @author Administrator
* @file Spring-Security + Oauth2
* @create 2020 09 29 11:48
* @description 授权服务器配置
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired
private PasswordEncoder passwordEncoder; @Autowired
private AuthenticationManager authenticationManager;
@Qualifier("customUserDetailsServiceImpl")
@Autowired
private UserDetailsService userDetailsService; @Qualifier("getTokenStore")
@Autowired
private TokenStore tokenStore; @Qualifier("getJwtAccessTokenConverter")
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter; @Qualifier("getJwtTokenEnhancer")
@Autowired
private TokenEnhancer tokenEnhancer; // @Qualifier("getRedisTokenStore")
// @Autowired
// private TokenStore tokenStore; /**
* 使用密码模式需要的配置方法
* @param endpoints
* @throws Exception
*/
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // - - - - - 配置JWT自定义申明增强 Starter - - - - -
TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
List<TokenEnhancer> tokenEnhancerList = new ArrayList<>(); tokenEnhancerList.add(tokenEnhancer);
tokenEnhancerList.add(jwtAccessTokenConverter); tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);
// - - - - - 配置JWT自定义申明增强 End - - - - - endpoints.
authenticationManager(authenticationManager).
userDetailsService(userDetailsService).
accessTokenConverter(jwtAccessTokenConverter).
tokenEnhancer(tokenEnhancerChain);
// tokenStore(tokenStore);
} @Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.
inMemory().
withClient("admin").
secret(passwordEncoder.encode("112233")).
// accessTokenValiditySeconds(3600). // 令牌有效时间 一小时
// redirectUris("http://www.baidu.com"). // 授权成功的跳转
accessTokenValiditySeconds(3600). // 过期时间
refreshTokenValiditySeconds(864000). // 刷新令牌的过期时间
redirectUris("http://localhost:8081/login").
autoApprove(true). //自动授权
scopes("all"). // 所有范围
// authorizedGrantTypes("authorization_code"); // 授权类型:授权码模式
authorizedGrantTypes("password", "refresh_token", "authorization_code"); // 授权类型:密码模式 追加令牌刷新,和兼容授权码模式
} @Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
// 密钥获取之前的身份认证,单点登陆必须配置
security.tokenKeyAccess("isAuthenticated()");
}
}
配置完成后先启动服务端,再启动客户端,注意不要同时启动,我出现了一个进程占用的情况
两个服务都无法开启,手动杀死8080端口的进程解决了
两边控制台显示运行成功之后,访问客户端的接口:
http://localhost:8081/user/getCurrentUser
结果会被重定向到服务端的登陆:
http://localhost:8080/login
输入用户信息登陆之后,会自动跳回到我们一开始希望访问的接口:
直接获取authentication对象能得到完整的信息
package cn.zeal4j.controller; import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; /**
* @author Administrator
* @file IntelliJ IDEA Spring-Security-SSO-Client
* @create 2020 09 30 0:38
*/
@Controller
@RequestMapping("user")
public class UserController { /**
* user/getCurrentUser
* @param authentication
* @return
*/
@RequestMapping("getCurrentUser")
@ResponseBody
public Object getCurrentUser(Authentication authentication) {
// return authentication.getPrincipal();
return authentication;
}
}
JSON数据:
{
"authorities": [{
"authority": "admin"
}],
"details": {
"remoteAddress": "0:0:0:0:0:0:0:1",
"sessionId": "C7FBF0520D8CA4DF4131B9E05965B6AA",
"tokenValue": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX25hbWUiOiJhZG1pbiIsInNjb3BlIjpbImFsbCJdLCJleHAiOjE2MDE0MDI1NjIsImp3dC1rZXktYWFhIjoiand0LXZhbHVlLUFBQSIsImF1dGhvcml0aWVzIjpbImFkbWluIl0sImp0aSI6ImFhMjJkNmY2LWMxYzMtNDg0ZS1iZjI5LTYzZTg1Y2ZlZGY4YSIsImp3dC1rZXktYmJiIjoiand0LXZhbHVlLUJCQiIsImNsaWVudF9pZCI6ImFkbWluIiwiand0LWtleS1jY2MiOiJqd3QtdmFsdWUtQ0NDIn0.LG-D88n-hNoVOG1hrlpwEs-64jA-T2TPdlRi0cram-w",
"tokenType": "bearer",
"decodedDetails": null
},
"authenticated": true,
"userAuthentication": {
"authorities": [{
"authority": "admin"
}],
"details": null,
"authenticated": true,
"principal": "admin",
"credentials": "N/A",
"name": "admin"
},
"principal": "admin",
"credentials": "",
"clientOnly": false,
"oauth2Request": {
"clientId": "admin",
"scope": ["all"],
"requestParameters": {
"client_id": "admin"
},
"resourceIds": [],
"authorities": [],
"approved": true,
"refresh": false,
"redirectUri": null,
"responseTypes": [],
"extensions": {},
"grantType": null,
"refreshTokenRequest": null
},
"name": "admin"
}
代码笔记已上传到Gitee仓库中,需要的自取:
https://gitee.com/daizhizhou/spring-security-tutorial
【Spring-Security】Re14 Oauth2协议P4 整合SSO单点登陆的更多相关文章
- Spring Security基于Oauth2的SSO单点登录怎样做?一个注解搞定
一.说明 单点登录顾名思义就是在多个应用系统中,只需要登录一次,就可以访问其他相互信任的应用系统,免除多次登录的烦恼.本文主要介绍 同域 和 跨域 两种不同场景单点登录的实现原理,并使用 Spring ...
- Spring Security实现OAuth2.0授权服务 - 基础版
一.OAuth2.0协议 1.OAuth2.0概述 OAuth2.0是一个关于授权的开放网络协议. 该协议在第三方应用与服务提供平台之间设置了一个授权层.第三方应用需要服务资源时,并不是直接使用用户帐 ...
- security和oauth2.0的整合
security和oauth2.0的整合 之前已经介绍过security的相关的介绍,现在所需要做的就是security和oauth2.0的整合,在原有的基础上我们加上一些相关的代码;代码实现如下: ...
- Spring Security 与 OAuth2 介绍
个人 OAuth2 全部文章 Spring Security 与 OAuth2(介绍):https://www.jianshu.com/p/68f22f9a00ee Spring Security 与 ...
- Spring Security 与 OAuth2(介绍)
https://www.jianshu.com/p/68f22f9a00ee Spring Security 与 OAuth2(介绍) 林塬 2018.01.23 11:14* 字数 3097 阅读 ...
- [权限管理系统(四)]-spring boot +spring security短信认证+redis整合
[权限管理系统]spring boot +spring security短信认证+redis整合 现在主流的登录方式主要有 3 种:账号密码登录.短信验证码登录和第三方授权登录,前面一节Sprin ...
- Spring Security实现OAuth2.0授权服务 - 进阶版
<Spring Security实现OAuth2.0授权服务 - 基础版>介绍了如何使用Spring Security实现OAuth2.0授权和资源保护,但是使用的都是Spring Sec ...
- IM开发基础知识补课:正确理解前置HTTP SSO单点登陆接口的原理
1.前言 一个安全的信息系统,合法身份检查是必须环节.尤其IM这种以“人”为中心的社交体系,身份认证更是必不可少. 一些PC时代小型IM系统中,身份认证可能直接做到长连接中(也就是整个IM系统都是以长 ...
- session问题总既然(深入理解)&Token问题理解&sso单点登陆理解实现
一.Session使http协议成为有状态协议(浏览器cookie本地这个session,服务器端也有这个session) 1.ajax前端登陆无法保存session,造成无法维持登陆状态(http本 ...
- spring boot:spring security实现oauth2+jwt管理认证授权及oauth2返回结果格式化(spring boot 2.3.3)
一,为什么oauth2要整合jwt? 1,OAuth2的token技术有一个最大的问题是不携带用户信息,所以资源服务器不能进行本地验证, 以致每次对于资源的访问,资源服务器都需要向认证服务器的toke ...
随机推荐
- categraf托管与自升级
categraf支持多种方式进行部署.托管,社区里部署和管理categraf也是五花八门,大家自己使用方便即可. 之前我们觉得大家通过ansible之类的工具批量下发/更新就能很简单地完成任务,最近很 ...
- 消息sms 邮箱/手机号/push发送的方案 & 定时任务xxlJob灵活度 & 泛型和发送的模板类设计
消息sms 邮箱/手机号/push发送的方案 & 定时任务xxlJob灵活度 & 泛型和发送的模板类设计 1.消息sms 邮箱/手机号/push发送的方案 1.判断收件人地址是否为空, ...
- postman Could not get any response 无法请求
外网访问接口地址,刚开始考虑到是阿里云服务器上面的ECS网络安全策略拦截,添加了白名单, 首先在浏览器中回车访问,页面有反应. 但是在postman中请求,仍然返回 Could not get any ...
- 解决:编译安卓源码时 JDK 报错 error='Not enough space' (errno=12)
背景 在编译 Android 10 代码的时候,OpenJDK发现报错: OpenJDK 64-Bit Server VM warning: INFO: os::commit_memory(.., . ...
- 抓取豆瓣电影TOP250标题-年份-评分-评分人数
import csv import re import requests headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; ...
- sqoop导入导出到mysql,hbase,hive,hdfs系统,多表关联导出案例
Sqoop工具1.协助 RDBMS 与 Hadoop 之间进行高效的大数据交流.把关系型数据库的数据导入到 Hadoop 与其相关的系统 (如HBase和Hive)同时也可以把数据从 Hadoop 系 ...
- vs code 设置中文
1.安装 下载地址:官网 打开 安装后打开默认显示英文界面. 2.修改 使用快捷键 ctrl+shift+p, 输入configure display language 下拉框选择 install ...
- 1. 简述一下你对 HTML 语义化的理解?
用正确的标签做正确的事情.1.HTML 语义化让页面的内容结构化,结构更清晰,便于对浏览器.搜索引擎解析; 2.即使在没有样式 CSS 的情况下也能以一种文档格式显示,并且是容易阅读的; 3.搜索引擎 ...
- Java-Filter:过滤器请求拦截
1.概念 web中的过滤器:当访问服务器资源时,过滤器可以将请求拦截下来,完成一些特殊的功能 过滤器的作用: 一般用于完成通用的操作,如:登录验证,统一编码处理,敏感字符过滤 2.快速入门 1.步骤 ...
- 新一代云原生日志架构 - Loggie的设计与实践
Loggie萌芽于网易严选业务的实际需求,成长于严选与数帆的长期共建,持续发展于网易数帆与网易传媒.中国工商银行的紧密协作.广泛的生态,使得项目能够基于业务需求不断完善.成熟.目前已经开源:https ...