logo头像

生活多彩,尽情享受!

SpringCloud OAuth2 单点登录

一. 创建MAVEN项目完成认证服务配置

1.pom中依赖如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?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">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<modelVersion>4.0.0</modelVersion>

<artifactId>springcloud-auth-server</artifactId>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!--排除tomcat依赖-->
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<!--undertow容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<!--spring security 、oauth、jwt依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
</dependencies>

</project>
2.创建项目入口类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cn.itxsl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @program: itxsl-cloud
* @description: 第三方应用
* @author: itxsl
* @create: 2019-04-23 16:55
**/
@RestController
@EnableOAuth2Sso//启用第三方应用
@SpringBootApplication
public class ClientApplication {

public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}

@GetMapping("/user")
public Authentication user(Authentication credentials) {
return credentials;
}

}
3.创建一个配置文件application.yml,内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
auth-server: http://127.0.0.1:7002/ # 认证服务器地址
server:
port: 7003
security:
oauth2:
client:
client-id: itxsl
client-secret: itxsl
scope: all
access-token-uri: ${auth-server}/oauth/token
user-authorization-uri: ${auth-server}/oauth/authorize
clientAuthenticationScheme: form
registered-redirect-uri: http://localhost:7003/auth/account
resource:
token-info-uri: ${auth-server}/oauth/check_token
userInfoUri: http://${auth-server}/user
sso:
login-path: /auth/account
logging:
level:
root: info

二、启动项目测试三方登录是否可用

1.启动项目

2.验证登录是否可用

源码地址: 源码