All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cuisongliu.jwt.tools.JwtTokenTool Maven / Gradle / Ivy

The newest version!
package com.cuisongliu.jwt.tools;
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2018 [email protected]
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

import com.cuisongliu.jwt.autoconfig.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 

jwt token工具类

*
 *     jwt的claim里一般包含以下几种数据:
 *     1. iss -- token的发行者
 *     2. sub -- 该JWT所面向的用户
 *     3. aud -- 接收该JWT的一方
 *     4. exp -- token的失效时间
 *     5. nbf -- 在此时间段之前,不会被处理
 *     6. iat -- jwt发布时间
 *     7. jti -- jwt唯一标识,防止重复使用
 * 
* * @author cuisongliu [[email protected]] * @since 2018-02-28 22:01 */ public class JwtTokenTool { private final JwtProperties jwtProperties; public JwtTokenTool(JwtProperties jwtProperties) { this.jwtProperties = jwtProperties; } /** * 获取用户名从token中 */ public String getUsernameFromToken(String token) { return getClaimFromToken(token).getSubject(); } /** * 获取jwt发布时间 */ public Date getIssuedAtDateFromToken(String token) { return getClaimFromToken(token).getIssuedAt(); } /** * 获取jwt失效时间 */ public Date getExpirationDateFromToken(String token) { return getClaimFromToken(token).getExpiration(); } /** * 获取jwt接收者 */ public String getAudienceFromToken(String token) { return getClaimFromToken(token).getAudience(); } /** * 获取私有的jwt claim */ public String getPrivateClaimFromToken(String token, String key) { return getClaimFromToken(token).get(key).toString(); } /** * 获取md5 key从token中 */ public String getMd5KeyFromToken(String token) { return getPrivateClaimFromToken(token, jwtProperties.getMd5Key()); } /** * 获取jwt的payload部分 */ public Claims getClaimFromToken(String token) { return Jwts.parser() .setSigningKey(jwtProperties.getSecret()) .parseClaimsJws(token) .getBody(); } /** * 解析token是否正确,不正确会报异常
*/ public void parseToken(String token) throws JwtException { Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token).getBody(); } /** *
     *  验证token是否失效
     *  true:过期   false:没过期
     * 
*/ public Boolean isTokenExpired(String token) { final Date expiration = getExpirationDateFromToken(token); return expiration.before(new Date()); } /** * 生成token(通过用户名和签名时候用的随机数) */ public String generateToken(String userName, String randomKey) { Map claims = new HashMap<>(); claims.put(jwtProperties.getMd5Key(), randomKey); return doGenerateToken(claims, userName); } /** * 生成token */ private String doGenerateToken(Map claims, String subject) { final Date createdDate = new Date(); final Date expirationDate = new Date(createdDate.getTime() + jwtProperties.getExpiration() * 1000); return Jwts.builder() .setClaims(claims) .setSubject(subject) .setIssuedAt(createdDate) .setExpiration(expirationDate) .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret()) .compact(); } /** * 获取混淆MD5签名用的随机字符串 */ public String getRandomKey() { return getRandomString(); } /** * 获取随机位数的字符串 * @author cuisongliu */ private String getRandomString() { String base = "abcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 6; i++) { int number = random.nextInt(base.length()); sb.append(base.charAt(number)); } return sb.toString(); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy