overview
最近在弄單點登錄,踩了不少坑,所以記錄一下,做了個簡單的例子。
目標:認證服務器認證后獲取 token,客戶端訪問資源時帶上 token 進行安全驗證。
可以直接看源碼。
關鍵依賴
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
|
<parent> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-parent</artifactid> <version> 2.1 . 2 .release</version> <relativepath/> </parent> <dependencies> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-test</artifactid> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework.security.oauth.boot</groupid> <artifactid>spring-security-oauth2-autoconfigure</artifactid> <version> 2.1 . 2 .release</version> </dependency> </dependencies> |
認證服務器
認證服務器的關鍵代碼有如下幾個文件:
authserverapplication
:
1
2
3
4
5
6
7
8
|
@springbootapplication @enableresourceserver public class authserverapplication { public static void main(string[] args) { springapplication.run(authserverapplication. class , args); } } |
authorizationserverconfiguration
認證配置:
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
|
@configuration @enableauthorizationserver class authorizationserverconfiguration extends authorizationserverconfigureradapter { @autowired authenticationmanager authenticationmanager; @autowired tokenstore tokenstore; @autowired bcryptpasswordencoder encoder; @override public void configure(clientdetailsserviceconfigurer clients) throws exception { //配置客戶端 clients .inmemory() .withclient( "client" ) .secret(encoder.encode( "123456" )).resourceids( "hi" ) .authorizedgranttypes( "password" , "refresh_token" ) .scopes( "read" ); } @override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { endpoints .tokenstore(tokenstore) .authenticationmanager(authenticationmanager); } @override public void configure(authorizationserversecurityconfigurer oauthserver) throws exception { //允許表單認證 oauthserver .allowformauthenticationforclients() .checktokenaccess( "permitall()" ) .tokenkeyaccess( "permitall()" ); } } |
代碼中配置了一個 client,id 是 client
,密碼 123456
。 authorizedgranttypes
有 password
和refresh_token
兩種方式。
securityconfiguration
安全配置:
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
|
@configuration @enablewebsecurity public class securityconfiguration extends websecurityconfigureradapter { @bean public tokenstore tokenstore() { return new inmemorytokenstore(); } @bean public bcryptpasswordencoder encoder() { return new bcryptpasswordencoder(); } @override protected void configure(authenticationmanagerbuilder auth) throws exception { auth.inmemoryauthentication() .passwordencoder(encoder()) .withuser( "user_1" ).password(encoder().encode( "123456" )).roles( "user" ) .and() .withuser( "user_2" ).password(encoder().encode( "123456" )).roles( "admin" ); } @override protected void configure(httpsecurity http) throws exception { // @formatter:off http.csrf().disable() .requestmatchers() .antmatchers( "/oauth/authorize" ) .and() .authorizerequests() .anyrequest().authenticated() .and() .formlogin().permitall(); // @formatter:on } @override @bean public authenticationmanager authenticationmanagerbean() throws exception { return super .authenticationmanagerbean(); } } |
上面在內存中創建了兩個用戶,角色分別是 user
和 admin
。后續可考慮在數據庫或者 redis 中存儲相關信息。
authuser
配置獲取用戶信息的 controller:
1
2
3
4
5
6
7
8
|
@restcontroller public class authuser { @getmapping ( "/oauth/user" ) public principal user(principal principal) { return principal; } } |
application.yml
配置,主要就是配置個端口號:
1
2
3
4
5
6
7
8
|
--- spring: profiles: active: dev application: name: auth-server server: port: 8101 |
客戶端配置
客戶端的配置比較簡單,主要代碼結構如下:
application.yml
配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
--- spring: profiles: active: dev application: name: client server: port: 8102 security: oauth2: client: client-id: client client-secret: 123456 access-token-uri: http: //localhost:8101/oauth/token user-authorization-uri: http: //localhost:8101/oauth/authorize scope: read use-current-uri: false resource: user-info-uri: http: //localhost:8101/oauth/user |
這里主要是配置了認證服務器的相關地址以及客戶端的 id 和 密碼。user-info-uri
配置的就是服務器端獲取用戶信息的接口。
hellocontroller
訪問的資源,配置了 admin
的角色才可以訪問:
1
2
3
4
5
6
7
8
|
@restcontroller public class hellocontroller { @requestmapping ( "/hi" ) @preauthorize ( "hasrole('admin')" ) public responseentity<string> hi() { return responseentity.ok().body( "auth success!" ); } } |
websecurityconfiguration
相關安全配置:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@configuration @enableoauth2sso @enableglobalmethodsecurity (prepostenabled = true ) class websecurityconfiguration extends websecurityconfigureradapter { @override public void configure(httpsecurity http) throws exception { http .csrf().disable() // 基于token,所以不需要session .sessionmanagement().sessioncreationpolicy(sessioncreationpolicy.stateless) .and() .authorizerequests() .anyrequest().authenticated(); } } |
其中 @enableglobalmethodsecurity(prepostenabled = true)
開啟后,spring security 的 @preauthorize,@postauthorize
注解才可以使用。
@enableoauth2sso
配置了單點登錄。
clientapplication
:
1
2
3
4
5
6
7
8
|
@springbootapplication @enableresourceserver public class clientapplication { public static void main(string[] args) { springapplication.run(clientapplication. class , args); } } |
驗證
啟動項目后,我們使用 postman 來進行驗證。
首先是獲取 token:
選擇 post 提交,地址為驗證服務器的地址,參數中輸入 username
,password
,grant_type
和 scope
,其中 grant_type
需要輸入 password
。
然后在下面等 authorization 標簽頁中,選擇 basic auth,然后輸入 client 的 id 和 password。
1
2
3
4
5
6
7
|
{ "access_token" : "02f501a9-c482-46d4-a455-bf79a0e0e728" , "token_type" : "bearer" , "refresh_token" : "0e62dddc-4f51-4cb5-81c3-5383fddbb81b" , "expires_in" : 41741 , "scope" : "read" } |
此時就可以獲得 access_token
為: 02f501a9-c482-46d4-a455-bf79a0e0e728
。需要注意的是這里是用 user_2 獲取的 token,即角色是 admin
。
然后我們再進行獲取資源的驗證:
使用 get 方法,參數中輸入 access_token,值輸入 02f501a9-c482-46d4-a455-bf79a0e0e728
。
點擊提交后即可獲取到結果。
如果我們不加上 token ,則會提示無權限。同樣如果我們換上 user_1 獲取的 token,因 user_1 的角色是 user
,此資源需要 admin
權限,則此處還是會獲取失敗。
簡單的例子就到這,后續有時間再加上其它功能吧,謝謝~
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://segmentfault.com/a/1190000018323304