Java中使用JWT生成Token進(jìn)行接口鑒權(quán)實(shí)現(xiàn)方法
先介紹下利用JWT進(jìn)行鑒權(quán)的思路:
1、用戶發(fā)起登錄請(qǐng)求。
2、服務(wù)端創(chuàng)建一個(gè)加密后的JWT信息,作為Token返回。
3、在后續(xù)請(qǐng)求中JWT信息作為請(qǐng)求頭,發(fā)給服務(wù)端。
4、服務(wù)端拿到JWT之后進(jìn)行解密,正確解密表示此次請(qǐng)求合法,驗(yàn)證通過;解密失敗說明Token無效或者已過期。
流程圖如下:
一、用戶發(fā)起登錄請(qǐng)求
二、服務(wù)端創(chuàng)建一個(gè)加密后的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返回
看后面有個(gè)Token
三、在后續(xù)請(qǐng)求中JWT信息作為請(qǐng)求頭,發(fā)給服務(wù)端
四、服務(wù)端拿到JWT之后進(jìn)行解密,正確解密表示此次請(qǐng)求合法,驗(yàn)證通過;解密失敗說明Token無效或者已過期。
1、在攔截器中讀取這個(gè)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>對(duì)不起,您的請(qǐng)求非法,系統(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í)際這種思路在微博做反爬時(shí)也用過,做過我之前文章的同學(xué)應(yīng)該知道。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Callable的對(duì)象中,用@Autowired注入別的對(duì)象失敗問題
這篇文章主要介紹了解決Callable的對(duì)象中,用@Autowired注入別的對(duì)象失敗問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07SpringBoot使用Minio進(jìn)行文件存儲(chǔ)的實(shí)現(xiàn)
本文主要介紹了SpringBoot使用Minio進(jìn)行文件存儲(chǔ)的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07Java漢字轉(zhuǎn)拼音工具類完整代碼實(shí)例
這篇文章主要介紹了java漢字轉(zhuǎn)拼音工具類完整代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03mvn compile報(bào)錯(cuò)“程序包c(diǎn)om.XXX不存在”
本文主要介紹了mvn compile報(bào)錯(cuò)“程序包c(diǎn)om.XXX不存在”,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01JDK生成WebService客戶端代碼以及調(diào)用方式
WebService 是一種跨編程語言和跨操作系統(tǒng)平臺(tái)的遠(yuǎn)程調(diào)用技術(shù),下面這篇文章主要給大家介紹了關(guān)于JDK生成WebService客戶端代碼以及調(diào)用方式的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-08-08Spring自動(dòng)裝配之方法、構(gòu)造器位置的自動(dòng)注入操作
這篇文章主要介紹了Spring自動(dòng)裝配之方法、構(gòu)造器位置的自動(dòng)注入操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-08-08SpringBoot+MybatisPlus+Mysql+JSP實(shí)戰(zhàn)
這篇文章主要介紹了SpringBoot+MybatisPlus+Mysql+JSP實(shí)戰(zhàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12