feat: sso-demo 适配 Spring Authorization Server

This commit is contained in:
zlt2000
2024-03-04 16:02:47 +08:00
parent 11c8773c40
commit 9dc20d56c9
17 changed files with 310 additions and 223 deletions
@@ -1,10 +1,9 @@
package com.sso.demo.controller;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.central.common.model.Result;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.central.common.utils.JsonUtil;
import com.central.common.utils.RsaUtils;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
@@ -24,8 +23,14 @@ import org.springframework.web.client.RestTemplate;
import org.apache.commons.codec.binary.Base64;
import jakarta.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.*;
/**
@@ -38,9 +43,6 @@ import java.util.*;
@Slf4j
@RestController
public class ApiController {
private static final String PUBKEY_START = "-----BEGIN PUBLIC KEY-----";
private static final String PUBKEY_END = "-----END PUBLIC KEY-----";
@Value("${zlt.sso.client-id:}")
private String clientId;
@@ -64,36 +66,32 @@ public class ApiController {
/**
* 模拟用户数据库
*/
private static final Map<Long, MyUser> userDb = new HashMap<>();
private static final Map<String, String> userDb = new HashMap<>();
/**
* nonce存储
*/
private final static ThreadLocal<String> NONCE = new ThreadLocal<>();
private final static Map<String, MyUser> localTokenMap = new HashMap<>();
private final static Map<String, String> localTokenMap = new HashMap<>();
@GetMapping("/token/{code}")
public Map<String, Object> tokenInfo(@PathVariable String code) throws Exception {
//获取token
Map<String, Object> tokenMap = getAccessToken(code);
String idTokenStr = (String)tokenMap.get("id_token");
Map datasMap = (Map)tokenMap.get("datas");
String idTokenStr = (String)datasMap.get("id_token");
//解析id_token
JsonNode idToken = this.getIdTokenJson(idTokenStr);
//检查id_token的有效性
checkToken(idToken);
//获取用户信息
MyUser user = this.getUserInfo(idToken);
String username = idToken.get("sub").asText();
//判断用户信息是否存在,否则注册用户信息
if (!userDb.containsKey(user.getId())) {
userDb.put(user.getId(), user);
if (!userDb.containsKey(username)) {
userDb.put(username, username);
}
String accessToken = (String)tokenMap.get("access_token");
localTokenMap.put(accessToken, user);
String accessToken = (String)datasMap.get("access_token");
localTokenMap.put(accessToken, username);
Map<String, Object> result = new HashMap<>(2);
result.put("tokenInfo", tokenMap);
result.put("userInfo", user);
result.put("tokenInfo", datasMap);
result.put("userInfo", username);
return result;
}
@@ -109,7 +107,7 @@ public class ApiController {
}
@GetMapping("/user")
public MyUser user(HttpServletRequest request) {
public String user(HttpServletRequest request) {
String token = request.getParameter("access_token");
return localTokenMap.get(token);
}
@@ -121,15 +119,11 @@ public class ApiController {
//token有效期
long expiresAt = idToken.get("exp").asLong();
long now = System.currentTimeMillis();
Assert.isTrue((expiresAt > now), "id_token已过期");
//Assert.isTrue((expiresAt > now), "id_token已过期");
//应用id
String aud = idToken.get("aud").asText();
Assert.isTrue(clientId.equals(aud), "非法应用"+aud);
//随机码
String nonce = idToken.get("nonce").asText();
Assert.isTrue((StrUtil.isEmpty(nonce) || nonce.equals(NONCE.get())), "nonce参数无效");
}
/**
@@ -147,18 +141,11 @@ public class ApiController {
param.add("grant_type", "authorization_code");
param.add("redirect_uri", redirectUri);
param.add("scope", "all");
param.add("nonce", this.genNonce());
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class);
return response.getBody();
}
private String genNonce() {
String nonce = RandomUtil.randomString(6);
NONCE.set(nonce);
return nonce;
}
/**
* 把 id_token 字符串解析为json对象
*/
@@ -167,18 +154,6 @@ public class ApiController {
return this.decodeAndVerify(idToken, publicKey);
}
/**
* 通过 id_token 获取用户信息
*/
public MyUser getUserInfo(JsonNode idToken) {
MyUser user = new MyUser();
user.setId(Long.valueOf(idToken.get("sub").textValue()));
user.setName(idToken.get("name").textValue());
user.setLoginName(idToken.get("login_name").textValue());
user.setPicture(idToken.get("picture").textValue());
return user;
}
private JsonNode decodeAndVerify(String jwtToken, RSAPublicKey rsaPublicKey) {
SignatureVerifier rsaVerifier = new RsaVerifier(rsaPublicKey);
Jwt jwt = JwtHelper.decodeAndVerify(jwtToken, rsaVerifier);
@@ -203,13 +178,25 @@ public class ApiController {
HttpEntity<String> request = new HttpEntity<>(headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Result> response = restTemplate.exchange(jwtKeyUri, HttpMethod.GET, request, Result.class);
Result<String> result = response.getBody();
Assert.isTrue((result.getResp_code() == 0), result.getResp_msg());
ResponseEntity<JSONObject> response = restTemplate.exchange(jwtKeyUri, HttpMethod.GET, request, JSONObject.class);
JSONObject result = response.getBody();
JSONArray keys = (JSONArray) result.get("keys");
JSONObject keyObj = (JSONObject) keys.get(0);
String e = (String) keyObj.get("e");
String n = (String) keyObj.get("n");
return this.getKeyInstance(n, e);
}
String publicKeyStr = result.getResp_msg();
publicKeyStr = publicKeyStr.substring(PUBKEY_START.length(), publicKeyStr.indexOf(PUBKEY_END));
return RsaUtils.getPublicKey(publicKeyStr);
private static RSAPublicKey getKeyInstance(String n, String e) throws InvalidKeySpecException, NoSuchAlgorithmException {
// 将 Base64 编码的字符串解码为字节数组
byte[] modulus = Base64.decodeBase64(n);
byte[] exponent = Base64.decodeBase64(e);
// 创建 RSA 公钥规范
RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(1, modulus), new BigInteger(1, exponent));
// 获取 RSA 密钥工厂
KeyFactory kf = KeyFactory.getInstance("RSA");
// 生成公钥
return (RSAPublicKey)kf.generatePublic(spec);
}
/**
@@ -11,4 +11,4 @@ zlt:
client-secret: webApp
redirect-uri: http://127.0.0.1:8082/callback.html
access-token-uri: http://127.0.0.1:9900/api-uaa/oauth/token
jwt-key-uri: http://127.0.0.1:9900/api-uaa/tokens/key
jwt-key-uri: http://127.0.0.1:9900/api-uaa/oauth/jwks
@@ -9,9 +9,7 @@
</head>
<body>
<div>
<p>用户名:<span id="userName"></span></p>
<p>登录名:<span id="loginName"></span></p>
<p>头像:<span id="picture"></span></p>
<p>应用id:<span id="clientId"></span></p>
<p>token:<span id="accessToken"></span></p>
<p><input type="button" value="登出" onclick="logout()"/></p>
@@ -29,11 +27,9 @@
if (accessToken) {//已登录
//获取token和用户信息
$.ajax({url:'http://127.0.0.1:'+port+'/user?access_token='+accessToken, success:function(result) {
if (result.name) {
if (result) {
$('#accessToken').html(accessToken);
$('#userName').html(result.name);
$('#loginName').html(result.loginName);
$('#picture').html(result.picture);
$('#loginName').html(result);
$('#clientId').html(clientId);
} else {
login();
@@ -7,7 +7,7 @@ let uaaUri = 'http://127.0.0.1:9900/api-uaa/oauth/';
let port = 8082;
function getAuthorizeUri(state) {
return uaaUri+'authorize?client_id='+clientId+'&redirect_uri=http://127.0.0.1:'+port+'/callback.html&response_type=code%20id_token&state='+state;
return uaaUri+'authorize?client_id='+clientId+'&redirect_uri=http://127.0.0.1:'+port+'/callback.html&scope=openid&response_type=code&state='+state;
}
function getLogoutUri(accessToken) {
+10 -2
View File
@@ -18,10 +18,14 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<!--<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
</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-thymeleaf</artifactId>
@@ -30,6 +34,10 @@
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
</dependencies>
<build>
@@ -1,44 +0,0 @@
package com.sso.demo.config;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
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.web.SecurityFilterChain;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import javax.annotation.Resource;
/**
* security配置
*
* @author zlt
* @date 2020/2/22
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@EnableOAuth2Sso
@Configuration
public class SecurityConfig {
@Value("${security.oauth2.sso.login-path:}")
private String loginPath;
@Resource
private LogoutSuccessHandler ssoLogoutSuccessHandler;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
/*http.authorizeHttpRequests().anyRequest().authenticated()
.and()
.csrf().disable()
.logout()
.logoutSuccessHandler(ssoLogoutSuccessHandler);
if (StrUtil.isNotEmpty(loginPath)) {
http.formLogin().loginProcessingUrl(loginPath);
}*/
return http.build();
}
}
@@ -1,39 +0,0 @@
package com.sso.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 登出成功处理类
*
* @author zlt
* @date 2020/3/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Component
public class SsoLogoutSuccessHandler implements LogoutSuccessHandler {
@Value("${zlt.logout-uri:''}")
private String logoutUri;
private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
@Override
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)oauth2Authentication.getDetails();
String accessToken = details.getTokenValue();
redirectStrategy.sendRedirect(request, response, logoutUri+accessToken);
}
}
@@ -0,0 +1,118 @@
package com.sso.demo.controller;
import cn.hutool.core.collection.CollectionUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zlt
* @date 2020/3/10
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Slf4j
@RestController
public class ApiController {
@Value("${zlt.sso.client-id:}")
private String clientId;
@Value("${zlt.sso.client-secret:}")
private String clientSecret;
@Value("${zlt.sso.redirect-uri:}")
private String redirectUri;
@Value("${zlt.sso.access-token-uri:}")
private String accessTokenUri;
@Value("${zlt.sso.user-info-uri:}")
private String userInfoUri;
private final static Map<String, Map<String, Object>> localTokenMap = new HashMap<>();
@GetMapping("/token/{code}")
public String tokenInfo(@PathVariable String code) throws UnsupportedEncodingException {
//获取token
Map tokenMap = getAccessToken(code);
Map datasMap = (Map)tokenMap.get("datas");
String accessToken = (String)datasMap.get("access_token");
//获取用户信息
Map userMap = getUserInfo(accessToken);
List<String> roles = getRoles(userMap);
Map result = new HashMap(2);
String username = (String)userMap.get("username");
result.put("username", username);
result.put("roles", roles);
localTokenMap.put(accessToken, result);
return accessToken;
}
/**
* 获取token
*/
public Map getAccessToken(String code) throws UnsupportedEncodingException {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
byte[] authorization = (clientId + ":" + clientSecret).getBytes("UTF-8");
String base64Auth = Base64.encodeBase64String(authorization);
headers.add("Authorization", "Basic " + base64Auth);
MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
param.add("code", code);
param.add("grant_type", "authorization_code");
param.add("redirect_uri", redirectUri);
param.add("scope", "app");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class);
Map result = response.getBody();
return result;
}
/**
* 获取用户信息
*/
public Map getUserInfo(String accessToken) {
RestTemplate restTemplate = new RestTemplate();
Map result = restTemplate.getForObject(userInfoUri+"?access_token="+accessToken, Map.class);
return (Map)result.get("datas");
}
private List<String> getRoles(Map userMap) {
List<Map<String, String>> roles = (List<Map<String, String>>)userMap.get("roles");
List<String> result = new ArrayList<>();
if (CollectionUtil.isNotEmpty(roles)) {
roles.forEach(e -> {
result.add(e.get("code"));
});
}
return result;
}
@GetMapping("/user")
public Map<String, Object> user(HttpServletRequest request) {
String token = request.getParameter("access_token");
return localTokenMap.get(token);
}
}
@@ -1,29 +0,0 @@
package com.sso.demo.controller;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author zlt
* @date 2020/2/22
* <p>
* Blog: http://zlt2000.gitee.io
* Github: https://github.com/zlt2000
*/
@Controller
public class HomeController {
@GetMapping("/")
public String home(ModelMap modelMap, Authentication authentication) {
OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication;
modelMap.put("username", oauth2Authentication.getName());
modelMap.put("authorities", oauth2Authentication.getAuthorities());
modelMap.put("clientId", oauth2Authentication.getOAuth2Request().getClientId());
OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)oauth2Authentication.getDetails();
modelMap.put("token", details.getTokenValue());
return "index";
}
}
@@ -1,23 +1,10 @@
server:
port: 8080
spring:
application:
name: sso-demo
zlt:
api-uaa:
url: http://127.0.0.1:9900/api-uaa/oauth
logout-uri: ${zlt.api-uaa.url}/remove/token?redirect_uri=http://127.0.0.1:8080&access_token=
security:
oauth2:
sso:
login-path: /singleLogin
client:
client-id: zlt
client-secret: zlt
access-token-uri: ${zlt.api-uaa.url}/token
user-authorization-uri: ${zlt.api-uaa.url}/authorize
resource:
token-info-uri: ${zlt.api-uaa.url}/check_token
sso:
client-id: zlt
client-secret: zlt
redirect-uri: http://127.0.0.1:8080/callback.html
access-token-uri: http://127.0.0.1:9900/api-uaa/oauth/token
user-info-uri: http://127.0.0.1:9900/api-user/users/current
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8"/>
<title>zlt</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/sso.js"></script>
</head>
<body>
<script>
window.onload = function() {
//url获取state
let state = getQueryVariable('state');
let localState = sessionStorage.getItem("state");
//判断state防止CSRF攻击
if (localState !== state) {
alert('state参数无效!');
let state = getState();
sessionStorage.setItem("state", state);
window.location = getAuthorizeUri(state);
}
//url获取code
let code = getQueryVariable('code');
//获取token和用户信息
$.ajax({url:'http://127.0.0.1:8080/token/'+code, success:function(result) {
console.log(result);
sessionStorage.setItem('access_token', result);
window.location = sessionStorage.getItem('visitUri');
}});
};
</script>
</body>
</html>
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta charset="utf-8"/>
<title>zlt</title>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/sso.js"></script>
</head>
<body>
<div>
<p>用户名:<span id="userName"></span></p>
<p>权限:[<span id="roles"></span>]</p>
<p>应用id:<span id="clientId"></span></p>
<p>token:<span id="accessToken"></span></p>
<p><input type="button" value="登出" onclick="logout()"/></p>
</div>
<script>
function login() {
let state = getState();
sessionStorage.setItem("visitUri", window.location.href);
sessionStorage.setItem("state", state);
window.location = getAuthorizeUri(state);
}
window.onload = function() {
let accessToken = sessionStorage.getItem('access_token');
if (accessToken) {//已登录
//获取token和用户信息
$.ajax({url:'http://127.0.0.1:8080/user?access_token='+accessToken, success:function(result) {
if (result.username) {
$('#accessToken').html(accessToken);
$('#userName').html(result.username);
$('#roles').html(result.roles);
$('#clientId').html(clientId);
} else {
login();
}
}});
} else {//未登录
login();
}
};
function logout() {
let accessToken = sessionStorage.getItem('access_token');
sessionStorage.removeItem('access_token');
window.location = getLogoutUri(accessToken);
}
</script>
</body>
</html>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,38 @@
const FULL_CHARTER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopgrstuvwxyz';
//应用id
let clientId = 'zlt';
//授权中心地址
let uaaUri = 'http://127.0.0.1:9900/api-uaa/oauth/';
function getAuthorizeUri(state) {
return uaaUri+'authorize?client_id='+clientId+'&redirect_uri=http://127.0.0.1:8080/callback.html&response_type=code&state='+state;
}
function getLogoutUri(accessToken) {
return uaaUri+'remove/token?redirect_uri=http://127.0.0.1:8080/index.html&access_token='+accessToken;
}
function getUserInfo(accessToken) {
return 'http://127.0.0.1:8080/user?access_token='+accessToken;
}
function getState() {
let state='';
for (let i = 0; i < 6; i++) {
state += FULL_CHARTER[Math.floor(Math.random() * 52)];
}
return state;
}
/**
* 获取url参数
*/
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return '';
}
@@ -1,16 +0,0 @@
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta content="text/html;charset=UTF-8">
<title>SSO单点登录demo</title>
</head>
<body>
<div>
<p>登录者: <span th:text="${username}"></span></p>
<p>权限: <span th:text="${authorities}"></span></p>
<p>应用id: <span th:text="${clientId}"></span></p>
<p>token: <span th:text="${token}"></span></p>
<p><input type="button" value="登出" onclick="location='/logout'"/></p>
</div>
</body>
</html>
@@ -51,7 +51,8 @@ public class ApiController {
public String tokenInfo(@PathVariable String code) throws UnsupportedEncodingException {
//获取token
Map tokenMap = getAccessToken(code);
String accessToken = (String)tokenMap.get("access_token");
Map datasMap = (Map)tokenMap.get("datas");
String accessToken = (String)datasMap.get("access_token");
//获取用户信息
Map userMap = getUserInfo(accessToken);
List<String> roles = getRoles(userMap);
@@ -80,7 +81,7 @@ public class ApiController {
param.add("code", code);
param.add("grant_type", "authorization_code");
param.add("redirect_uri", redirectUri);
param.add("scope", "app");
param.add("scope", "openid");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request , Map.class);
Map result = response.getBody();
@@ -112,15 +113,4 @@ public class ApiController {
String token = request.getParameter("access_token");
return localTokenMap.get(token);
}
@GetMapping("/logoutNotify")
public void logoutNotify(HttpServletRequest request) {
String tokens = request.getParameter("tokens");
log.info("=====logoutNotify: " + tokens);
if (StrUtil.isNotEmpty(tokens)) {
for (String accessToken : tokens.split(",")) {
localTokenMap.remove(accessToken);
}
}
}
}