spring-boot-security-oauth-client-sample

This commit is contained in:
MaxKey 2024-06-18 10:18:34 +08:00
parent 80337f7ad3
commit 22c40f1e1d
10 changed files with 361 additions and 1 deletions

View File

@ -7,7 +7,7 @@
| --------| :----- |
| cas-springboot-demo | SpringBoot开发的CAS协议客户端集成的介绍 |
| jeesite/5.2.1 | jeesite集成插件及使用介绍 |
| Spring-Security-Oauth2-SSO | Spring-Security-Oauth2-SSO|
| spring-boot-security-oauth-client-sample | spring-boot-security-oauth-client-sample|
| *_* | *_* |

View File

@ -0,0 +1,2 @@
# Auto detect text files and perform LF normalization
* text=auto

View File

@ -0,0 +1,89 @@
# spring-oauth-client-sample
## spring-boot-security-oauth-client-sample
### Application
```java
@SpringBootApplication
public class SpringBootOauthClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOauthClientApplication.class, args);
}
}
```
### application.yml
```ini
# 授权服务地址
maxkey-auth-url: http://sso.maxkey.top/sign
security:
oauth2:
client:
client-id: 1000185112135991296
client-secret: 8Nv7MTcwNjIwMjQyMDU5Mzg5MDU65R
scope: all
user-authorization-uri: ${maxkey-auth-url}/authz/oauth/v20/authorize
access-token-uri: ${maxkey-auth-url}/authz/oauth/v20/token
resource:
# 检查令牌
#token-info-uri: ${maxkey-auth-url}/authz/oauth/v20/token
# 用户信息
user-info-uri: ${maxkey-auth-url}/api/oauth/v20/me
```
### ResourceServerConfiguration
```java
@Configuration
@EnableOAuth2Sso
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {
Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class);
@Value("${maxkey-auth-url}")
String maxkeyAuthUrl;
@Value("${security.oauth2.client.user-authorization-uri}")
String userAuthorizationUri;
@Value("${security.oauth2.client.access-token-uri}")
String accessTokenUri;
@Value("${security.oauth2.resource.user-info-uri}")
String userInfoUri;
@Override
public void configure(HttpSecurity http) throws Exception {
//http.antMatcher("/orgs/**").antMatcher("/userinfo").antMatcher("/login").authorizeRequests().anyRequest().authenticated();
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
log.info("UserAuthorizationUri {}" ,userAuthorizationUri);
log.info("AccessTokenUri {}" ,accessTokenUri);
log.info("UserInfoUri {}" ,userInfoUri);
if(accessTokenUri.startsWith("https")) {
HttpsTrusts.beforeConnection();
}
log.debug("ResourceServerConfiguration");
}
}
```
### ResourceController
```java
@RestController
public class ResourceController {
Logger log = LoggerFactory.getLogger(ResourceController.class);
@GetMapping("/")
public String index() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getPrincipal().toString();
}
}
```

View File

@ -0,0 +1,83 @@
<?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 http://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.6.RELEASE</version>
<relativePath />
</parent>
<groupId>org.maxkey.oauthclient</groupId>
<artifactId>spring-boot-security-oauth-client-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>boot-oauth-client</name>
<description>Demo project for spring-boot-security-oauth-client-sample</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<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>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-security</artifactId>
</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>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,14 @@
package org.maxkey.springboot.oauthclient;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootOauthClientApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootOauthClientApplication.class, args);
}
}

View File

@ -0,0 +1,42 @@
package org.maxkey.springboot.oauthclient.config;
import org.maxkey.springboot.oauthclient.http.HttpsTrusts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableOAuth2Sso
public class ResourceServerConfiguration extends WebSecurityConfigurerAdapter {
Logger log = LoggerFactory.getLogger(ResourceServerConfiguration.class);
@Value("${maxkey-auth-url}")
String maxkeyAuthUrl;
@Value("${security.oauth2.client.user-authorization-uri}")
String userAuthorizationUri;
@Value("${security.oauth2.client.access-token-uri}")
String accessTokenUri;
@Value("${security.oauth2.resource.user-info-uri}")
String userInfoUri;
@Override
public void configure(HttpSecurity http) throws Exception {
//http.antMatcher("/orgs/**").antMatcher("/userinfo").antMatcher("/login").authorizeRequests().anyRequest().authenticated();
http.authorizeRequests().anyRequest().authenticated().and().csrf().disable();
log.info("UserAuthorizationUri {}" ,userAuthorizationUri);
log.info("AccessTokenUri {}" ,accessTokenUri);
log.info("UserInfoUri {}" ,userInfoUri);
if(accessTokenUri.startsWith("https")) {
HttpsTrusts.beforeConnection();
}
log.debug("ResourceServerConfiguration");
}
}

View File

@ -0,0 +1,20 @@
package org.maxkey.springboot.oauthclient.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ResourceController {
Logger log = LoggerFactory.getLogger(ResourceController.class);
@GetMapping("/")
public String index() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
return authentication.getPrincipal().toString();
}
}

View File

@ -0,0 +1,75 @@
/*
* Copyright [2020] [MaxKey of copyright http://www.maxkey.top]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.maxkey.springboot.oauthclient.http;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class HttpsTrusts {
private static void trustAllHttpsCertificates() throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new HttpsTrustsTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
/*
* https ssl auto trust
*/
public static void beforeConnection() {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
}
});
} catch(Exception e) {
e.printStackTrace();
}
}
static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
}
}

View File

@ -0,0 +1,22 @@
server:
port: 9001
# 授权服务地址
maxkey-auth-url: http://sso.maxkey.top/sign
security:
oauth2:
client:
client-id: 1000185112135991296
client-secret: 8Nv7MTcwNjIwMjQyMDU5Mzg5MDU65R
scope: all
user-authorization-uri: ${maxkey-auth-url}/authz/oauth/v20/authorize
access-token-uri: ${maxkey-auth-url}/authz/oauth/v20/token
resource:
# 检查令牌
#token-info-uri: ${maxkey-auth-url}/authz/oauth/v20/token
# 用户信息
user-info-uri: ${maxkey-auth-url}/api/oauth/v20/me
spring:
main:
allow-bean-definition-overriding: true

View File

@ -0,0 +1,13 @@
log4j.rootLogger=info,Console,File
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n
log4j.appender.File = org.apache.log4j.RollingFileAppender
log4j.appender.File.File = logs/info.log
log4j.appender.File.MaxFileSize = 10MB
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c - %L]%m%n