溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法

發(fā)布時間:2020-09-01 18:51:05 來源:腳本之家 閱讀:247 作者:小怪聊職場 欄目:編程語言

先介紹下利用JWT進(jìn)行鑒權(quán)的思路:

1、用戶發(fā)起登錄請求。

2、服務(wù)端創(chuàng)建一個加密后的JWT信息,作為Token返回。

3、在后續(xù)請求中JWT信息作為請求頭,發(fā)給服務(wù)端。

4、服務(wù)端拿到JWT之后進(jìn)行解密,正確解密表示此次請求合法,驗(yàn)證通過;解密失敗說明Token無效或者已過期。

流程圖如下:

Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法

一、用戶發(fā)起登錄請求

Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法

二、服務(wù)端創(chuàng)建一個加密后的JWT信息,作為Token返回

1、用戶登錄之后把生成的Token返回給前端

@Authorization
@ResponseBody
@GetMapping("user/auth")
public Result getUserSecurityInfo(HttpServletRequest request) {
 try {
  UserDTO userDTO = ...
  UserVO userVO = new UserVO();
  //這里調(diào)用創(chuàng)建JWT信息的方法
  userVO.setToken(TokenUtil.createJWT(String.valueOf(userDTO.getId())));
  return Result.success(userVO);
 } catch (Exception e) {
  return Result.fail(ErrorEnum.SYSTEM_ERROR);
 }
}

2、創(chuàng)建JWT,Generate Tokens

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import java.util.Date; 
 
//Sample method to construct a JWT
private String createJWT(String id, String issuer, String subject, long ttlMillis) {
 
 //The JWT signature algorithm we will be using to sign the token
 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
 
 long nowMillis = System.currentTimeMillis();
 Date now = new Date(nowMillis);
 
 //We will sign our JWT with our ApiKey secret
 byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey.getSecret());
 Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
 
 //Let's set the JWT Claims
 JwtBuilder builder = Jwts.builder().setId(id)
        .setIssuedAt(now)
        .setSubject(subject)
        .setIssuer(issuer)
        .signWith(signatureAlgorithm, signingKey);
 
 //if it has been specified, let's add the expiration
 if (ttlMillis >= 0) {
 long expMillis = nowMillis + ttlMillis;
  Date exp = new Date(expMillis);
  builder.setExpiration(exp);
 }
 
 //Builds the JWT and serializes it to a compact, URL-safe string
 return builder.compact();
}

3、作為Token返回

Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法

看后面有個Token

三、在后續(xù)請求中JWT信息作為請求頭,發(fā)給服務(wù)端

Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法

四、服務(wù)端拿到JWT之后進(jìn)行解密,正確解密表示此次請求合法,驗(yàn)證通過;解密失敗說明Token無效或者已過期。

1、在攔截器中讀取這個Header里面的Token值

@Slf4j
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {
 private boolean chechToken(HttpServletRequest request, HttpServletResponse response) throws IOException{
  Long userId = ...;

  if (!TokenUtil.parseJWT(request.getHeader("Authorization"), String.valueOf(userId))){
   response.setContentType("text/html;charset=GBK");
   response.setCharacterEncoding("GBK");
   response.setStatus(403);
   response.getWriter().print("<font size=6 color=red>對不起,您的請求非法,系統(tǒng)拒絕響應(yīng)!</font>");
   return false;
  } else{
   return true;
  }
 }
}

2、拿到之后進(jìn)行解密校驗(yàn)

Decode and Verify Tokens

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
 
//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
 //This line will throw an exception if it is not a signed JWS (as expected)
 Claims claims = Jwts.parser()   
  .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
  .parseClaimsJws(jwt).getBody();
 System.out.println("ID: " + claims.getId());
 System.out.println("Subject: " + claims.getSubject());
 System.out.println("Issuer: " + claims.getIssuer());
 System.out.println("Expiration: " + claims.getExpiration());
}

五、總結(jié)

大家知道,我之前做過爬蟲,實(shí)際這種思路在微博做反爬時也用過,做過我之前文章的同學(xué)應(yīng)該知道。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI