Merge branch 'refs/heads/dev'
This commit is contained in:
@@ -159,4 +159,17 @@ central-platform -- 父项目,公共依赖
|
||||
<td><img alt="nacos-discovery" src="https://gitee.com/zlt2000/images/raw/master/nacos-discovery.png"/></td>
|
||||
<td><img alt="应用吞吐量监控" src="https://gitee.com/zlt2000/images/raw/master/%E5%BA%94%E7%94%A8%E5%90%9E%E5%90%90%E9%87%8F%E7%9B%91%E6%8E%A7.png"/></td>
|
||||
</tr>
|
||||
</table>
|
||||
</table>
|
||||
|
||||
|
||||
## 8.友情链接
|
||||
|
||||
### flowsphere
|
||||
|
||||
云原生微服务流量治理解决方案,项目地址:https://github.com/flowsphere-projects/flowsphere
|
||||
|
||||
项目亮点:
|
||||
|
||||
1.全网唯一使用JavaAgent实现Http、MQ、Job全链路灰度
|
||||
|
||||
2.全网唯一支持JavaAgent接入Sentinel
|
||||
+10
-3
@@ -3,10 +3,12 @@ package com.central.oauth2.common.config;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import com.central.oauth2.common.component.CustomAuthorizationServiceIntrospector;
|
||||
import com.central.oauth2.common.component.CustomBearerTokenResolver;
|
||||
import com.central.oauth2.common.enums.TokenType;
|
||||
import com.central.oauth2.common.properties.SecurityProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
@@ -45,7 +47,7 @@ public class DefaultResourceServerConf {
|
||||
private AccessDeniedHandler oAuth2AccessDeniedHandler;
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain springSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
|
||||
http.authorizeHttpRequests(authorizeRequests -> {
|
||||
AuthorizeHttpRequestsConfigurer<HttpSecurity>.AuthorizedUrl authorizedUrl = authorizeRequests
|
||||
.requestMatchers(HttpMethod.OPTIONS).permitAll()
|
||||
@@ -64,8 +66,13 @@ public class DefaultResourceServerConf {
|
||||
http.oauth2ResourceServer(oauth2 -> {
|
||||
oauth2.authenticationEntryPoint(authenticationEntryPoint)
|
||||
.bearerTokenResolver(customBearerTokenResolver)
|
||||
.accessDeniedHandler(oAuth2AccessDeniedHandler)
|
||||
.opaqueToken(token -> token.introspector(this.getOpaqueTokenIntrospector()));
|
||||
.accessDeniedHandler(oAuth2AccessDeniedHandler);
|
||||
if (TokenType.JWT.getName().equals(securityProperties.getResourceServer().getTokenType())) {
|
||||
oauth2.jwt(Customizer.withDefaults());
|
||||
} else {
|
||||
oauth2.opaqueToken(token -> token.introspector(this.getOpaqueTokenIntrospector()));
|
||||
}
|
||||
//.opaqueToken(token -> token.introspector(this.getOpaqueTokenIntrospector()));
|
||||
});
|
||||
|
||||
return http.build();
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ public class ResponseUtil {
|
||||
}
|
||||
|
||||
private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, Result result) throws IOException {
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
|
||||
try (
|
||||
Writer writer = response.getWriter()
|
||||
) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.zlt.config;
|
||||
|
||||
import com.central.oauth2.common.config.DefaultResourceServerConf;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
//import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
|
||||
|
||||
/**
|
||||
* security资源服务器配置
|
||||
@@ -13,7 +13,6 @@ import org.springframework.context.annotation.Configuration;
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
/*@Configuration
|
||||
@EnableResourceServer
|
||||
@Configuration
|
||||
public class MyResourceConfig extends DefaultResourceServerConf {
|
||||
}*/
|
||||
}
|
||||
|
||||
+39
-52
@@ -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
|
||||
@@ -10,16 +10,6 @@
|
||||
<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');
|
||||
|
||||
|
||||
@@ -9,19 +9,15 @@
|
||||
</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>
|
||||
</div>
|
||||
<script>
|
||||
function login() {
|
||||
let state = getState();
|
||||
sessionStorage.setItem("visitUri", window.location.href);
|
||||
sessionStorage.setItem("state", state);
|
||||
window.location = getAuthorizeUri(state);
|
||||
window.location = getAuthorizeUri();
|
||||
}
|
||||
|
||||
window.onload = function() {
|
||||
@@ -29,11 +25,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();
|
||||
|
||||
@@ -6,22 +6,14 @@ 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;
|
||||
function getAuthorizeUri() {
|
||||
return uaaUri+'authorize?client_id='+clientId+'&redirect_uri=http://127.0.0.1:'+port+'/callback.html&scope=openid&response_type=code';
|
||||
}
|
||||
|
||||
function getLogoutUri(accessToken) {
|
||||
return uaaUri+'remove/token?redirect_uri=http://127.0.0.1:'+port+'/index.html&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参数
|
||||
*/
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
-39
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.zlt.config;
|
||||
|
||||
import com.central.oauth2.common.config.DefaultResourceServerConf;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
@@ -12,9 +13,6 @@ import org.springframework.context.annotation.Configuration;
|
||||
* Blog: http://zlt2000.gitee.io
|
||||
* Github: https://github.com/zlt2000
|
||||
*/
|
||||
/*
|
||||
@Configuration
|
||||
@EnableResourceServer
|
||||
public class MyResourceConfig extends DefaultResourceServerConf {
|
||||
}
|
||||
*/
|
||||
|
||||
@@ -28,7 +28,7 @@ import java.io.IOException;
|
||||
@RequiredArgsConstructor
|
||||
@Component
|
||||
public class OauthLogoutSuccessHandler implements LogoutSuccessHandler {
|
||||
private static final String REDIRECT_URL = "redirect_url";
|
||||
private static final String REDIRECT_URL = "redirect_uri";
|
||||
private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
|
||||
private final UnifiedLogoutService unifiedLogoutService;
|
||||
private final SecurityProperties securityProperties;
|
||||
|
||||
@@ -12,7 +12,7 @@ const Settings: LayoutSettings & {
|
||||
fixedHeader: false,
|
||||
fixSiderbar: true,
|
||||
colorWeak: false,
|
||||
title: 'Microservices-Platform',
|
||||
title: '开源项目演示环境',
|
||||
pwa: false,
|
||||
logo: './logo.png',
|
||||
iconfontUrl: '',
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
<meta name="description" content="
|
||||
Out-of-the-box mid-stage front-end/design solution." />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
|
||||
<title>Microservices-Platform</title>
|
||||
<title>开源项目演示环境</title>
|
||||
<link rel="icon" href="<%= context.config.publicPath +'favicon.ico'%>" type="image/x-icon" />
|
||||
</head>
|
||||
|
||||
@@ -223,4 +223,4 @@
|
||||
</div>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
</html>
|
||||
|
||||
Reference in New Issue
Block a user