Jwt快速入門(copy即可)
阿新 • • 發佈:2020-09-06
Jwt
-
什麼是jwt
- JSON Web Token(縮寫 JWT)是目前最流行的跨域認證解決方案,本文介紹它的原理和用法。
-
網際網路服務離不開使用者認證。一般流程是下面這樣。
1、使用者向伺服器傳送使用者名稱和密碼。
2、伺服器驗證通過後,在當前對話(session)裡面儲存相關資料,比如使用者角色、登入時間等等。
3、伺服器向用戶返回一個 session_id,寫入使用者的 Cookie。
4、使用者隨後的每一次請求,都會通過 Cookie,將 session_id 傳回伺服器。
5、伺服器收到 session_id,找到前期儲存的資料,由此得知使用者的身份。
匯入依賴
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.10.3</version> </dependency>
編寫工具類
package com.botao.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import java.util.Calendar; import java.util.HashMap; import java.util.Map; /** * @author 星時代曹波濤 */ public class JwtUtils { /** * 簽名 */ private static final String SING = "!@#$%^&*(^432142@#$^&"; public static String getToken(Map<String, String> map) { Calendar calendar = Calendar.getInstance(); //設定過期時間為7天 calendar.add(Calendar.DATE, 7); JWTCreator.Builder builder = JWT.create(); map.forEach(builder::withClaim); String token = builder.withExpiresAt(calendar.getTime()) .sign(Algorithm.HMAC256(SING)); return token; } public static String getToken() { Map<String, String> map = new HashMap<String, String>(4); return getToken(map); } public static boolean verify(String token){ try { JWT.require(Algorithm.HMAC256(SING)).build().verify(token); return true; }catch (Exception e){ e.printStackTrace(); return false; } } public static DecodedJWT getMsg(String token){ try { return JWT.require(Algorithm.HMAC256(SING)).build().verify(token); }catch (Exception e){ e.printStackTrace(); return null; } } }
程式碼測試
@Test public void test(){ HashMap<String, String> map = new HashMap<>(); map.put("username","張三"); String token = JwtUtils.getToken(map); System.out.println("token:"+token); System.out.println("結果:===》"+JwtUtils.verify(token)); System.out.println("資訊:===》"+JwtUtils.getMsg(token).getClaim("username").asString()); }
執行結果
token:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1OTk5ODM1MjUsInVzZXJuYW1lIjoi5byg5LiJIn0.SIKyAbXZ_1FhVb9wr2DoP6PyqwMm_i0RQYNtmiB6umk
結果:===》true
資訊:===》張三