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

The following examples show how to use io.jsonwebtoken.JwtBuilder#setExpiration() . 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: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 8 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 2
Source File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 8 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 3
Source File: JsonWebToken.java    From pravega with 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 File: SecurityServiceImpl.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 7 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: 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 6
Source File: JsonWebTokenService.java    From spring-boot-mongodb-jwt with Apache License 2.0 6 votes vote down vote up
@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 7
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 8
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 9
Source File: JwtTokenGenerator.java    From hsweb-framework with 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 10
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 11
Source File: JwtUtil.java    From xmanager with Apache License 2.0 6 votes vote down vote up
/**
 * 创建jwt
 * @param id
 * @param subject
 * @param ttlMillis
 * @return
 * @throws Exception
 */
public String createJWT(String id, String subject, long ttlMillis) throws Exception {

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    SecretKey key = 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 12
Source File: JwtUtils.java    From zhcc-server with Apache License 2.0 5 votes vote down vote up
/**
 * 创建jwt
 * 
 * @param subject
 * @return
 */
public String createJWT(String subject) {
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
	long nowMillis = System.currentTimeMillis();
	Date now = new Date(nowMillis);
	SecretKey key = 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 13
Source File: SSOClientTest.java    From sso-client with Apache License 2.0 5 votes vote down vote up
protected JwtBuilder jwtBuilder(long exp, Map<String, Object> ext){
    JwtBuilder jwt = Jwts.builder()
            .claim("user_id","43FE6476-CD7B-493B-8044-C7E3149D0876")
            .claim("scope","perm name user")
            .claim("client_id","console")
            .claim("username","admin");
    if(ext != null){
        for (Entry<String, Object> entry : ext.entrySet()){
            jwt.claim(entry.getKey(),entry.getValue());
        }
    }
    jwt.setExpiration(new Date(exp));
    return jwt;
}
 
Example 14
Source File: JsonWebToken.java    From Alpine with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new JWT for the specified principal. Token is signed using
 * the SecretKey with an HMAC 256 algorithm.
 *
 * @param principal the Principal to create the token for
 * @param permissions the effective list of permissions for the principal
 * @param identityProvider the identity provider the principal was authenticated with. If null, it will be derived from principal
 * @return a String representation of the generated token
 * @since 1.8.0
 */
public String createToken(final Principal principal, final List<Permission> permissions, final IdentityProvider identityProvider) {
    final Date today = new Date();
    final JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setSubject(principal.getName());
    jwtBuilder.setIssuer(ISSUER);
    jwtBuilder.setIssuedAt(today);
    jwtBuilder.setExpiration(addDays(today, 7));
    if (permissions != null) {
        jwtBuilder.claim("permissions", permissions.stream()
                .map(Permission::getName)
                .collect(Collectors.joining(","))
        );
    }
    if (identityProvider != null) {
        jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, identityProvider.name());
    } else {
        if (principal instanceof LdapUser) {
            jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.LDAP.name());
        } else if (principal instanceof OidcUser) {
            jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.OPENID_CONNECT.name());
        } else {
            jwtBuilder.claim(IDENTITY_PROVIDER_CLAIM, IdentityProvider.LOCAL.name());
        }
    }
    return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).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: 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 17
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 18
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 19
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 20
Source File: JWTUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 3 votes vote down vote up
/**
 * createJWT: 创建jwt<br/>
 *
 * @author guooo
 * @param id
 *            唯一id,uuid即可
 * @param subject
 *            json形式字符串或字符串,增加用户非敏感信息存储,如user tid,与token解析后进行对比,防止乱用
 * @param ttlMillis
 *            有效期
 * @param stringKey
 * @return jwt token
 * @throws Exception
 * @since JDK 1.6
 */
public static String createJWT(String id, String subject, long ttlMillis) throws Exception {
	SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
	long nowMillis = System.currentTimeMillis();
	Key key = generalKey(signatureAlgorithm);
	JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject)
			.signWith(signatureAlgorithm, key);
	if (ttlMillis >= 0) {
		long expMillis = nowMillis + ttlMillis;
		Date exp = new Date(expMillis);
		builder.setExpiration(exp);
	}
	return builder.compact();
}