SpringBoot 使用jwt進行身份驗證

2021-08-23 12:36:35 字數 2605 閱讀 2694

這裡只供參考,比較使用jwt方式進行身份驗證感覺不好,最不行的就是不能退出

登陸時設定多長過期時間,只能等這個時間過了以後才算退出,服務端只能驗證請求過來的token是否通過驗證

code:

/**

* created by qhong on 2018/6/7 15:34

* 標註該註解的,就不需要登入

**/@target()

@retention(retentionpolicy.runtime)

@documented

public @inte***ce authignore

loginuser:

@target(elementtype.parameter)

@retention(retentionpolicy.runtime)

public @inte***ce loginuser

jwtutil:

@configurationproperties(prefix = "jwt")

@component

public class jwtutils

public claims getclaimbytoken(string token) catch (exception e)

}/**

* token是否過期

* @return true:過期

*/public boolean istokenexpired(date expiration)

public string getsecret()

public void setsecret(string secret)

public long getexpire()

public void setexpire(long expire)

public string getheader()

public void setheader(string header)

}

# 加密秘鑰

jwt.secret=f4e2e52034348f86b67cde581c0f9eb5

# token有效時長,單位秒

jwt.expire=60000

jwt.header=token

***:

/**

* created by qhong on 2018/6/7 15:36

**/@component

public class authorizationinterceptor extends handlerinterceptoradapter else

//如果有@authignore註解,則不驗證token

if(annotation != null)

//獲取使用者憑證

string token = request.getheader(jwtutils.getheader());

if(stringutils.isblank(token))

//token憑證為空

if(stringutils.isblank(token))

claims claims = jwtutils.getclaimbytoken(token);

if(claims == null || jwtutils.istokenexpired(claims.getexpiration()))

//設定userid到request裡,後續根據userid,獲取使用者資訊

request.setattribute(user_key, long.parselong(claims.getsubject()));

return true;

}}

註解攔截:

@component

public class loginuserhandlermethodargumentresolver implements handlermethodargumentresolver

@override

public object resolveargument(methodparameter parameter, modelandviewcontainer container,

nativewebrequest request, webdatabinde***ctory factory) throws exception

//獲取使用者資訊

user user = userservice.selectbyid((long)object);

return user;

}}

webconfig:

@configuration

public class webconfig extends webmvcconfigureradapter

@override

public void addargumentresolvers(listargumentresolvers)

}

login:

@authignore

public r login2(@requestbody user u)

loginuser註解使用:

public user query2(@loginuser user u)

Springboot整合JWT做登入攔截

為什麼需要jwt在傳統的 session 驗證中,服務端必須儲存 session id,用於與使用者傳過來的 cookie 驗證。而在一開始儲存 session id 時,只會儲存在一台伺服器上,所以只能由乙個 server 應答,就算其他伺服器有空閒也無法應答,因此也利用不到分布式伺服器的優點。而...

jwt使用實戰

what is jwt?json web token,主要是用來做認證的,因為他是基於數字簽名的 所以安全性賊高,是一種協議,本身是json格式,支援跨語言,同時它由三部分組成header 用於說明加密演算法和說明是jwt playload 傳輸使用者需要攜帶的脫敏業務資訊 signature 用來...

JWT使用記錄

keyhelper 生產公鑰和私鑰 publickeyfilename為公鑰檔案及路徑 privatekeyfilename為私鑰檔案及路徑 public static void generatekey string publickeyfilename,string privatekeyfilena...