Java Code Examples for io.jsonwebtoken.JwtBuilder#compact()

The following examples show how to use io.jsonwebtoken.JwtBuilder#compact() . 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
Source File: JjwtUtil.java    From ProjectStudy with 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 2
Source File: JwtService.java    From faster-framework-project with 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 3
Source File: JwtHelper.java    From github-branch-source-plugin with 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 4
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 6 votes vote down vote up
@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 5
Source File: SSOClientTest.java    From sso-client with Apache License 2.0 6 votes vote down vote up
@Before
public void before(){
    String pk = org.apache.commons.codec.binary.Base64.encodeBase64String(keyPair.getPublic().getEncoded());

    stubFor(get("/oauth2/publickey").willReturn(aResponse().withStatus(200).withBody(pk)));
    
    JwtBuilder builder = jwtBuilder(System.currentTimeMillis()+3600*1000L)
            .signWith(SignatureAlgorithm.RS256,keyPair.getPrivate());
    jwtToken = builder.compact();

    SSOConfig config = new SSOConfig().autoConfigureUrls(baseUrl);
    config.setClientId("test");
    config.setClientSecret("test_secret");
    config.setResourceName("resourceName");
    config.setRedirectUri("http://www.example.com");
    client = new SSOClient(config);

    basicHeader = SSOUtils.encodeBasicAuthorizationHeader(config.getClientId(),config.getClientSecret());
}
 
Example 6
Source File: JwtUtils.java    From my_curd with 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 7
Source File: JwtUtil.java    From mogu_blog_v2 with 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 8
Source File: JwtUtil.java    From hellokoding-courses with 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;
}
 
Example 9
Source File: KeyUtil.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
/**
 * 生成Token令牌
 *
 * @param name String
 * @return String
 */
public static String generateToken(String name) {
    JwtBuilder builder = Jwts.builder()
            .setId(name)
            .setIssuedAt(new Date())
            .setExpiration(Dc3Util.expireTime(6, Calendar.HOUR))
            .signWith(SignatureAlgorithm.HS256, Common.KEY);
    return builder.compact();
}
 
Example 10
Source File: JwtUtils.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 创建jwt
 * 
 * @param subject
 * @param secret
 * @param ttlMillis
 * @return
 */
public static String createJWT(String subject, String secret, long ttlMillis) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = generalKey(secret);
    JwtBuilder builder = Jwts.builder().setId("jwt").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 11
Source File: SimpleJwtTokenService.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	public JwtTokenInfo generateToken(JwtUserDetail userDetail){
		if(userDetail==null){
			return null;
		}
		LocalDateTime issuteAt = LocalDateTime.now();
		Date expirationDate = Dates.toDate(issuteAt.plusSeconds(getExpirationInSeconds().intValue()));
		JwtBuilder builder = Jwts.builder()
							.setSubject(userDetail.getUserName())
							.setIssuer(jwtConfig.getIssuer())
							.setAudience(jwtConfig.getAudience())
//							.setId(jti)
							.claim(JwtSecurityUtils.CLAIM_USER_ID, userDetail.getUserId())
//							.claim(JwtUtils.CLAIM_AUTHORITIES, getAuthorities(userDetail))
							.setIssuedAt(Dates.toDate(issuteAt))
							.setExpiration(expirationDate)
							.signWith(SignatureAlgorithm.HS512, jwtConfig.getSigningKey());
		
		if(userDetail.getProperties()!=null){
			userDetail.getProperties().forEach((k,v)->builder.claim(getPropertyKey(k), v));
		}
		
		String token = builder.compact();
		
		return JwtTokenInfo.builder()
							.token(token)
							.build();
	}
 
Example 12
Source File: JWTUtil.java    From NutzSite with Apache License 2.0 5 votes vote down vote up
/**
 * 创建token
 * @param id
 * @return
 */
public static String createJWT(String id) {
    //过期时间不要太长 移动端需要长时间记住用户名 让移动端本地存储 用户名 密码即可
    Date exp = DateUtils.addDays(new Date(),1) ;
    //Let's set the JWT Claims
    JwtBuilder builder = Jwts.builder().setId(id)
            .setIssuedAt(new Date())
            .setSubject(id)
            .setIssuer(issuer)
            .signWith(key);
    builder.setExpiration(exp);
    //Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();
}
 
Example 13
Source File: JwtUtils.java    From withme3.0 with MIT License 5 votes vote down vote up
public static String createJWT(String authUser) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(CONSTANT.SECRET_KEY);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    JwtBuilder builder = Jwts.builder()
            .setHeaderParam("typ", "jwt")
            .setHeaderParam("alg", "HS256")
            .setPayload(authUser)
            .signWith(signatureAlgorithm, signingKey);
    return builder.compact();
}
 
Example 14
Source File: JwtTokenService.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Generate a JWT token for the given user. The roles will be stored as a claim in JWT token as a
 * comma separated string.
 *
 * @param user authenticated user details object.
 * @return compact JWS (JSON Web Signature)
 */
public @Nonnull String generateToken(OneOpsUser user) {
  Instant now = Instant.now();
  Instant expiresIn = now.plusSeconds(expiresInSec);

  JwtBuilder jwt =
      Jwts.builder()
          .setSubject(user.getUsername())
          .setIssuer(issuer)
          .setIssuedAt(Date.from(now))
          .setExpiration(Date.from(expiresIn))
          .signWith(SIGNATURE_ALGORITHM, String.valueOf(secretKey));
  if (user.getAuthorities() != null) {
    List<String> roles =
        user.getAuthorities()
            .stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList());
    jwt.claim(ROLE_CLAIM, String.join(",", roles));
  }
  if (user.getDomain() != null) {
    jwt.claim(DOMAIN_CLAIM, user.getDomain().getType());
  }
  if (user.getCn() != null) {
    jwt.claim(CN_CLAIM, user.getCn());
  }
  if (compressionEnabled) {
    jwt.compressWith(CompressionCodecs.DEFLATE);
  }
  return jwt.compact();
}
 
Example 15
Source File: JwtUtils.java    From leo-im-server with Apache License 2.0 5 votes vote down vote up
/**
 * 创建jwt
 * 
 * @param subject
 * @param secret
 * @param ttlMillis
 * @return
 */
public static String createJWT(String subject, String secret, long ttlMillis) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = generalKey(secret);
    JwtBuilder builder = Jwts.builder().setId("jwt").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 16
Source File: TokenUtils.java    From XUpdateService with Apache License 2.0 5 votes vote down vote up
/**
 * 生成Token
 *
 * @param id        编号
 * @param issuer    该JWT的签发者,是否使用是可选的
 * @param subject   该JWT所面向的用户,是否使用是可选的;
 * @param ttlMillis 签发时间 (有效时间,过期会报错)
 * @return token String
 */
public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {

    // 签名算法 ,将对token进行签名
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

    // 生成签发时间
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);

    // 通过秘钥签名JWT
    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

    // Let's set the JWT Claims
    JwtBuilder builder = Jwts.builder().setId(id)
            .setIssuedAt(now)
            .setSubject(subject)
            .setIssuer(issuer)
            .signWith(signatureAlgorithm, signingKey);

    // if it has been specified, let's add the expiration
    if (ttlMillis >= 0) {
        long expMillis = nowMillis + ttlMillis;
        Date exp = new Date(expMillis);
        builder.setExpiration(exp);
    }

    // Builds the JWT and serializes it to a compact, URL-safe string
    return builder.compact();

}
 
Example 17
Source File: JsonWebTokenUtil.java    From sureness with 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 18
Source File: JsonWebTokenHandler.java    From presto with 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 19
Source File: JWTPolicyTest.java    From apiman-plugins with Apache License 2.0 4 votes vote down vote up
private String unsignedNotYetValidToken() throws Exception {
    Instant instant = LocalDateTime.now().plusDays(5).toInstant(ZoneOffset.UTC);
    Date nbf = Date.from(instant);
    JwtBuilder jwts = Jwts.builder().setSubject("france frichot").setNotBefore(nbf);
    return jwts.compact();
}
 
Example 20
Source File: JWTPolicyTest.java    From apiman-plugins with Apache License 2.0 4 votes vote down vote up
private String unsignedToken() throws Exception {
     JwtBuilder jwts = Jwts.builder().setSubject("france frichot");
     return jwts.compact();
}