Java中使用JWT生成Token進行接口鑒權實現(xiàn)方法
先介紹下利用JWT進行鑒權的思路:
1、用戶發(fā)起登錄請求。
2、服務端創(chuàng)建一個加密后的JWT信息,作為Token返回。
3、在后續(xù)請求中JWT信息作為請求頭,發(fā)給服務端。
4、服務端拿到JWT之后進行解密,正確解密表示此次請求合法,驗證通過;解密失敗說明Token無效或者已過期。
流程圖如下:
一、用戶發(fā)起登錄請求
二、服務端創(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ā)給服務端
四、服務端拿到JWT之后進行解密,正確解密表示此次請求合法,驗證通過;解密失敗說明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)拒絕響應!</font>"); return false; } else{ return true; } } }
2、拿到之后進行解密校驗
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()); }
五、總結
大家知道,我之前做過爬蟲,實際這種思路在微博做反爬時也用過,做過我之前文章的同學應該知道。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
解決Callable的對象中,用@Autowired注入別的對象失敗問題
這篇文章主要介紹了解決Callable的對象中,用@Autowired注入別的對象失敗問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07SpringBoot使用Minio進行文件存儲的實現(xiàn)
本文主要介紹了SpringBoot使用Minio進行文件存儲的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07JDK生成WebService客戶端代碼以及調(diào)用方式
WebService 是一種跨編程語言和跨操作系統(tǒng)平臺的遠程調(diào)用技術,下面這篇文章主要給大家介紹了關于JDK生成WebService客戶端代碼以及調(diào)用方式的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2024-08-08SpringBoot+MybatisPlus+Mysql+JSP實戰(zhàn)
這篇文章主要介紹了SpringBoot+MybatisPlus+Mysql+JSP實戰(zhàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12