类io.jsonwebtoken.JwtBuilder源码实例Demo

下面列出了怎么用io.jsonwebtoken.JwtBuilder的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
源代码4 项目: pravega   文件: JsonWebToken.java
/**
 * Returns the 3 part JWT string representation.
 *
 *  Example JWT:
 *   - Compact representation:
 *       eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjM3MDc2MjUyMjgsInMxIjoiUkVBRF9VUERBVEUifQ.j6xbFRIIZxv3GEedqKcZVy-49Y7U1710q-gjY43-UMgO_kwCH_9kJRuZ7Am589kg5TJewmGhGB9SPblES78pEg
 *   - Decoded parts:
 *       - header: {alg=HS512}
 *       - body/payload: {exp=3707625228, s1=READ_UPDATE},
 *       - signature: j6xbFRIIZxv3GEedqKcZVy-49Y7U1710q-gjY43-UMgO_kwCH_9kJRuZ7Am589kg5TJewmGhGB9SPblES78pEg
 *
 * @return compact representation of JWT
 */
public String toCompactString() {
    JwtBuilder builder = Jwts.builder()
            .setSubject(subject)
            .setAudience(audience)
            .setIssuedAt(Date.from(currentInstant));

    if (this.permissionsByResource != null) {
        // Subject, audience and issued at fields are claims (in the JWT body) too. Invoking the setClaims()
        // will override the fields we set before. Therefore, we use the append method addClaims(..), instead.
        builder.addClaims(permissionsByResource);
    }
    if (this.expirationTime != null) {
        builder.setExpiration(expirationTime);
    }
    builder.signWith(signatureAlgorithm, signingKey);
    return builder.compact();
}
 
源代码5 项目: ProjectStudy   文件: JjwtUtil.java
/**
 * 生成签名,获取Token
 *
 * @param username
 * @param base64Security
 * @return java.lang.String
 * @author Wang926454
 * @date 2018/8/31 10:03
 */
public static String createJWT(String username, String base64Security) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    // 生成JWT的时间
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    // 添加构成JWT的参数
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
            .setIssuedAt(now)
            .setSubject(username)
            .signWith(signatureAlgorithm, base64Security.getBytes());
    // 设置过期时间
    if (EXPIRE_TIME >= 0) {
        long expMillis = nowMillis + EXPIRE_TIME;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
    // 生成JWT
    return builder.compact();
}
 
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
@Override
public String createToken(String subject, long ttlMillis) {
	
	if (ttlMillis <= 0) {
		throw new RuntimeException("Expiry time must be greater than Zero :["+ttlMillis+"] ");
	}
	
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

	// The JWT signature algorithm we will be using to sign the token
	long nowMillis = System.currentTimeMillis();

	byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(secretKey);
	Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

	JwtBuilder builder = Jwts.builder()
			.setSubject(subject)				
			.signWith(signatureAlgorithm, signingKey);
	
	builder.setExpiration(new Date(nowMillis + ttlMillis));		

	return builder.compact();
}
 
源代码9 项目: faster-framework-project   文件: JwtService.java
/**
 * 生成token
 *
 * @param audience       观众,理解为此token允许哪些人使用。
 *                       可以是一个数组字符串,包含了所有的允许对象,如"www.baidu.com","www.qq.com"。
 *                       也可以是一个单一字符串,如:"{userId}"
 * @param expSecond      过期时间(秒)
 * @param base64Security 秘钥
 * @return String
 */
private String createToken(String audience, long expSecond, String base64Security) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    //生成签名密钥
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    //添加构成JWT的参数
    JwtBuilder builder = Jwts.builder()
            .setAudience(audience)
            .setIssuedAt(now)
            .claim("env", env)
            .signWith(signatureAlgorithm, signingKey);
    //添加Token过期时间
    if (expSecond > 0) {
        long expMillis = nowMillis + expSecond * 1000;
        Date exp = new Date(expMillis);
        builder = builder.setExpiration(exp).setNotBefore(now);
    }
    //生成Token
    return builder.compact();
}
 
源代码10 项目: samples-android   文件: Utils.java
public static String getJwt(String issuer, String nonce, Date expiredDate, Date issuedAt,
                            String... audience) {
    JwtBuilder builder = Jwts.builder();
    KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
    Map<String, Object> map = new HashMap<>();
    map.put(Claims.AUDIENCE, Arrays.asList(audience));

    return builder
            .addClaims(map)
            .claim("nonce", nonce)
            .setIssuer(issuer)
            .setSubject("sub")
            .setExpiration(expiredDate)
            .setIssuedAt(issuedAt)
            .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
            .compact();
}
 
@Override
public String getToken(final String username, final String password) {
    if (username == null || password == null) {
        return null;
    }
    final User user = (User) userDetailsService.loadUserByUsername(username);
    Map<String, Object> tokenData = new HashMap<>();
    if (password.equals(user.getPassword())) {
        tokenData.put("clientType", "user");
        tokenData.put("userID", user.getId());
        tokenData.put("username", user.getUsername());
        tokenData.put("token_create_date", LocalDateTime.now());
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, tokenExpirationTime);
        tokenData.put("token_expiration_date", calendar.getTime());
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.setExpiration(calendar.getTime());
        jwtBuilder.setClaims(tokenData);
        return jwtBuilder.signWith(SignatureAlgorithm.HS512, tokenKey).compact();

    } else {
        throw new ServiceException("Authentication error", this.getClass().getName());
    }
}
 
源代码12 项目: my_curd   文件: JwtUtils.java
/**
 * 生成签名
 *
 * @param username       用户名
 * @param roleList       角色集合
 * @param permissionList 权限集合
 * @return
 */
public static String buildToken(String username, List<String> roleList, List<String> permissionList) {
    // HS256签名算法
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    // 构造payload
    long nowSeconds = System.currentTimeMillis() / 1000;
    JSONObject payload = new JSONObject();
    payload.put("iss", ISS);                   // 签发者
    payload.put("iat", nowSeconds);             // 签发时间
    payload.put("exp", nowSeconds + EXPIRATION_TIME_VALUE);  // 过期时间

    payload.put("username", username);
    if (roleList == null) {
        payload.put("roleList", new ArrayList<>());
    }
    if (permissionList == null) {
        payload.put("permissionList", new ArrayList<>());
    }
    JwtBuilder builder = Jwts.builder().setPayload(payload.toJSONString())
            .signWith(signatureAlgorithm, signingKey);
    return builder.compact();
}
 
源代码13 项目: hsweb-framework   文件: JwtTokenGenerator.java
public String createJWT(String id, String subject, long ttlMillis) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = jwtConfig.generalKey();
    JwtBuilder builder = Jwts.builder()
            .setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .signWith(signatureAlgorithm, key);
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }
    return builder.compact();
}
 
源代码14 项目: kisso   文件: JwtHelper.java
/**
 * <p>
 * 签名并生成 Token
 * </p>
 */
public static String signCompact(JwtBuilder jwtBuilder) {
    SSOConfig config = SSOConfig.getInstance();
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.forName(config.getSignAlgorithm());
    if (SSOConstants.RSA.equals(signatureAlgorithm.getFamilyName())) {
        try {
            if(null == RSA_KEY) {
                ClassPathResource resource = new ClassPathResource(config.getRsaJksStore());
                KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                keystore.load(resource.getInputStream(), config.getRsaStorepass().toCharArray());
                RSA_KEY = keystore.getKey(config.getRsaAlias(), config.getRsaKeypass().toCharArray());
            }
            // RSA 签名
            return jwtBuilder.signWith(RSA_KEY, signatureAlgorithm).compact();
        } catch (Exception e) {
            throw new KissoException("signCompact error.", e);
        }
    }
    // 普通签名
    SecretKey secretKey = getSecretKey(config.getSignKey(), signatureAlgorithm);
    return jwtBuilder.signWith(secretKey, signatureAlgorithm).compact();
}
 
源代码15 项目: github-branch-source-plugin   文件: JwtHelper.java
/**
 * Create a JWT for authenticating to GitHub as an app installation
 * @param githubAppId the app ID
 * @param privateKey PKC#8 formatted private key
 * @return JWT for authenticating to GitHub
 */
static String createJWT(String githubAppId, final String privateKey) {
    requireNonNull(githubAppId, privateKey);

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.RS256;

    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    Key signingKey;
    try {
        signingKey = getPrivateKeyFromString(privateKey);
    } catch (GeneralSecurityException e) {
        throw new IllegalArgumentException("Couldn't parse private key for GitHub app, make sure it's PKCS#8 format", e);
    }

    JwtBuilder builder = Jwts.builder()
            .setIssuedAt(now)
            .setIssuer(githubAppId)
            .signWith(signingKey, signatureAlgorithm);

    Date exp = new Date(nowMillis + VALIDITY_MS);
    builder.setExpiration(exp);

    return builder.compact();
}
 
源代码16 项目: java-docs-samples   文件: MqttExample.java
/** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
private static String createJwtRsa(String projectId, String privateKeyFile)
    throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("RSA");

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}
 
源代码17 项目: java-docs-samples   文件: MqttExample.java
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
private static String createJwtEs(String projectId, String privateKeyFile)
    throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("EC");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
源代码18 项目: java-docs-samples   文件: HttpExample.java
/** Create an ES-based JWT for the given project id, signed with the given private key. */
private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("EC");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
源代码19 项目: java-docs-samples   文件: MqttCommandsDemo.java
/** Create a Cloud IoT Core JWT for the given project id, signed with the given RSA key. */
private static String createJwtRsa(String projectId, String privateKeyFile)
    throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("RSA");

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}
 
源代码20 项目: java-docs-samples   文件: MqttCommandsDemo.java
/** Create a Cloud IoT Core JWT for the given project id, signed with the given ES key. */
private static String createJwtEs(String projectId, String privateKeyFile)
    throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("EC");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
/** Create a RSA-based JWT for the given project id, signed with the given private key. */
private static String createJwtRsa(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("RSA");

  return jwtBuilder.signWith(SignatureAlgorithm.RS256, kf.generatePrivate(spec)).compact();
}
 
/** Create an ES-based JWT for the given project id, signed with the given private key. */
private static String createJwtEs(String projectId, String privateKeyFile) throws Exception {
  DateTime now = new DateTime();
  // Create a JWT to authenticate this device. The device will be disconnected after the token
  // expires, and will have to reconnect with a new token. The audience field should always be set
  // to the GCP project id.
  JwtBuilder jwtBuilder =
      Jwts.builder()
          .setIssuedAt(now.toDate())
          .setExpiration(now.plusMinutes(20).toDate())
          .setAudience(projectId);

  byte[] keyBytes = Files.readAllBytes(Paths.get(privateKeyFile));
  PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
  KeyFactory kf = KeyFactory.getInstance("EC");

  return jwtBuilder.signWith(SignatureAlgorithm.ES256, kf.generatePrivate(spec)).compact();
}
 
源代码23 项目: jjwt   文件: DefaultJwtBuilder.java
@Override
public JwtBuilder claim(String name, Object value) {
    Assert.hasText(name, "Claim property name cannot be null or empty.");
    if (this.claims == null) {
        if (value != null) {
            ensureClaims().put(name, value);
        }
    } else {
        if (value == null) {
            this.claims.remove(name);
        } else {
            this.claims.put(name, value);
        }
    }

    return this;
}
 
源代码24 项目: presto   文件: JsonWebTokenHandler.java
public String getBearerToken(String subject)
{
    checkState(jwtSigner.isPresent(), "not configured");

    JwtBuilder jwt = Jwts.builder()
            .setSubject(subject)
            .setExpiration(Date.from(ZonedDateTime.now().plusMinutes(5).toInstant()));

    jwtSigner.get().accept(jwt);
    jwtKeyId.ifPresent(keyId -> jwt.setHeaderParam(KEY_ID, keyId));
    jwtIssuer.ifPresent(jwt::setIssuer);
    jwtAudience.ifPresent(jwt::setAudience);

    return jwt.compact();
}
 
源代码25 项目: sureness   文件: JsonWebTokenUtil.java
/**
 *   json web token 签发
 * @param id 令牌ID
 * @param subject 用户ID
 * @param issuer 签发人
 * @param period 有效时间(毫秒)
 * @param roles 访问主张-角色
 * @param permissions 访问主张-权限
 * @param isRefresh 是否是刷新token
 * @param algorithm 加密算法
 * @return java.lang.String jwt
 */
public static String issueJwt(String id, String subject, String issuer, Long period,
                              List<String> roles, List<String> permissions,
                              Boolean isRefresh, SignatureAlgorithm algorithm) {
    // 当前时间戳
    long currentTimeMillis = System.currentTimeMillis();
    // 秘钥
    byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(secretKey);
    JwtBuilder jwtBuilder = Jwts.builder();
    if (id != null) {
        jwtBuilder.setId(id);
    }
    if (subject != null) {
        jwtBuilder.setSubject(subject);
    }
    if (issuer != null) {
        jwtBuilder.setIssuer(issuer);
    }
    // 设置签发时间
    jwtBuilder.setIssuedAt(new Date(currentTimeMillis));
    // 设置到期时间
    if (null != period) {
        jwtBuilder.setExpiration(new Date(currentTimeMillis + period * 1000));
    }
    if (roles != null) {
        jwtBuilder.claim("roles", roles);
    }
    if (permissions != null) {
        jwtBuilder.claim("perms", permissions);
    }
    if (isRefresh != null) {
        jwtBuilder.claim("isRefresh", isRefresh);
    }
    // 压缩,可选GZIP
    jwtBuilder.compressWith(CompressionCodecs.DEFLATE);
    // 加密设置
    jwtBuilder.signWith(algorithm, secretKeyBytes);
    return jwtBuilder.compact();
}
 
源代码26 项目: mogu_blog_v2   文件: JwtUtil.java
/**
 * 生成jwt token user
 *
 * @param userOpenId
 * @param userId
 * @param isUser
 * @param shopId
 * @return
 */
public static String createJWT(String userOpenId, Long userId, boolean isUser, Long shopId) {
    log.info("userOpenId" + userOpenId + "userId" + userId + "isUser" + isUser + "shopId" + shopId);
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    //生成签名密钥
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    //添加构成JWT的参数
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
            .claim("user_id", userId)
            .claim("shop_id", shopId)
            .claim("is_user", isUser)
            .claim("user_open_id", userOpenId)
            .signWith(signatureAlgorithm, signingKey);
    //添加Token过期时间
    if (expiresSecond >= 0) {
        long expMillis = nowMillis + expiresSecond;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
    }

    //生成JWT
    String compact = builder.compact();
    log.info("生成jwt===========" + compact);
    return compact;

}
 
源代码27 项目: mogu_blog_v2   文件: JwtUtil.java
public static String createSysUserJWT(Long shopId, Long sysUserId, String loginUserName, String loginPassWord, boolean isShop) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        //生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Secret);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //添加构成JWT的参数
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .claim("shop_id", shopId)
                .claim("sys_user_id", sysUserId)
                .claim("is_shop", isShop)
                .claim("login_username", loginUserName)
                .claim("login_password", loginPassWord)
//	                .claim("user_open_id", userOpenId)
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (expiresSecond >= 0) {
            long expMillis = nowMillis + expiresSecond;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }

        //生成JWT
        String compact = builder.compact();
        log.info("生成jwt===========" + compact);
        return compact;
    }
 
源代码28 项目: mogu_blog_v2   文件: JwtHelper.java
/**
 * 构建jwt
 *
 * @param userName       账户名
 * @param adminUid       账户id
 * @param roleName       账户拥有角色名
 * @param audience       代表这个Jwt的接受对象
 * @param issuer         代表这个Jwt的签发主题
 * @param TTLMillis      jwt有效时间
 * @param base64Security 加密方式
 * @return
 */
public String createJWT(String userName, String adminUid, String roleName,
                        String audience, String issuer, long TTLMillis, String base64Security) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    //生成签名密钥
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    //添加构成JWT的参数
    JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
            .claim("adminUid", adminUid)
            .claim("role", roleName)
            .claim("creatTime", now)
            .setSubject(userName)
            .setIssuer(issuer)
            .setAudience(audience)
            .signWith(signatureAlgorithm, signingKey);
    //添加Token过期时间
    if (TTLMillis >= 0) {
        long expMillis = nowMillis + TTLMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp).setNotBefore(now);
    }
    //生成JWT
    return builder.compact();
}
 
源代码29 项目: mogu_blog_v2   文件: JwtHelper.java
public String refreshToken(String token, String base64Security, long TTLMillis) {
    String refreshedToken;
    try {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        // 生成签名密钥
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(base64Security);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        final Claims claims = parseJWT(token, base64Security);
        claims.put("creatDate", new Date());
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT")
                .setClaims(claims)
                .setSubject(getUsername(token, base64Security))
                .setIssuer(getIssuer(token, base64Security))
                .setAudience(getAudience(token, base64Security))
                .signWith(signatureAlgorithm, signingKey);
        //添加Token过期时间
        if (TTLMillis >= 0) {
            long expMillis = nowMillis + TTLMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp).setNotBefore(now);
        }
        refreshedToken = builder.compact();
    } catch (Exception e) {
        refreshedToken = null;
    }
    return refreshedToken;
}
 
源代码30 项目: hellokoding-courses   文件: JwtUtil.java
public static String generateToken(String signingKey, String subject) {
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    JwtBuilder builder = Jwts.builder()
            .setSubject(subject)
            .setIssuedAt(now)
            .signWith(SignatureAlgorithm.HS256, signingKey);

    String token = builder.compact();

    RedisUtil.INSTANCE.sadd(REDIS_SET_ACTIVE_SUBJECTS, subject);

    return token;
}
 
 类所在包