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
+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>