Java Code Examples for io.jsonwebtoken.Jwts#builder()

The following examples show how to use io.jsonwebtoken.Jwts#builder() . 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: Utils.java    From samples-android with 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 2
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 3
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 4
Source File: LoginContext.java    From Aooms with Apache License 2.0 5 votes vote down vote up
public AuthenticationInfo login(String username, String password){
    AuthenticationInfo authenticationInfo = loginService.login(username,password);

    //boolean success = true;
    if(authenticationInfo == null){
        // 返回一个Ghost用户
        //authenticationInfo = new AuthenticationInfo().ghost();
        //success = false;
        return null;
    }


    JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setClaims(new DefaultClaims());
    jwtBuilder.claim(SSOAuthentication.CACHE_GROUP_PLACEHOLDER, cacheGroup);
    jwtBuilder.claim(SSOAuthentication.CACHE_TIMEOUT_PLACEHOLDER, timeout);
    SSOToken token = SSOToken.create(jwtBuilder)
            .setId(authenticationInfo.getSessionId())
            .setIssuer(Aooms.NAME)
            .setOrigin(TokenOrigin.HTML5)
            .setTime(System.currentTimeMillis());
    authenticationInfo.setToken(token.getToken());

    // 缓存
    cache(authenticationInfo);
    return authenticationInfo;
}
 
Example 5
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 6
Source File: ShiroUtils.java    From jsets-shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 签发JWT
 * 
 * @param subject
 *            用户名称
 * @param issuer
 *            签发人
 * @param period
 *            有效时间
 * @param roles
 *            访问主张-角色
 * @param permissions
 *            访问主张-资源
 * @param algorithm
 *            算法
 * @return JSON WEB TOKEN
 */
public static String issueJwt(String subject, String issuer, Long period, String roles, String permissions,
		SignatureAlgorithm algorithm) {
	// 当前时间戳(精确到毫秒)
	long currentTimeMillis = System.currentTimeMillis();
	// 秘钥
	byte[] secretKeyBytes = DatatypeConverter.parseBase64Binary(properties().getJwtSecretKey());
	JwtBuilder jwt = Jwts.builder();
	jwt.setId(UUID.randomUUID().toString());
	// 用户名
	jwt.setSubject(subject);
	// 签发者
	if (null != issuer && !"".equals(issuer))
		jwt.setIssuer(issuer);
	// 签发时间
	jwt.setIssuedAt(new Date(currentTimeMillis));
	// 有效时间
	if (null != period) {
		Date expiration = new Date(currentTimeMillis + period);
		jwt.setExpiration(expiration);
	}
	// 访问主张-角色
	if (null != roles && !"".equals(roles))
		jwt.claim("roles", roles);
	// 访问主张-权限
	if (null != permissions && !"".equals(permissions))
		jwt.claim("perms", permissions);
	jwt.compressWith(CompressionCodecs.DEFLATE);
	jwt.signWith(algorithm, secretKeyBytes);
	return jwt.compact();
}
 
Example 7
Source File: SSOToken.java    From kisso with Apache License 2.0 5 votes vote down vote up
@Override
public String getToken() {
    if (null == this.jwtBuilder) {
        this.jwtBuilder = Jwts.builder();
    }
    if (null != this.getId()) {
        this.jwtBuilder.setId(this.getId());
    }
    if (null != this.getTenantId()) {
        this.jwtBuilder.claim(SSOConstants.TOKEN_TENANT_ID, this.getTenantId());
    }
    if (null != this.getIp()) {
        this.jwtBuilder.claim(SSOConstants.TOKEN_USER_IP, this.getIp());
    }
    if (null != this.getIssuer()) {
        this.jwtBuilder.setIssuer(this.getIssuer());
    }
    if (null != this.getUserAgent()) {
        this.jwtBuilder.claim(SSOConstants.TOKEN_USER_AGENT, this.getUserAgent());
    }
    if (null != this.getClaims()) {
        this.jwtBuilder.setClaims(this.getClaims());
    }
    if (TokenFlag.NORMAL != this.getFlag()) {
        this.jwtBuilder.claim(SSOConstants.TOKEN_FLAG, this.getFlag().value());
    }
    if (TokenOrigin.COOKIE != this.getOrigin()) {
        this.jwtBuilder.claim(SSOConstants.TOKEN_ORIGIN, this.getOrigin().value());
    }
    this.jwtBuilder.setIssuedAt(new Date(time));
    return JwtHelper.signCompact(jwtBuilder);
}
 
Example 8
Source File: DynamicJWTController.java    From tutorials with MIT License 4 votes vote down vote up
@RequestMapping(value = "/dynamic-builder-specific", method = POST)
public JwtResponse dynamicBuilderSpecific(@RequestBody Map<String, Object> claims) throws UnsupportedEncodingException {
    JwtBuilder builder = Jwts.builder();

    claims.forEach((key, value) -> {
        switch (key) {
        case "iss":
            ensureType(key, value, String.class);
            builder.setIssuer((String) value);
            break;
        case "sub":
            ensureType(key, value, String.class);
            builder.setSubject((String) value);
            break;
        case "aud":
            ensureType(key, value, String.class);
            builder.setAudience((String) value);
            break;
        case "exp":
            ensureType(key, value, Long.class);
            builder.setExpiration(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
            break;
        case "nbf":
            ensureType(key, value, Long.class);
            builder.setNotBefore(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
            break;
        case "iat":
            ensureType(key, value, Long.class);
            builder.setIssuedAt(Date.from(Instant.ofEpochSecond(Long.parseLong(value.toString()))));
            break;
        case "jti":
            ensureType(key, value, String.class);
            builder.setId((String) value);
            break;
        default:
            builder.claim(key, value);
        }
    });

    builder.signWith(SignatureAlgorithm.HS256, secretService.getHS256SecretBytes());

    return new JwtResponse(builder.compact());
}
 
Example 9
Source File: JsonWebToken.java    From Alpine with Apache License 2.0 2 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 claims a Map of all claims
 * @return a String representation of the generated token
 * @since 1.0.0
 */
public String createToken(final Map<String, Object> claims) {
    final JwtBuilder jwtBuilder = Jwts.builder();
    jwtBuilder.setClaims(claims);
    return jwtBuilder.signWith(SignatureAlgorithm.HS256, key).compact();
}