JWT結合springboot來實現token的分發與校驗
阿新 • • 發佈:2019-05-07
因工作中需要用到登陸,此時就要用到token的分發與校驗,採用jwt來進行token的生成與校驗,下面把使用方法記下:
大致方案:
利用jwt生成token,併發放給前端;
下一次前端請求後端url時帶上token,後端利用jwt相同的金鑰對token進行校驗,如果校驗成功,允許前端訪問後端api,返回200;
如果校驗失敗,返回給前端401;
依賴:
compile('com.auth0:java-jwt:3.4.0')
生成token:
public static String genToken(Map<String, String> claims, Date expireDatePoint){ try { //使用HMAC256進行加密 Algorithm algorithm = Algorithm.HMAC256(SECRET); //金鑰 //建立jwt JWTCreator.Builder builder = JWT.create() .withClaim("loginName", username) withExpiresAt(expireDatePoint); //過期時間點 //傳入引數 claims.forEach((key,value)-> { builder.withClaim(key, value); }); //簽名加密 return builder.sign(algorithm); } catch (IllegalArgumentException | UnsupportedEncodingException e) { throw new RuntimeException(e); } }
校驗token
public static Map<String,String> verifyToken(String token) throws RuntimeException{ Algorithm algorithm = null; try { //使用HMAC256進行加密 algorithm = Algorithm.HMAC256(SECRET); } catch (IllegalArgumentException | UnsupportedEncodingException e) { throw new RuntimeException(e); } //解密 JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build(); DecodedJWT jwt = verifier.verify(token); Map<String, Claim> map = jwt.getClaims(); Map<String, String> resultMap = new HashMap<>(); map.forEach((k,v) -> resultMap.put(k, v.asString())); return resultMap; }
校驗token,可以用在微服務當中的api gateway服務,利用全域性過濾器globalFilter,對所有api進行攔截,校驗token的合法性,選擇是否