io.jsonwebtoken.JwtBuilder#claim ( )源码实例Demo

下面列出了io.jsonwebtoken.JwtBuilder#claim ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: sureness   文件: JsonWebTokenUtil.java
/**
 *   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();
}
 
源代码2 项目: Aooms   文件: LoginContext.java
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;
}
 
源代码3 项目: Alpine   文件: JsonWebToken.java
/**
 * 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();
}
 
/**
 * 签发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();
}
 
源代码5 项目: sso-client   文件: SSOClientTest.java
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;
}
 
源代码6 项目: secrets-proxy   文件: JwtTokenService.java
/**
 * 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();
}
 
源代码7 项目: pulsar   文件: AuthenticationProviderTokenTest.java
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();
}
 
源代码8 项目: react-native-pure-jwt   文件: RNPureJwtModule.java
@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());
}