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

The following examples show how to use io.jsonwebtoken.JwtBuilder#claim() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: AuthenticationProviderTokenTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static String createTokenWithAudience(Key signingKey, String audienceClaim, List<String> audience) {
    JwtBuilder builder = Jwts.builder()
            .setSubject(SUBJECT)
            .signWith(signingKey);

    builder.claim(audienceClaim, audience);
    return builder.compact();
}
 
Example 8
Source File: RNPureJwtModule.java    From react-native-pure-jwt with MIT License 4 votes vote down vote up
@ReactMethod
public void sign(ReadableMap claims, String secret, ReadableMap options, Promise callback) {
    String algorithm = options.hasKey("alg") ? options.getString("alg") : "HS256";
    JwtBuilder constructedToken = Jwts.builder()
            .signWith(SignatureAlgorithm.forName(algorithm), this.toBase64(secret))
            .setHeaderParam("alg", algorithm)
            .setHeaderParam("typ", "JWT");

    Set<Map.Entry<String, Object>> entries = claims.toHashMap().entrySet();

    for (Object entry: entries) {
        Map.Entry item = (Map.Entry) entry;

        String key = (String) item.getKey();
        Object value = item.getValue();

        Double valueAsDouble;

        switch (key) {
            case "alg":
                break;

            case "exp":
                valueAsDouble = (double) value;
                constructedToken.setExpiration(new Date(valueAsDouble.longValue()));
                break;

            case "iat":
                valueAsDouble = (double) value;
                constructedToken.setIssuedAt(new Date(valueAsDouble.longValue()));
                break;

            case "nbf":
                valueAsDouble = (double) value;
                constructedToken.setNotBefore(new Date(valueAsDouble.longValue()));
                break;

            case "aud":
                constructedToken.setAudience(value.toString());
                break;

            case "iss":
                constructedToken.setIssuer(value.toString());
                break;

            case "sub":
                constructedToken.setSubject(value.toString());
                break;

            case "jti":
                constructedToken.setId(value.toString());
                break;
                
            default:
                constructedToken.claim(key, value);
        }
    }

    callback.resolve(constructedToken.compact());
}