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
package cn.itxsl;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @program: example
* @description: 认证中心
* @author: itxsl
* @create: 2019-04-25 12:26
**/
@SpringBootApplication
public class AuthApplication {

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

}
3.创建认证服务器三方应用配置中心:
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package cn.itxsl.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.util.*;

/**
* @program: itxsl-cloud
* @description: 认证服务配置
* @author: itxsl
* @create: 2019-04-23 15:45
**/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {

@Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
//默认是不支持表单提交,这里修改提交权限
security
.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
super.configure(security);
}




@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService());
super.configure(clients);
}

@Autowired
private AuthenticationManager authenticationManager;

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.setClientDetailsService(clientDetailsService());
endpoints.authenticationManager(authenticationManager)
.accessTokenConverter(jwtAccessTokenConverter());//这里配置JWT加密,如果不想要JWT,将此行及jwtAccessTokenConverter()方法删除即可
}

@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
KeyPair keyPair = new KeyStoreKeyFactory(
new ClassPathResource("keystore.jks"), "foobar".toCharArray())//jks可用jdk 工具生成
.getKeyPair("test");
converter.setKeyPair(keyPair);
return converter;
}

//正常情况,这个ClientDetailsService是在业务层,继承ClientDetailsService接口,并实现loadClientByClientId(String s)方法
public ClientDetailsService clientDetailsService(){
return new ClientDetailsService() {
@Override
public ClientDetails loadClientByClientId(String s) throws ClientRegistrationException {
return new ClientDetails() {
@Override
public String getClientId() {
return "itxsl";
}

@Override
public Set<String> getResourceIds() {
return null;
}

@Override
public boolean isSecretRequired() {
return true;
}

@Override
public String getClientSecret() {
return "itxsl";
}

@Override
public boolean isScoped() {
return true;
}

@Override
public Set<String> getScope() {
HashSet<String> strings = new HashSet<>();
strings.add("all");
return strings;
}

@Override//这里配置支持哪几种授权模式
public Set<String> getAuthorizedGrantTypes() {
Set<String> strings = new HashSet<>();
strings.add("code");
strings.add("authorization_code");
strings.add("refresh_token");
strings.add("password");
return strings;
}

@Override
public Set<String> getRegisteredRedirectUri() {
Set<String> strings = new HashSet<>();
strings.add("http://localhost:7003/auth/account");//这里是重定向地址及最后code授权码返回地址
return strings;
}

@Override
public Collection<GrantedAuthority> getAuthorities() {
List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
grantedAuthorityList.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return "itxsl";
}
});
return grantedAuthorityList;
}

@Override
public Integer getAccessTokenValiditySeconds() {
return 3600;
}

@Override
public Integer getRefreshTokenValiditySeconds() {
return 3600;
}

@Override
public boolean isAutoApprove(String s) {
return true;
}

@Override
public Map<String, Object> getAdditionalInformation() {
return null;
}
};
}
};
}
}
4.创建认证服务器用户安全配置中心:
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package cn.itxsl.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collection;

/**
* @program: itxsl-cloud
* @description: 账号认证中心
* @author: itxsl
* @create: 2019-04-23 15:53
**/
@EnableWebSecurity
public class WebSecurityConfigure extends WebSecurityConfigurerAdapter {

@Bean
public UserDetailsService userDetailsService(){
return new UserDetailsService() {//这里一般都是在业务层,实现UserDetailsService中loadUserByUsername(String s)方法去数据库查询用户
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return new UserDetails() {
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}

@Override
public String getPassword() {
return "itxsl";
}

@Override
public String getUsername() {
return "itxsl";
}

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
};
}
} ;
}



@Bean//密码编码模式,这里没使用加密,需要加密可创建一个new BCryptPasswordEncoder()返回,
// 这里加密后,用户密码和ClientSecret都会用加密后的串进行校验密码
public PasswordEncoder passwordEncoder(){

return new PasswordEncoder() {
@Override
public String encode(CharSequence charSequence) {
return charSequence.toString();
}

@Override
public boolean matches(CharSequence charSequence, String s) {
return charSequence.toString().equals(s);
}
};
}

@Override
@Bean//定义没有password grant_type
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
5.创建一个配置文件application.yml配置端口,内容如下:
1
2
3
4
5
server:
port: 7002
logging:
level:
root: info

二.启动项目测试认证服务中心。

1.启动项目

项目启动成功!

2.根据第三方应用配置中心及用户配置中心中应用信息和用户信息进行测试。
3.在浏览器地址栏中输入下面内容并访问:

http://127.0.0.1:7002/oauth/authorize?client_id=itxsl&redirect_uri=http://localhost:7003/auth/account&response_type=code&scope=all&state=1a6L30

接下来会进入一个登录页面:

4.输入账号和密码‘itxsl’完成登录拿到code码:

5.接下来打开postman,使用post请求获取token:

输入client_id和client_sercet

成功获取access_token等信息:

到此认证服务器Demo搭建完毕。

源码地址: 源码