Java Code Examples for io.jsonwebtoken.JwtBuilder

The following examples show how to use io.jsonwebtoken.JwtBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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();
}
 
Example 2
@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();
}
 
Example 3
Source Project: pravega   Source File: JsonWebToken.java    License: Apache License 2.0 8 votes vote down vote up
/**
 * 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();
}
 
Example 4
Source Project: ProjectStudy   Source File: JjwtUtil.java    License: MIT License 7 votes vote down vote up
/**
 * 生成签名,获取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();
}
 
Example 5
@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();
}
 
Example 6
@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();
}
 
Example 7
@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();
}
 
Example 8
@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();
}
 
Example 9
Source Project: faster-framework-project   Source File: JwtService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 生成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();
}
 
Example 10
Source Project: samples-android   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 11
@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());
    }
}
 
Example 12
Source Project: my_curd   Source File: JwtUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 生成签名
 *
 * @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();
}
 
Example 13
Source Project: hsweb-framework   Source File: JwtTokenGenerator.java    License: Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 14
Source Project: kisso   Source File: JwtHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <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();
}
 
Example 15
Source Project: github-branch-source-plugin   Source File: JwtHelper.java    License: MIT License 6 votes vote down vote up
/**
 * 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();
}
 
Example 16
Source Project: java-docs-samples   Source File: MqttExample.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example 17
Source Project: java-docs-samples   Source File: MqttExample.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example 18
Source Project: java-docs-samples   Source File: HttpExample.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example 19
Source Project: java-docs-samples   Source File: MqttCommandsDemo.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example 20
Source Project: java-docs-samples   Source File: MqttCommandsDemo.java    License: Apache License 2.0 6 votes vote down vote up
/** 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();
}
 
Example 21
/** 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();
}
 
Example 22
/** 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();
}
 
Example 23
Source Project: jjwt   Source File: DefaultJwtBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 24
Source Project: presto   Source File: JsonWebTokenHandler.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 25
Source Project: sureness   Source File: JsonWebTokenUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *   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();
}
 
Example 26
Source Project: mogu_blog_v2   Source File: JwtUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 生成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;

}
 
Example 27
Source Project: mogu_blog_v2   Source File: JwtUtil.java    License: Apache License 2.0 5 votes vote down vote up
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;
    }
 
Example 28
Source Project: mogu_blog_v2   Source File: JwtHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 构建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();
}
 
Example 29
Source Project: mogu_blog_v2   Source File: JwtHelper.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 30
Source Project: hellokoding-courses   Source File: JwtUtil.java    License: MIT License 5 votes vote down vote up
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;
}