JsonWebToken生成

import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.sgcc.iot.application.application.entity.ApplicationVo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

/**
 * 生成token
 * @author hemingzhu
 *
 */
@Component
public class JwtTokenProvider {

  /**
   * THIS IS NOT A SECURE PRACTICE! For simplicity, we are storing a static key here. Ideally, in a
   * microservices environment, this key would be kept on a config-server.
   */
  @Value("${security.jwt.token.secret-key:secret-key}")
  private String secretKey;

@PostConstruct
  protected void init() {
    secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes());
  }


  public String createToken(ApplicationVo applicationVo) {


    Claims claims = Jwts.claims().setSubject(applicationVo.getApplicationName());
    claims.setSubject(applicationVo.getId());
    claims.setSubject(String.valueOf(System.currentTimeMillis()));
    claims.setSubject(UUID.randomUUID().toString());
	long nowMillis = System.currentTimeMillis();
	Date now = new Date(nowMillis);


	Calendar calendar = Calendar.getInstance();
	Date date = new Date(System.currentTimeMillis());
	calendar.setTime(date);
	calendar.add(Calendar.YEAR, 1);
	date = calendar.getTime();
    return Jwts.builder()
        .setClaims(claims)
        .setIssuedAt(now)
        .setExpiration(date) //过期时间
        .signWith(SignatureAlgorithm.HS256, secretKey)
        .compact();
  }
  

}

生成jsonwentoken

jar包:

compile group: 'io.jsonwebtoken', name: 'jjwt', version: '0.9.0'

解密

	/**
	 * 校验token
	 * 
	 * @param token
	 * @param key
	 * @throws Exception
	 */
	public static void verifyToken(String token, String key) throws Exception {
		try { 
			//Jwts.parser().setSigningKey(secretKey).parseClaimsJws(token);   // 可以用来验证是否正确
			JWTVerifier verifier = JWT.require(Algorithm.HMAC256(key)).build();
			DecodedJWT jwt = verifier.verify(token);
			Map<String, Claim> claims = jwt.getClaims();
			System.out.println(claims.get("applicationName").asString());
		} catch (InvalidClaimException e) {
			logger.info("token过期");
		} catch (SignatureVerificationException e) {
			logger.info("key错误");
		}
	}

阅读更多
文章标签: jsonwebtoken
个人分类: 后台
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭