您好,登錄后才能下訂單哦!
先介紹下利用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無效或者已過期。
流程圖如下:
一、用戶發(fā)起登錄請求
二、服務(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返回
看后面有個Token
三、在后續(xù)請求中JWT信息作為請求頭,發(fā)給服務(wù)端
四、服務(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í)有所幫助,也希望大家多多支持億速云。
免責(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)容。