Java Code Examples for com.nimbusds.jwt.JWTClaimsSet#Builder

The following examples show how to use com.nimbusds.jwt.JWTClaimsSet#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: ScooldUtils.java    From scoold with Apache License 2.0 7 votes vote down vote up
public SignedJWT generateJWToken(Map<String, Object> claims, long validitySeconds) {
	String secret = Config.getConfigParam("app_secret_key", "");
	if (!StringUtils.isBlank(secret)) {
		try {
			Date now = new Date();
			JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
			claimsSet.issueTime(now);
			if (validitySeconds > 0) {
				claimsSet.expirationTime(new Date(now.getTime() + (validitySeconds * 1000)));
			}
			claimsSet.notBeforeTime(now);
			claimsSet.claim(Config._APPID, Config.getConfigParam("access_key", "x"));
			claims.entrySet().forEach((claim) -> claimsSet.claim(claim.getKey(), claim.getValue()));
			JWSSigner signer = new MACSigner(secret);
			SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
			signedJWT.sign(signer);
			return signedJWT;
		} catch (JOSEException e) {
			logger.warn("Unable to sign JWT: {}.", e.getMessage());
		}
	}
	logger.error("Failed to generate JWT token - app_secret_key is blank.");
	return null;
}
 
Example 2
Source File: JWTToken.java    From knox with Apache License 2.0 6 votes vote down vote up
public JWTToken(String alg, String[] claimsArray, List<String> audiences) {
  JWSHeader header = new JWSHeader(new JWSAlgorithm(alg));

  if (claimsArray[2] != null) {
    if (audiences == null) {
      audiences = new ArrayList<>();
    }
    audiences.add(claimsArray[2]);
  }
  JWTClaimsSet claims;
  JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
  .issuer(claimsArray[0])
  .subject(claimsArray[1])
  .audience(audiences);
  if(claimsArray[3] != null) {
    builder = builder.expirationTime(new Date(Long.parseLong(claimsArray[3])));
  }

  // Add a private UUID claim for uniqueness
  builder.claim(KNOX_ID_CLAIM, String.valueOf(UUID.randomUUID()));

  claims = builder.build();

  jwt = new SignedJWT(header, claims);
}
 
Example 3
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 6 votes vote down vote up
/**
 * Encrypt id token.
 *
 * @param client   the client
 * @param idClaims the id claims
 */
private JWT encryptIdToken(final ClientDetailsEntity client, final JWTClaimsSet.Builder idClaims) {
    log.debug("Locating encrypter service for client {}", client.getClientId());
    final JWTEncryptionAndDecryptionService encrypter = encrypters.getEncrypter(client);

    if (encrypter == null) {
        log.error("Couldn't find encrypter for client: {} ", client.getClientId());
        return null;
    }
    log.debug("Found encrypter service for client {}.", client.getClientId());
    final JWTClaimsSet claims = idClaims.build();
    final EncryptedJWT idToken = new EncryptedJWT(new JWEHeader(client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc()), claims);

    log.debug("Encrypting idToken with response alg {} and response encoding {} and claims {}",
            client.getIdTokenEncryptedResponseAlg(),
            client.getIdTokenEncryptedResponseEnc(), claims.getClaims().keySet());
    encrypter.encryptJwt(idToken);
    return idToken;
}
 
Example 4
Source File: DefaultJWTTransformer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public JWTClaimsSet transform(JWTClaimsSet jwtClaimsSet) {

    JWTClaimsSet.Builder transformedJWT = new JWTClaimsSet.Builder();
    if (tokenIssuer != null) {
        Map<String, ClaimMappingDto> claimConfigurations = tokenIssuer.getClaimConfigurations();
        for (Map.Entry<String, Object> claimEntry : jwtClaimsSet.getClaims().entrySet()) {
            ClaimMappingDto claimMappingDto = claimConfigurations.get(claimEntry.getKey());
            String claimKey = claimEntry.getKey();
            if (claimMappingDto != null) {
                claimKey = claimMappingDto.getLocalClaim();
            }
            transformedJWT.claim(claimKey, claimEntry.getValue());
        }
        return transformedJWT.build();
    }
    return jwtClaimsSet;

}
 
Example 5
Source File: UserRepository.java    From shiro-jwt with MIT License 6 votes vote down vote up
default String createToken(Object userId) {
    try {
        JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

        builder.issuer(getIssuer());
        builder.subject(userId.toString());
        builder.issueTime(new Date());
        builder.notBeforeTime(new Date());
        builder.expirationTime(new Date(new Date().getTime() + getExpirationDate()));
        builder.jwtID(UUID.randomUUID().toString());

        JWTClaimsSet claimsSet = builder.build();
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

        Payload payload = new Payload(claimsSet.toJSONObject());

        JWSObject jwsObject = new JWSObject(header, payload);

        JWSSigner signer = new MACSigner(getSharedKey());
        jwsObject.sign(signer);
        return jwsObject.serialize();
    } catch (JOSEException ex) {
        return null;
    }
}
 
Example 6
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 6 votes vote down vote up
/**
 * Calculate amr and acr claims.
 *
 * @param accessToken the access token
 * @param idClaims    the id claims
 */
private void calculateAmrAndAcrClaims(final OAuth2AccessTokenEntity accessToken,
                                      final JWTClaimsSet.Builder idClaims) {
    final OAuth2Authentication authN = accessToken.getAuthenticationHolder().getAuthentication();
    final Collection<GrantedAuthority> authorities = authN.getAuthorities();
    for (final GrantedAuthority authority : authorities) {
        log.debug("Evaluating authority {} of the authentication", authority);
        final AuthenticationClassRefAuthority acr =
                AuthenticationClassRefAuthority.getAuthenticationClassRefAuthority(authority);
        if (acr != null) {
            idClaims.claim(OIDCConstants.ACR, acr.getAuthority());
            log.debug("Added {} claim as {}", OIDCConstants.ACR, acr.getAuthority());
        }
        final AuthenticationMethodRefAuthority amr =
                AuthenticationMethodRefAuthority.getAuthenticationClassRefAuthority(authority);
        if (amr != null) {
            idClaims.claim(OIDCConstants.AMR, amr.getAuthority());
            log.debug("Added {} claim as {}", OIDCConstants.AMR, amr.getAuthority());
        }
    }
}
 
Example 7
Source File: JwtGenerator.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a basic set of claims
 *
 * @return a basic set of claims
 */
public JWTClaimsSet.Builder getBasicClaimSet() {
	return new JWTClaimsSet.Builder()
			.issueTime(new Date())
			.expirationTime(JwtGenerator.NO_EXPIRE_DATE)
			.claim(TokenClaims.CLAIM_CLIENT_ID, clientId)
			.claim(TokenClaims.CLAIM_ORIGIN, "userIdp")
			.claim(TokenClaims.CLAIM_USER_NAME, userName)
			.claim(TokenClaims.CLAIM_EMAIL, userName + "@test.org")
			.claim(TokenClaims.CLAIM_ZDN, subdomain)
			.claim(TokenClaims.CLAIM_ZONE_ID, identityZoneId)
			.claim(TokenClaims.CLAIM_EXTERNAL_ATTR, new ExternalAttrClaim())
			.claim(TokenClaims.CLAIM_GRANT_TYPE, GRANT_TYPE);
}
 
Example 8
Source File: JwtGenerator.java    From cloud-security-xsuaa-integration with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a basic Jwt with the given clientId, userName, scopes, user attributes
 * claims and the keyId header.
 *
 * @return jwt
 */
public Jwt getToken() {
	JWTClaimsSet.Builder claimsSetBuilder = getBasicClaimSet();

	if (scopes != null && scopes.length > 0) {
		claimsSetBuilder.claim(TokenClaims.CLAIM_SCOPES, scopes);
		if (deriveAudiences) {
			claimsSetBuilder.audience(deriveAudiencesFromScopes(scopes));
		}
	}
	if (attributes.size() > 0) {
		claimsSetBuilder.claim(TokenClaims.CLAIM_XS_USER_ATTRIBUTES, attributes);
	}
	for (Map.Entry<String, Object> customClaim : customClaims.entrySet()) {
		claimsSetBuilder.claim(customClaim.getKey(), customClaim.getValue());
	}
	return createFromClaims(claimsSetBuilder.build().toString(), getHeaderMap(jwtHeaderKeyId, getOrCreateJku()));
}
 
Example 9
Source File: TokenGenerator.java    From cruise-control with BSD 2-Clause "Simplified" License 5 votes vote down vote up
static TokenAndKeys generateToken(String subject, List<String> audience, long expirationTime) throws JOSEException {
  RSAKey rsaJwk = new RSAKeyGenerator(2048)
      .keyID("123")
      .generate();
  RSAKey rsaPublicJWK = rsaJwk.toPublicJWK();
  RSASSASigner signer = new RSASSASigner(rsaJwk);

  JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
      .type(JOSEObjectType.JWT)
      .build();
  JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder()
      .subject(subject)
      .issuer("https://linkedin.com");

  if (audience != null) {
    claimsSet.audience(audience);
  }

  if (expirationTime > 0) {
    claimsSet.expirationTime(new Date(expirationTime));
  } else {
    claimsSet.expirationTime(Date.from(Instant.now().plusSeconds(120)));
  }

  SignedJWT signedJWT = new SignedJWT(header, claimsSet.build());
  signedJWT.sign(signer);

  return new TokenAndKeys(signedJWT.serialize(), (RSAPrivateKey) signer.getPrivateKey(), rsaPublicJWK.toRSAPublicKey());
}
 
Example 10
Source File: JwtGeneratorTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 5 votes vote down vote up
@Test
public void testTokenWithCustomClaimsAndHeaders() {
	JwtGenerator jwtGenerator = new JwtGenerator("clientId", "subdomain", "tenantId");
	JWTClaimsSet.Builder builder = jwtGenerator.getBasicClaimSet();
	builder.claim(TokenClaims.CLAIM_USER_NAME, "new_testuser");

	Map<String, String> map = jwtGenerator.getBasicHeaders();

	Jwt jwt = JwtGenerator.createFromClaims(builder.build(), map);

	assertThat(jwt.getHeaders(), hasEntry(TokenHeaders.JKU, "http://localhost:33195/subdomain/token_keys"));
	assertThat(jwt.getHeaders(), hasEntry(TokenHeaders.KID, "legacy-token-key"));
	assertThat(jwt.getClaims(), hasEntry(TokenClaims.CLAIM_USER_NAME, "new_testuser"));
}
 
Example 11
Source File: MobiTokenVerifier.java    From mobi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a JWT Token String for the user with the provided username using the Mobi token key and the provided
 * issuer, scope, tokenDuration, and additional claims.
 *
 * @param username The sub of the token
 * @param issuer The issuer of the token
 * @param scope The scope of the token
 * @param tokenDuration The duration for the new token
 * @param claims An optional map of custom claims to add to the token
 * @return The String representing the encoded and compact JWT Token
 * @throws JOSEException if there is a problem creating the token
 */
SignedJWT generateToken(String username, String issuer, String scope, long tokenDuration,
                        @Nullable Map<String, Object> claims) throws JOSEException {
    // Create HMAC signer
    JWSSigner signer = new MACSigner(padKey(KEY));

    Date now = new Date();
    Date expirationDate = new Date(now.getTime() + tokenDuration);

    // Prepare JWT Builder with claims set
    JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder()
            .subject(username)
            .issuer(issuer)
            .expirationTime(expirationDate)
            .claim("scope", scope);

    if (claims != null) {
        claims.forEach(builder::claim);
    }

    SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), builder.build());

    // Apply the HMAC protection
    signedJWT.sign(signer);

    return signedJWT;
}
 
Example 12
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 5 votes vote down vote up
private JWTClaimsSet getJWTClaimsSet(String issuer, String subject, Date issueTime, Date notBeforeTime, Date expirationTime) {
    JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();
    builder.issuer(issuer);
    builder.subject(subject);
    builder.issueTime(issueTime);
    builder.notBeforeTime(notBeforeTime);
    builder.expirationTime(expirationTime);
    builder.jwtID(UUID.randomUUID().toString());
    return builder.build();
}
 
Example 13
Source File: InsuranceAgentJWTClaimsSetGenerator.java    From micronaut-microservices-poc with Apache License 2.0 5 votes vote down vote up
@Override
protected void populateWithUserDetails(JWTClaimsSet.Builder builder, UserDetails userDetails) {
    super.populateWithUserDetails(builder, userDetails);
    if (userDetails instanceof InsuranceAgentDetails) {
        builder.claim("avatar", ((InsuranceAgentDetails) userDetails).getAvatarUrl());
    }
}
 
Example 14
Source File: STSJWTBuilder.java    From cellery-security with Apache License 2.0 5 votes vote down vote up
private void addMandatoryClaims(JWTClaimsSet.Builder claimsSet) {

        Date issuedAt = new Date(System.currentTimeMillis());
        Date expiryTime = new Date(issuedAt.getTime() + expiryInSeconds * 1000);

        List<String> audience = getAudience(this.audience);

        claimsSet.jwtID(UUID.randomUUID().toString())
                .issuer(getIssuer())
                .issueTime(issuedAt)
                .expirationTime(expiryTime)
                .audience(audience)
                .claim(KEY_TYPE_CLAIM, PRODUCTION_KEY_TYPE);
    }
 
Example 15
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate at hash claim.
 *
 * @param accessToken   the access token
 * @param signingAlg    the signing alg
 * @param idClaims      the id claims
 * @param responseTypes the response types
 */
private void calculateAtHashClaim(final OAuth2AccessTokenEntity accessToken,
                                  final JWSAlgorithm signingAlg, final JWTClaimsSet.Builder idClaims,
                                  final Set<String> responseTypes) {
    if (responseTypes.contains(OIDCConstants.TOKEN)) {
        // calculate the token hash
        final Base64URL atHash = IdTokenHashUtils.getAccessTokenHash(signingAlg, accessToken);
        idClaims.claim(OIDCConstants.AT_HASH, atHash);

        log.debug("{} is set to {}", OIDCConstants.AT_HASH, atHash);
    }
}
 
Example 16
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate nonce claim.
 *
 * @param request  the request
 * @param idClaims the id claims
 */
private void calculateNonceClaim(final OAuth2Request request, final JWTClaimsSet.Builder idClaims) {
    final String nonce = (String) request.getExtensions().get(ConnectRequestParameters.NONCE);
    if (!Strings.isNullOrEmpty(nonce)) {
        idClaims.claim(ConnectRequestParameters.NONCE, nonce);
        log.debug("{} is set to {}", ConnectRequestParameters.NONCE, nonce);
    }
}
 
Example 17
Source File: SecurityUtils.java    From para with Apache License 2.0 5 votes vote down vote up
/**
 * Generates a new JWT token.
 * @param user a User object belonging to the app
 * @param app the app object
 * @return a new JWT or null
 */
public static SignedJWT generateJWToken(User user, App app) {
	if (app != null) {
		try {
			Date now = new Date();
			JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
			String userSecret = "";
			claimsSet.issueTime(now);
			claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
			claimsSet.notBeforeTime(now);
			claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
			claimsSet.claim(Config._APPID, app.getId());
			if (user != null) {
				claimsSet.subject(user.getId());
				claimsSet.claim("idp", user.getIdentityProvider());
				userSecret = user.getTokenSecret();
			}
			JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
			SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
			signedJWT.sign(signer);
			return signedJWT;
		} catch (JOSEException e) {
			logger.warn("Unable to sign JWT: {}.", e.getMessage());
		}
	}
	return null;
}
 
Example 18
Source File: ShibbolethAcrAwareTokenService.java    From shibboleth-oidc with Apache License 2.0 5 votes vote down vote up
/**
 * Calculate expiration claim.
 *
 * @param client   the client
 * @param idClaims the id claims
 */
private void calculateExpirationClaim(final ClientDetailsEntity client,
                                      final JWTClaimsSet.Builder idClaims) {
    if (client.getIdTokenValiditySeconds() != null) {
        final long exp = client.getIdTokenValiditySeconds() * 1000L;
        final Date expiration = new Date(System.currentTimeMillis() + exp);
        idClaims.expirationTime(expiration);
        log.debug("Claim expiration is set to {}", expiration);
    }
}
 
Example 19
Source File: XsuaaTokenTest.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
private XsuaaToken createToken(JWTClaimsSet.Builder claimsBuilder) {
	Jwt jwt = JwtGenerator.createFromClaims(claimsBuilder.build());
	return new XsuaaToken(jwt);
}
 
Example 20
Source File: SecurityManager.java    From snowflake-ingest-java with Apache License 2.0 4 votes vote down vote up
/**
 * regenerateToken - Regenerates our Token given our current user,
 *                    account and keypair
 */
private void regenerateToken()
{
  //create our JWT claim builder object
  JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder();

  //set the subject to the fully qualified username
  String subject = String.format("%s.%s", account, user);
  LOGGER.info("Creating Token with subject {}", subject);

  //set the issuer
  String publicKeyFPInJwt = calculatePublicKeyFp(keyPair);
  String issuer = String.format("%s.%s.%s", account, user, publicKeyFPInJwt);
  LOGGER.info("Creating Token with issuer {}", issuer);

  // iat set to now
  Date iat = new Date(System.currentTimeMillis());

  // expiration in 59 minutes
  Date exp = new Date(iat.getTime() + 59 * 60 * 1000);

  // build claim set
  JWTClaimsSet claimsSet = builder.issuer(issuer)
      .subject(subject)
      .issueTime(iat)
      .expirationTime(exp)
      .build();

  SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256),
                                      claimsSet);

  JWSSigner signer = new RSASSASigner(this.keyPair.getPrivate());

  String newToken;
  try
  {
    signedJWT.sign(signer);
    newToken = signedJWT.serialize();
  }
  catch (JOSEException e)
  {
    regenFailed.set(true);
    LOGGER.error("Failed to regenerate token! Exception is as follows : {}",
                 e.getMessage());
    throw new SecurityException();
  }

  //atomically update the string
  LOGGER.info("Created new JWT");
  token.set(newToken);
}