JAVA-Actual-Combat-5

Java实战 (Jwt令牌生成) 5

简介

JWT (JSON Web Token) 是一个开放标准[2],它定义了一种以紧凑和自包含的方法,用于在双方之间安全地传输编码为 JSON 对象的信息。

因此,简单来说,它是 JSON 格式的加密字符串,其中包含敏感信息,它使我们能够验证不同服务间的发送者。

代码示例

1. 依赖配置

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
</dependency>

2. JwtToken实体类

package com.sevattal.common.base.util;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
 * @author Sevattal
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtInfo {
    private String id;
    private String name;
    private List<String> roles;
    private String avatar;
    //权限、角色等
    //不要存敏感信息
}

3. JwtToken工具类(用于生成token、验证token)

package com.sevattal.common.base.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.springframework.util.StringUtils;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.List;
/**
 * @author Sevattal
 **/
public class JwtUtils {
    public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
    private static Key getKeyInstance(){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] bytes = DatatypeConverter.parseBase64Binary(APP_SECRET);
        return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
    }
    public static String getJwtToken(JwtInfo jwtInfo, int expire){
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("sevattal-user")//主题
                .setIssuedAt(new Date())//颁发时间
                .setExpiration(DateTime.now().plusSeconds(expire).toDate())//过期时间
                .claim("id", jwtInfo.getId())//用户id
                .claim("name", jwtInfo.getName())//用户昵称
                .claim("roles",jwtInfo.getRoles()) //用户角色
                .claim("avatar", jwtInfo.getAvatar())//用户头像
                .signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .compact();
        return JwtToken;
    }
    /**
     * 判断token是否存在与有效
     * @param jwtToken
     * @return
     */
    public static boolean checkJwtTToken(String jwtToken) {
        if(StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 判断token是否存在与有效
     * @param request
     * @return
     */
    public static boolean checkJwtTToken(HttpServletRequest request) {
        try {
            String jwtToken = request.getHeader("token");
            if(StringUtils.isEmpty(jwtToken)) return false;
            Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 根据token获取会员id
     * @param request
     * @return
     */
    public static JwtInfo getUserIdByJwtToken(HttpServletRequest request) {
        String jwtToken = request.getHeader("token");
        if(StringUtils.isEmpty(jwtToken)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
        Claims claims = claimsJws.getBody();
        JwtInfo jwtInfo = new JwtInfo(claims.get("id").toString(), claims.get("name").toString(),(List<String>)claims.get("roles"), claims.get("avatar").toString());
        return jwtInfo;
    }
    public static JwtInfo getUserIdByJwtToken(String token) {
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        JwtInfo jwtInfo = new JwtInfo(claims.get("id").toString(), claims.get("name").toString(),(List<String>)claims.get("roles"), claims.get("avatar").toString());
        return jwtInfo;
    }
}
Contents
  1. 1. Java实战 (Jwt令牌生成) 5
    1. 1.1. 简介
    2. 1.2. 代码示例
      1. 1.2.1. 1. 依赖配置
      2. 1.2.2. 2. JwtToken实体类
      3. 1.2.3. 3. JwtToken工具类(用于生成token、验证token)
|