1、概括
在博客中,我們將討論如何讓spring security oauth2實現使用json web tokens。
2、maven 配置
首先,我們需要在我們的pom.xml中添加spring-security-jwt依賴項。
1
2
3
4
|
<dependency> <groupid>org.springframework.security</groupid> <artifactid>spring-security-jwt</artifactid> </dependency> |
我們需要為authorization server和resource server添加spring-security-jwt依賴項。
3、授權服務器
接下來,我們將配置我們的授權服務器使用jwttokenstore - 如下所示
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
|
@configuration @enableauthorizationserver public class oauth2authorizationserverconfig extends authorizationserverconfigureradapter { @override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { endpoints.tokenstore(tokenstore()) .accesstokenconverter(accesstokenconverter()) .authenticationmanager(authenticationmanager); } @bean public tokenstore tokenstore() { return new jwttokenstore(accesstokenconverter()); } @bean public jwtaccesstokenconverter accesstokenconverter() { jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); converter.setsigningkey( "123" ); return converter; } @bean @primary public defaulttokenservices tokenservices() { defaulttokenservices defaulttokenservices = new defaulttokenservices(); defaulttokenservices.settokenstore(tokenstore()); defaulttokenservices.setsupportrefreshtoken( true ); return defaulttokenservices; } } |
請注意,在jwtaccesstokenconverter中使用了一個對稱密鑰來簽署我們的令牌 - 這意味著我們需要為資源服務器使用同樣的確切密鑰。
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
|
@configuration @enableresourceserver public class oauth2resourceserverconfig extends resourceserverconfigureradapter { @override public void configure(resourceserversecurityconfigurer config) { config.tokenservices(tokenservices()); } @bean public tokenstore tokenstore() { return new jwttokenstore(accesstokenconverter()); } @bean public jwtaccesstokenconverter accesstokenconverter() { jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); converter.setsigningkey( "123" ); return converter; } @bean @primary public defaulttokenservices tokenservices() { defaulttokenservices defaulttokenservices = new defaulttokenservices(); defaulttokenservices.settokenstore(tokenstore()); return defaulttokenservices; } } |
請記住,我們將這兩個服務器定義為完全獨立且可獨立部署的服務器。這就是我們需要在新配置中再次聲明一些相同的bean的原因。
5、令牌中的自定義聲明
現在讓我們設置一些基礎設施,以便能夠在訪問令牌中添加一些自定義聲明。框架提供的標準聲明都很好,但大多數情況下我們需要在令牌中使用一些額外的信息來在客戶端使用。 我們將定義一個tokenenhancer來定制我們的access token與這些額外的聲明。 在下面的例子中,我們將添加一個額外的字段“組織”到我們的訪問令牌 - 與此customtokenenhancer:
1
2
3
4
5
6
7
8
9
10
11
|
public class customtokenenhancer implements tokenenhancer { @override public oauth2accesstoken enhance( oauth2accesstoken accesstoken, oauth2authentication authentication) { map<string, object> additionalinfo = new hashmap<>(); additionalinfo.put( "organization" , authentication.getname() + randomalphabetic( 4 )); ((defaultoauth2accesstoken) accesstoken).setadditionalinformation(additionalinfo); return accesstoken; } } |
然后,我們將把它連接到我們的授權服務器配置 - 如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@override public void configure(authorizationserverendpointsconfigurer endpoints) throws exception { tokenenhancerchain tokenenhancerchain = new tokenenhancerchain(); tokenenhancerchain.settokenenhancers( arrays.aslist(tokenenhancer(), accesstokenconverter())); endpoints.tokenstore(tokenstore()) .tokenenhancer(tokenenhancerchain) .authenticationmanager(authenticationmanager); } @bean public tokenenhancer tokenenhancer() { return new customtokenenhancer(); } |
有了這個新的配置啟動和運行 - 這是一個令牌令牌有效載荷看起來像:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
{ "user_name" : "john" , "scope" : [ "foo" , "read" , "write" ], "organization" : "johniich" , "exp" : 1458126622 , "authorities" : [ "role_user" ], "jti" : "e0ad1ef3-a8a5-4eef-998d-00b26bc2c53f" , "client_id" : "fooclientidpassword" } |
5.1、在js客戶端使用訪問令牌
最后,我們要在angualrjs客戶端應用程序中使用令牌信息。我們將使用angular-jwt庫。 所以我們要做的就是在index.html中使用“組織”聲明:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<p class = "navbar-text navbar-right" >{{organization}}</p> <script type= "text/javascript" src= "https://cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt.js" > </script> <script> var app = angular.module( 'myapp' , [ "ngresource" , "ngroute" , "ngcookies" , "angular-jwt" ]); app.controller( 'mainctrl' , function($scope, $cookies, jwthelper,...) { $scope.organiztion = "" ; function getorganization(){ var token = $cookies.get( "access_token" ); var payload = jwthelper.decodetoken(token); $scope.organization = payload.organization; } ... }); |
6、不對稱的keypair
在我們以前的配置中,我們使用對稱密鑰來簽署我們的令牌:
1
2
3
4
5
6
|
@bean public jwtaccesstokenconverter accesstokenconverter() { jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); converter.setsigningkey( "123" ); return converter; } |
我們還可以使用非對稱密鑰(公鑰和私鑰)來執行簽名過程。
6.1、生成jks java keystore文件
我們首先使用命令行工具keytool生成密鑰 - 更具體地說.jks文件:
1
2
3
4
5
|
keytool -genkeypair -alias mytest -keyalg rsa -keypass mypass -keystore mytest.jks -storepass mypass |
該命令將生成一個名為mytest.jks的文件,其中包含我們的密鑰 - 公鑰和私鑰。 還要確保keypass和storepass是一樣的。
6.2、導出公鑰
接下來,我們需要從生成的jks中導出我們的公鑰,我們可以使用下面的命令來實現:
1
|
keytool -list -rfc --keystore mytest.jks | openssl x509 -inform pem -pubkey |
示例回應如下所示:
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
|
-----begin public key----- miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeagik2wt4x2etdl41c7vfp osmquzmyoyteo2rsvemlf/hxieyvickr0sqzvkodhebcmigxqdz5prijtq3rhpy2 /5wjbcyq7yhgtlvspmy6sivxn7ndye7i5pxo/khk4nz+fa6p3l8+l90e/3qwf6j3 dkwnagjfry8absyxt1d5eliig1/geqzc0fzmnhhfrbtxwwxrlpudt0kfvf0qvmpr xxclxt+tee1sewgeqeoll5vxrlqmzzcbe1rz9kqqm43+a9qn5icsrndftaesq3cr lawjkl2kcwu1hwjqw+dzrsz1x4kexnmyzpdpbbgmu6mhdhpywi7skzt7mx4bdnuk eqidaqab -----end public key----- -----begin certificate----- miidczccafogawibagiegtziuzanbgkqhkig9w0baqsfada2mqswcqydvqqgewj1 czelmakga1uecbmcy2exczajbgnvbactamxhmq0wcwydvqqdewr0zxn0mb4xdte2 mdmxnta4mtazmfoxdte2mdyxmza4mtazmfownjelmakga1uebhmcdxmxczajbgnv bagtamnhmqswcqydvqqhewjsytenmasga1ueaxmedgvzddccasiwdqyjkozihvcn aqebbqadggepadccaqocggebaicctlremdhlq5enqu736trdkrmtmjsrxjtkbfxj cxf4vyhml4ncq9ekm1zkhrxaqjihl0a8+aa4o06t0rz8tv+viqqmku8h4ey77ktm urir1zezxwboyoav6pyh5oj8/hwuj9y/pi/dbp96sh+o9wylpwicruwpag0mf7dx erc4ibtf4bkswth2zjyyx6wbccfl65ava09cn739efzj0ccqi10/rrhtbhlhhknj iy+b10s6ps2xaxtuwfzeejun/mvuj+ynekzw30whrenwq5qfispdphflnr8caspn wuumdv+jbfztmsz3twwxplojb3yacsco0imu+5l+aq51cnkcaweaaamhmb8whqyd vr0obbyefogefubgquex9ujak34pyrskhk+wma0gcsqgsib3dqebcwuaa4ibaqb3 1elfneq45yo1cxnl0c1iqlknp2wxg89ahebkkuoa1zktoiznyjihw5myju/zscu0 ybobhtde5hdtsatma9sn5cpoaljwzpwv/zc6wyhawtfljzzc6d2rl3qyrsirxmsp /j1vq9wkesqdshnegy7ggrgjn4a8ckechszqyzxulq7zah6goeud+vjb+bhep4an hiyy1ouxd+hsdkeqqs+7em5u7ww6dz2q8mtfj5qaxjy75t0pprhwzmljuhuz+q2v ffwejeaonb9w9mcpe1caie+oeejz0jq0el3/djsx3rlvqzn+lmhrjjevhfyeb3xf llfcugha7hxn2xf3x1jw -----end certificate----- |
我們只取得我們的公鑰,并將其復制到我們的資源服務器src / main / resources / public.txt中
1
2
3
4
5
6
7
8
9
|
-----begin public key----- miibijanbgkqhkig9w0baqefaaocaq8amiibcgkcaqeagik2wt4x2etdl41c7vfp osmquzmyoyteo2rsvemlf/hxieyvickr0sqzvkodhebcmigxqdz5prijtq3rhpy2 /5wjbcyq7yhgtlvspmy6sivxn7ndye7i5pxo/khk4nz+fa6p3l8+l90e/3qwf6j3 dkwnagjfry8absyxt1d5eliig1/geqzc0fzmnhhfrbtxwwxrlpudt0kfvf0qvmpr xxclxt+tee1sewgeqeoll5vxrlqmzzcbe1rz9kqqm43+a9qn5icsrndftaesq3cr lawjkl2kcwu1hwjqw+dzrsz1x4kexnmyzpdpbbgmu6mhdhpywi7skzt7mx4bdnuk eqidaqab -----end public key----- |
6.3、maven 配置
接下來,我們不希望jms文件被maven過濾進程拾取 - 所以我們將確保將其排除在pom.xml中:
1
2
3
4
5
6
7
8
9
10
11
|
<build> <resources> <resource> <directory>src/main/resources</directory> <filtering> true </filtering> <excludes> <exclude>*.jks</exclude> </excludes> </resource> </resources> </build> |
如果我們使用spring boot,我們需要確保我們的jks文件通過spring boot maven插件添加到應用程序classpath - addresources:
1
2
3
4
5
6
7
8
9
10
11
|
<build> <plugins> <plugin> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-maven-plugin</artifactid> <configuration> <addresources> true </addresources> </configuration> </plugin> </plugins> </build> |
6.4、授權服務器
現在,我們將配置jwtaccesstokenconverter使用mytest.jks中的keypair,如下所示:
1
2
3
4
5
6
7
8
|
@bean public jwtaccesstokenconverter accesstokenconverter() { jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); keystorekeyfactory keystorekeyfactory = new keystorekeyfactory( new classpathresource( "mytest.jks" ), "mypass" .tochararray()); converter.setkeypair(keystorekeyfactory.getkeypair( "mytest" )); return converter; } |
6.5、資源服務器
最后,我們需要配置我們的資源服務器使用公鑰 - 如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@bean public jwtaccesstokenconverter accesstokenconverter() { jwtaccesstokenconverter converter = new jwtaccesstokenconverter(); resource resource = new classpathresource( "public.txt" ); string publickey = null ; try { publickey = ioutils.tostring(resource.getinputstream()); } catch ( final ioexception e) { throw new runtimeexception(e); } converter.setverifierkey(publickey); return converter; } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/chenjianandiyi/article/details/78604376