摘要:用spring-boot開發(fā)restful api非常的方便,在生產(chǎn)環(huán)境中,對(duì)發(fā)布的api增加授權(quán)保護(hù)是非常必要的。現(xiàn)在我們來看如何利用jwt技術(shù)為api增加授權(quán)保護(hù),保證只有獲得授權(quán)的用戶才能夠訪問api。
一:開發(fā)一個(gè)簡(jiǎn)單的api
在idea開發(fā)工具中新建一個(gè)maven工程,添加對(duì)應(yīng)的依賴如下:
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
|
<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-web</artifactid> </dependency> <!-- spring-data-jpa --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-data-jpa</artifactid> </dependency> <!-- mysql --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version> 5.1 . 30 </version> </dependency> <!-- spring-security 和 jwt --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-security</artifactid> </dependency> <dependency> <groupid>io.jsonwebtoken</groupid> <artifactid>jjwt</artifactid> <version> 0.7 . 0 </version> </dependency> |
新建一個(gè)usercontroller.java文件,在里面在中增加一個(gè)hello方法:
1
2
3
4
5
|
@requestmapping ( "/hello" ) @responsebody public string hello(){ return "hello" ; } |
這樣一個(gè)簡(jiǎn)單的restful api就開發(fā)好了。
現(xiàn)在我們運(yùn)行一下程序看看效果,執(zhí)行jwtauthapplication.java類中的main方法:
等待程序啟動(dòng)完成后,可以簡(jiǎn)單的通過curl工具進(jìn)行api的調(diào)用,如下圖:
至此,我們的接口就開發(fā)完成了。但是這個(gè)接口沒有任何授權(quán)防護(hù),任何人都可以訪問,這樣是不安全的,下面我們開始加入授權(quán)機(jī)制。
二:增加用戶注冊(cè)功能
首先增加一個(gè)實(shí)體類user.java:
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
|
package boss.portal.entity; import javax.persistence.*; /** * @author zhaoxinguo on 2017/9/13. */ @entity @table (name = "tb_user" ) public class user { @id @generatedvalue private long id; private string username; private string password; public long getid() { return id; } public string getusername() { return username; } public void setusername(string username) { this .username = username; } public string getpassword() { return password; } public void setpassword(string password) { this .password = password; } } |
然后增加一個(gè)repository類userrepository,可以讀取和保存用戶信息:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package boss.portal.repository; import boss.portal.entity.user; import org.springframework.data.jpa.repository.jparepository; /** * @author zhaoxinguo on 2017/9/13. */ public interface userrepository extends jparepository<user, long > { user findbyusername(string username); } |
在usercontroller類中增加注冊(cè)方法,實(shí)現(xiàn)用戶注冊(cè)的接口:
1
2
3
4
5
6
7
8
9
|
/** * 該方法是注冊(cè)用戶的方法,默認(rèn)放開訪問控制 * @param user */ @postmapping ( "/signup" ) public void signup( @requestbody user user) { user.setpassword(bcryptpasswordencoder.encode(user.getpassword())); applicationuserrepository.save(user); } |
其中的@postmapping("/signup")
這個(gè)方法定義了用戶注冊(cè)接口,并且指定了url地址是/users/signup。由于類上加了注解 @requestmapping(“/users”),類中的所有方法的url地址都會(huì)有/users前綴,所以在方法上只需指定/signup子路徑即可。
密碼采用了bcryptpasswordencoder進(jìn)行加密,我們?cè)赼pplication中增加bcryptpasswordencoder實(shí)例的定義。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
package boss.portal; import org.springframework.boot.springapplication; import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.context.annotation.bean; import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder; @springbootapplication public class jwtauthapplication { @bean public bcryptpasswordencoder bcryptpasswordencoder() { return new bcryptpasswordencoder(); } public static void main(string[] args) { springapplication.run(jwtauthapplication. class , args); } } |
三:增加jwt認(rèn)證功能
用戶填入用戶名密碼后,與數(shù)據(jù)庫(kù)里存儲(chǔ)的用戶信息進(jìn)行比對(duì),如果通過,則認(rèn)證成功。傳統(tǒng)的方法是在認(rèn)證通過后,創(chuàng)建sesstion,并給客戶端返回cookie。現(xiàn)在我們采用jwt來處理用戶名密碼的認(rèn)證。區(qū)別在于,認(rèn)證通過后,服務(wù)器生成一個(gè)token,將token返回給客戶端,客戶端以后的所有請(qǐng)求都需要在http頭中指定該token。服務(wù)器接收的請(qǐng)求后,會(huì)對(duì)token的合法性進(jìn)行驗(yàn)證。驗(yàn)證的內(nèi)容包括:
- 內(nèi)容是一個(gè)正確的jwt格式
- 檢查簽名
- 檢查claims
- 檢查權(quán)限
處理登錄
創(chuàng)建一個(gè)類jwtloginfilter,核心功能是在驗(yàn)證用戶名密碼正確后,生成一個(gè)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
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
|
package boss.portal.web.filter; import boss.portal.entity.user; import com.fasterxml.jackson.databind.objectmapper; import io.jsonwebtoken.jwts; import io.jsonwebtoken.signaturealgorithm; import org.springframework.security.authentication.authenticationmanager; import org.springframework.security.authentication.usernamepasswordauthenticationtoken; import org.springframework.security.core.authentication; import org.springframework.security.core.authenticationexception; import org.springframework.security.web.authentication.usernamepasswordauthenticationfilter; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.util.arraylist; import java.util.date; /** * 驗(yàn)證用戶名密碼正確后,生成一個(gè)token,并將token返回給客戶端 * 該類繼承自u(píng)sernamepasswordauthenticationfilter,重寫了其中的2個(gè)方法 * attemptauthentication :接收并解析用戶憑證。 * successfulauthentication :用戶成功登錄后,這個(gè)方法會(huì)被調(diào)用,我們?cè)谶@個(gè)方法里生成token。 * @author zhaoxinguo on 2017/9/12. */ public class jwtloginfilter extends usernamepasswordauthenticationfilter { private authenticationmanager authenticationmanager; public jwtloginfilter(authenticationmanager authenticationmanager) { this .authenticationmanager = authenticationmanager; } // 接收并解析用戶憑證 @override public authentication attemptauthentication(httpservletrequest req, httpservletresponse res) throws authenticationexception { try { user user = new objectmapper() .readvalue(req.getinputstream(), user. class ); return authenticationmanager.authenticate( new usernamepasswordauthenticationtoken( user.getusername(), user.getpassword(), new arraylist<>()) ); } catch (ioexception e) { throw new runtimeexception(e); } } // 用戶成功登錄后,這個(gè)方法會(huì)被調(diào)用,我們?cè)谶@個(gè)方法里生成token @override protected void successfulauthentication(httpservletrequest req, httpservletresponse res, filterchain chain, authentication auth) throws ioexception, servletexception { string token = jwts.builder() .setsubject(((org.springframework.security.core.userdetails.user) auth.getprincipal()).getusername()) .setexpiration( new date(system.currenttimemillis() + 60 * 60 * 24 * 1000 )) .signwith(signaturealgorithm.hs512, "myjwtsecret" ) .compact(); res.addheader( "authorization" , "bearer " + token); } } |
該類繼承自u(píng)sernamepasswordauthenticationfilter,重寫了其中的2個(gè)方法:
attemptauthentication
:接收并解析用戶憑證。
successfulauthentication
:用戶成功登錄后,這個(gè)方法會(huì)被調(diào)用,我們?cè)谶@個(gè)方法里生成token。
授權(quán)驗(yàn)證
用戶一旦登錄成功后,會(huì)拿到token,后續(xù)的請(qǐng)求都會(huì)帶著這個(gè)token,服務(wù)端會(huì)驗(yàn)證token的合法性。
創(chuàng)建jwtauthenticationfilter類,我們?cè)谶@個(gè)類中實(shí)現(xiàn)token的校驗(yàn)功能。
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
|
package boss.portal.web.filter; import io.jsonwebtoken.jwts; import org.springframework.security.authentication.authenticationmanager; import org.springframework.security.authentication.usernamepasswordauthenticationtoken; import org.springframework.security.core.context.securitycontextholder; import org.springframework.security.web.authentication.www.basicauthenticationfilter; import javax.servlet.filterchain; import javax.servlet.servletexception; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import java.io.ioexception; import java.util.arraylist; /** * token的校驗(yàn) * 該類繼承自basicauthenticationfilter,在dofilterinternal方法中, * 從http頭的authorization 項(xiàng)讀取token數(shù)據(jù),然后用jwts包提供的方法校驗(yàn)token的合法性。 * 如果校驗(yàn)通過,就認(rèn)為這是一個(gè)取得授權(quán)的合法請(qǐng)求 * @author zhaoxinguo on 2017/9/13. */ public class jwtauthenticationfilter extends basicauthenticationfilter { public jwtauthenticationfilter(authenticationmanager authenticationmanager) { super (authenticationmanager); } @override protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain chain) throws ioexception, servletexception { string header = request.getheader( "authorization" ); if (header == null || !header.startswith( "bearer " )) { chain.dofilter(request, response); return ; } usernamepasswordauthenticationtoken authentication = getauthentication(request); securitycontextholder.getcontext().setauthentication(authentication); chain.dofilter(request, response); } private usernamepasswordauthenticationtoken getauthentication(httpservletrequest request) { string token = request.getheader( "authorization" ); if (token != null ) { // parse the token. string user = jwts.parser() .setsigningkey( "myjwtsecret" ) .parseclaimsjws(token.replace( "bearer " , "" )) .getbody() .getsubject(); if (user != null ) { return new usernamepasswordauthenticationtoken(user, null , new arraylist<>()); } return null ; } return null ; } } |
該類繼承自basicauthenticationfilter,在dofilterinternal方法中,從http頭的authorization
項(xiàng)讀取token數(shù)據(jù),然后用jwts包提供的方法校驗(yàn)token的合法性。如果校驗(yàn)通過,就認(rèn)為這是一個(gè)取得授權(quán)的合法請(qǐng)求。
springsecurity配置
通過springsecurity的配置,將上面的方法組合在一起。
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
|
package boss.portal.security; import boss.portal.web.filter.jwtloginfilter; import boss.portal.web.filter.jwtauthenticationfilter; import org.springframework.boot.autoconfigure.security.securityproperties; import org.springframework.context.annotation.configuration; import org.springframework.core.annotation.order; import org.springframework.http.httpmethod; import org.springframework.security.config.annotation.authentication.builders.authenticationmanagerbuilder; import org.springframework.security.config.annotation.web.builders.httpsecurity; import org.springframework.security.config.annotation.web.configuration.websecurityconfigureradapter; import org.springframework.security.core.userdetails.userdetailsservice; import org.springframework.security.crypto.bcrypt.bcryptpasswordencoder; /** * springsecurity的配置 * 通過springsecurity的配置,將jwtloginfilter,jwtauthenticationfilter組合在一起 * @author zhaoxinguo on 2017/9/13. */ @configuration @order (securityproperties.access_override_order) public class websecurityconfig extends websecurityconfigureradapter { private userdetailsservice userdetailsservice; private bcryptpasswordencoder bcryptpasswordencoder; public websecurityconfig(userdetailsservice userdetailsservice, bcryptpasswordencoder bcryptpasswordencoder) { this .userdetailsservice = userdetailsservice; this .bcryptpasswordencoder = bcryptpasswordencoder; } @override protected void configure(httpsecurity http) throws exception { http.cors().and().csrf().disable().authorizerequests() .antmatchers(httpmethod.post, "/users/signup" ).permitall() .anyrequest().authenticated() .and() .addfilter( new jwtloginfilter(authenticationmanager())) .addfilter( new jwtauthenticationfilter(authenticationmanager())); } @override public void configure(authenticationmanagerbuilder auth) throws exception { auth.userdetailsservice(userdetailsservice).passwordencoder(bcryptpasswordencoder); } } |
這是標(biāo)準(zhǔn)的springsecurity配置內(nèi)容,就不在詳細(xì)說明。注意其中的
1
2
|
.addfilter( new jwtloginfilter(authenticationmanager())) .addfilter( new jwtauthenticationfilter(authenticationmanager())) |
這兩行,將我們定義的jwt方法加入springsecurity的處理流程中。
下面對(duì)我們的程序進(jìn)行簡(jiǎn)單的驗(yàn)證:
# 請(qǐng)求hello接口,會(huì)收到403錯(cuò)誤,如下圖:
curl http://localhost:8080/hello
# 注冊(cè)一個(gè)新用戶curl -h"content-type: application/json" -x post -d '{"username":"admin","password":"password"}' http://localhost:8080/users/signup
如下圖:
# 登錄,會(huì)返回token,在http header中,authorization: bearer 后面的部分就是tokencurl -i -h"content-type: application/json" -x post -d '{"username":"admin","password":"password"}' http://localhost:8080/login
如下圖:
# 用登錄成功后拿到的token再次請(qǐng)求hello接口# 將請(qǐng)求中的xxxxxx替換成拿到的token# 這次可以成功調(diào)用接口了curl -h"content-type: application/json" \-h"authorization: bearer xxxxxx" \"http://localhost:8080/users/hello"
如下圖:
五:總結(jié)
至此,給springboot的接口加上jwt認(rèn)證的功能就實(shí)現(xiàn)了,過程并不復(fù)雜,主要是開發(fā)兩個(gè)springsecurity的filter,來生成和校驗(yàn)jwt token。
jwt作為一個(gè)無狀態(tài)的授權(quán)校驗(yàn)技術(shù),非常適合于分布式系統(tǒng)架構(gòu),因?yàn)榉?wù)端不需要保存用戶狀態(tài),因此就無需采用redis等技術(shù),在各個(gè)服務(wù)節(jié)點(diǎn)之間共享session數(shù)據(jù)。
六:源碼下載地址
地址:https://gitee.com/micai/springboot-springsecurity-jwt-demo
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/sxdtzhaoxinguo/article/details/77965226