com.nimbusds.jwt.JWTClaimsSet Java Examples

The following examples show how to use com.nimbusds.jwt.JWTClaimsSet. 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: CelleryCellStsService.java    From cellery-security with Apache License 2.0 7 votes vote down vote up
protected JWTClaimsSet handleRequestToMicroGW(CellStsRequest cellStsRequest, String requestId, String jwt) throws
        CelleryCellSTSException {

    JWTClaimsSet jwtClaims;
    log.debug("Incoming request to cell gateway {} from {}", CellStsUtils.getMyCellName(),
            cellStsRequest.getSource());
    try {
        log.debug("Validating incoming JWT {}", jwt);
        validateInboundToken(cellStsRequest, jwt);
        userContextStore.put(requestId, jwt);
        jwtClaims = extractUserClaimsFromJwt(jwt);

    } catch (TokenValidationFailureException e) {
        throw new CelleryCellSTSException("Error while validating JWT token", e);
    }
    return jwtClaims;
}
 
Example #2
Source File: CellerySignedJWTBuilder.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
public String build() throws CelleryAuthException {

        // Build the JWT Header
        try {
            JWSHeader jwsHeader = buildJWSHeader();
            // Add mandatory claims
            addMandatoryClaims(claimSetBuilder);
            JWTClaimsSet claimsSet = this.claimSetBuilder.build();

            SignedJWT signedJWT = new SignedJWT(jwsHeader, claimsSet);
            JWSSigner signer = new RSASSASigner(getRSASigningKey());

            signedJWT.sign(signer);
            return signedJWT.serialize();
        } catch (IdentityOAuth2Exception | JOSEException e) {
            throw new CelleryAuthException("Error while generating the signed JWT.", e);
        }
    }
 
Example #3
Source File: CelleryCellInterceptorService.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private boolean isCompositeSource(CheckRequest checkRequest, String destinationWorkload) {

        Map requestHeaders = checkRequest.getAttributes().getRequest().getHttp().getHeaders();
        String token = CellStsUtils.extractJwtFromAuthzHeader
                (CellStsUtils.getAuthorizationHeaderValue(requestHeaders));
        if (StringUtils.isEmpty(token)) {
            log.debug("No token received. Hence source shouldn't be a composite.");
            return false;
        }
        try {
            JWTClaimsSet jwtClaims = STSTokenGenerator.getJWTClaims(token);
            String destination = jwtClaims.getStringClaim(Constants.DESTINATION);
            String issuerCell = jwtClaims.getStringClaim(Constants.CELL_INSTANCE_NAME);
            if (destinationWorkload.equalsIgnoreCase(destination) &&
                    Constants.COMPOSITE_CELL_NAME.equalsIgnoreCase(issuerCell)) {
                log.debug("Source is a composite");
                return true;
            }

        } catch (CelleryCellSTSException | ParseException e) {
            // This is harmless since there can be cases where tokens are not attached to reqeust.
            log.debug("Couldn't derive source from token");
        }
        log.debug("Source is not a composite.");
        return false;
    }
 
Example #4
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidSignature_OKP() throws JOSEException{
    //Generate OKP key
    OctetKeyPair okp = new OctetKeyPairGenerator(Curve.Ed25519).generate();
    OKPKey key = new OKPKey();
    key.setKty("OKP");
    key.setKid(KID);
    key.setCrv(okp.getCurve().getStdName());
    key.setX(okp.getX().toString());

    //Sign JWT with Edward Curve algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.EdDSA).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new Ed25519Signer(okp));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #5
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public String asToken(final String claims) throws Exception {
    try {
        final JWSHeader header = new JWSHeader.Builder(new JWSAlgorithm("RS"+hashSize, Requirement.OPTIONAL))
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(privateKey));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #6
Source File: CelleryCellStsService.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private JWTClaimsSet handleInternalRequest(CellStsRequest cellStsRequest, String requestId, String jwt) throws
        CelleryCellSTSException {

    JWTClaimsSet jwtClaims;
    log.debug("Call from a workload to workload within cell {} ; Source workload {} ; Destination workload {}",
            cellStsRequest.getSource().getCellInstanceName(), cellStsRequest.getSource().getWorkload(),
            cellStsRequest.getDestination().getWorkload());

    try {
        if (localContextStore.get(requestId) == null) {
            log.debug("Initial entrace to cell from gateway. No cached token found.");
            validateInboundToken(cellStsRequest, jwt);
            localContextStore.put(requestId, jwt);
        } else {
            if (!StringUtils.equalsIgnoreCase(localContextStore.get(requestId), jwt)) {
                throw new CelleryCellSTSException("Intra cell STS token is tampered.");
            }
        }
        jwtClaims = extractUserClaimsFromJwt(jwt);
    } catch (TokenValidationFailureException e) {
        throw new CelleryCellSTSException("Error while validating locally issued token.", e);
    }
    return jwtClaims;
}
 
Example #7
Source File: JWSServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidSignature_OCT() throws JOSEException{
    // Generate random 256-bit (32-byte) shared secret
    SecureRandom random = new SecureRandom();
    byte[] sharedSecret = new byte[32];
    random.nextBytes(sharedSecret);

    OCTKey key = new OCTKey();
    key.setKty("oct");
    key.setKid(KID);
    key.setK(Base64.getEncoder().encodeToString(sharedSecret));

    //Sign JWT with MAC algorithm
    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.HS256).keyID(KID).build(),
            new JWTClaimsSet.Builder()
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    );
    signedJWT.sign(new MACSigner(sharedSecret));

    assertTrue("Should be ok",jwsService.isValidSignature(signedJWT, key));
}
 
Example #8
Source File: SelfContainedTokenValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
/**
 * Validates a self contained access security.
 *
 * @param token          Incoming security. JWT to be validated.
 * @param cellStsRequest Request which reaches cell STS.
 * @throws TokenValidationFailureException TokenValidationFailureException.
 */
@Override
public void validateToken(String token, CellStsRequest cellStsRequest) throws TokenValidationFailureException {

    if (StringUtils.isEmpty(token)) {
        throw new TokenValidationFailureException("No token found in the request.");
    }
    try {
        log.debug("Validating token: {}", token);
        SignedJWT parsedJWT = SignedJWT.parse(token);
        JWTClaimsSet jwtClaimsSet = parsedJWT.getJWTClaimsSet();
        validateIssuer(jwtClaimsSet, cellStsRequest);
        validateAudience(jwtClaimsSet, cellStsRequest);
        validateExpiry(jwtClaimsSet);
        validateSignature(parsedJWT, cellStsRequest);
    } catch (ParseException e) {
        throw new TokenValidationFailureException("Error while parsing JWT: " + token, e);
    }
}
 
Example #9
Source File: FirebaseJwtTokenDecoderTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Test
public void validTokenTests() throws Exception {
	JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("one").build();
	JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
			.subject("test-subject")
			.audience("123456")
			.expirationTime(Date.from(Instant.now().plusSeconds(36000)))
			.issuer("https://securetoken.google.com/123456")
			.issueTime(Date.from(Instant.now().minusSeconds(3600)))
			.claim("auth_time", Instant.now().minusSeconds(3600).getEpochSecond())
			.build();
	SignedJWT signedJWT = signedJwt(keyGeneratorUtils.getPrivateKey(), header, claimsSet);
	List<OAuth2TokenValidator<Jwt>> validators = new ArrayList<>();
	validators.add(new JwtTimestampValidator());
	validators.add(new JwtIssuerValidator("https://securetoken.google.com/123456"));
	validators.add(new FirebaseTokenValidator("123456"));
	DelegatingOAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<Jwt>(validators);
	RestOperations operations = mockRestOperations();
	FirebaseJwtTokenDecoder decoder = new FirebaseJwtTokenDecoder(operations, "https://spring.local", validator);
	Jwt jwt = decoder.decode(signedJWT.serialize());
	assertThat(jwt.getClaims()).isNotEmpty();
}
 
Example #10
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 #11
Source File: DefaultJWTTransformer.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public String getTransformedConsumerKey(JWTClaimsSet jwtClaimsSet) throws APIManagementException {

    try {
        if (tokenIssuer.getConsumerKeyClaim() == null) {
            if (jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.CONSUMER_KEY) != null) {
                return jwtClaimsSet.getStringClaim(APIConstants.JwtTokenConstants.CONSUMER_KEY);
            } else if (jwtClaimsSet.getClaim(APIConstants.JwtTokenConstants.AUTHORIZED_PARTY) != null) {
                return jwtClaimsSet.getStringClaim(APIConstants.JwtTokenConstants.AUTHORIZED_PARTY);
            }
        } else {
            if (jwtClaimsSet.getClaim(tokenIssuer.getConsumerKeyClaim()) != null) {
                return jwtClaimsSet.getStringClaim(tokenIssuer.getConsumerKeyClaim());
            }
        }
    } catch (ParseException e) {
        throw new APIManagementException("Error while parsing JWT claims", e);
    }

    return null;
}
 
Example #12
Source File: AbstractGrantTypeHandler.java    From tutorials with MIT License 6 votes vote down vote up
protected String getAccessToken(String clientId, String subject, String approvedScope) throws Exception {
    //4. Signing
    JWSSigner jwsSigner = getJwsSigner();

    Instant now = Instant.now();
    //Long expiresInMin = 30L;
    Date expirationTime = Date.from(now.plus(expiresInMin, ChronoUnit.MINUTES));

    //3. JWT Payload or claims
    JWTClaimsSet jwtClaims = new JWTClaimsSet.Builder()
            .issuer("http://localhost:9080")
            .subject(subject)
            .claim("upn", subject)
            .claim("client_id", clientId)
            .audience("http://localhost:9280")
            .claim("scope", approvedScope)
            .claim("groups", Arrays.asList(approvedScope.split(" ")))
            .expirationTime(expirationTime) // expires in 30 minutes
            .notBeforeTime(Date.from(now))
            .issueTime(Date.from(now))
            .jwtID(UUID.randomUUID().toString())
            .build();
    SignedJWT signedJWT = new SignedJWT(jwsHeader, jwtClaims);
    signedJWT.sign(jwsSigner);
    return signedJWT.serialize();
}
 
Example #13
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenExpirationTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(), new Date());

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

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

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #14
Source File: ApiKeyAuthenticator.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the jwt token is expired or not.
 *
 * @param payload The payload of the JWT token
 * @return returns true if the JWT token is expired
 */
private static boolean isJwtTokenExpired(JWTClaimsSet payload) {

    int timestampSkew = (int) OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds();

    DefaultJWTClaimsVerifier jwtClaimsSetVerifier = new DefaultJWTClaimsVerifier();
    jwtClaimsSetVerifier.setMaxClockSkew(timestampSkew);
    try {
        jwtClaimsSetVerifier.verify(payload);
        if (log.isDebugEnabled()) {
            log.debug("Token is not expired. User: " + payload.getSubject());
        }
    } catch (BadJWTException e) {
        if ("Expired JWT".equals(e.getMessage())) {
            return true;
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Token is not expired. User: " + payload.getSubject());
    }
    return false;
}
 
Example #15
Source File: CellerySignedJWTValidator.java    From cellery-security with Apache License 2.0 6 votes vote down vote up
private void validateNotBeforeTime(JWTClaimsSet claimsSet) throws IdentityOAuth2Exception {

        Date notBeforeTime = claimsSet.getNotBeforeTime();
        if (notBeforeTime != null) {
            long timeStampSkewMillis = OAuthServerConfiguration.getInstance().getTimeStampSkewInSeconds() * 1000;
            long notBeforeTimeMillis = notBeforeTime.getTime();
            long currentTimeInMillis = System.currentTimeMillis();
            if (currentTimeInMillis + timeStampSkewMillis < notBeforeTimeMillis) {
                if (log.isDebugEnabled()) {
                    log.debug("Token is used before Not_Before_Time." +
                            ", Not Before Time(ms) : " + notBeforeTimeMillis +
                            ", TimeStamp Skew : " + timeStampSkewMillis +
                            ", Current Time : " + currentTimeInMillis + ". Token Rejected and validation terminated.");
                }
                throw new IdentityOAuth2Exception("Token is used before Not_Before_Time.");
            }
            if (log.isDebugEnabled()) {
                log.debug("Not Before Time(nbf) of Token was validated successfully.");
            }
        }
    }
 
Example #16
Source File: KnoxServiceTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
@Test(expected = ParseException.class)
public void testPlainJwt() throws Exception {
    final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
    final KeyPair pair = keyGen.generateKeyPair();
    final RSAPublicKey publicKey = (RSAPublicKey) pair.getPublic();

    final Date expiration = new Date(System.currentTimeMillis() + TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS));
    final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("user-1")
            .expirationTime(expiration)
            .build();

    final PlainJWT plainJWT = new PlainJWT(claimsSet);

    final KnoxConfiguration configuration = getConfiguration(publicKey);
    final KnoxService service = new KnoxService(configuration);

    service.getAuthenticationFromToken(plainJWT.serialize());
}
 
Example #17
Source File: DefaultIDTokenBuilder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
/**
 * Generic Signing function
 *
 * @param jwtClaimsSet contains JWT body
 * @param request
 * @return
 * @throws IdentityOAuth2Exception
 */
protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext request)
        throws IdentityOAuth2Exception {

    if (JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.RS512.equals(signatureAlgorithm)) {
        return signJWTWithRSA(jwtClaimsSet, request);
    } else if (JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) ||
            JWSAlgorithm.HS512.equals(signatureAlgorithm)) {
        // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    } else {
        // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done
        return null;
    }
}
 
Example #18
Source File: KnoxService.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Validate the jwt expiration.
 *
 * @param jwtToken knox jwt
 * @return whether this jwt is not expired
 * @throws ParseException if the payload of the jwt doesn't represent a valid json object and a jwt claims set
 */
private boolean validateExpiration(final SignedJWT jwtToken) throws ParseException {
    boolean valid = false;

    final JWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet();
    if (claimsSet == null) {
        logger.error("Claims set is missing from Knox JWT.");
        return false;
    }

    final Date now = new Date();
    final Date expiration = claimsSet.getExpirationTime();

    // the token is not expired if the expiration isn't present or the expiration is after now
    if (expiration == null || now.before(expiration)) {
        valid = true;
    }

    if (!valid) {
        logger.error("The Knox JWT is expired.");
    }

    return valid;
}
 
Example #19
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");

    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(pk));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #20
Source File: JSONWebTokenManager.java    From authmore-framework with Apache License 2.0 6 votes vote down vote up
@Override
public TokenResponse create(ClientDetails client, String userId, Set<String> scopes) {
    assertValidateScopes(client, scopes);
    JWTClaimsSet claims = new JWTClaimsSet.Builder()
            .claim(TOKEN_USER_ID, userId)
            .claim(TOKEN_CLIENT_ID, client.getClientId())
            .claim(TOKEN_AUTHORITIES, client.getAuthoritySet())
            .claim(TOKEN_SCOPES, scopes)
            .claim(TOKEN_EXPIRE_AT, expireAtByLiveTime(client.getAccessTokenValiditySeconds()))
            .claim(TOKEN_RESOURCE_IDS, client.getResourceIds())
            .build();
    PrivateKey privateKey = keyPair.getPrivate();
    RSASSASigner signer = new RSASSASigner(privateKey);
    SignedJWT signedJWT = new SignedJWT(new JWSHeader.Builder(JWSAlgorithm.RS256).build(), claims);
    try {
        signedJWT.sign(signer);
    } catch (JOSEException e) {
        throw new OAuthException("Failed to sign jwt.");
    }
    return new TokenResponse(signedJWT.serialize(), client.getAccessTokenValiditySeconds(), scopes);
}
 
Example #21
Source File: TestJWTAuthenticationHandler.java    From registry with Apache License 2.0 6 votes vote down vote up
protected SignedJWT getJWT(String sub, Date expires, RSAPrivateKey privateKey)
        throws Exception {
    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject(sub)
            .issueTime(new Date(new Date().getTime()))
            .issuer("https://c2id.com")
            .claim("scope", "openid")
            .audience("bar")
            .expirationTime(expires)
            .build();
    List<String> aud = new ArrayList<String>();
    aud.add("bar");

    JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256).build();

    SignedJWT signedJWT = new SignedJWT(header, claimsSet);
    JWSSigner signer = new RSASSASigner(privateKey);

    signedJWT.sign(signer);

    return signedJWT;
}
 
Example #22
Source File: OpenIdConnectJwtValidation.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Check whether the token has been released by the expected issuer
 */
private Boolean validateTokenIssuer(JWTClaimsSet claims) {

    String issuer = claims.getIssuer();
    if (issuer == null) {
        log.error("The authorization token doesn't have an issuer (iss)");
        return false;
    }

    if (issuer.toLowerCase().equals(this.issuer)) {
        return true;
    }

    log.error("The authorization token issuer `{}` doesn't match the expected issuer `{}`",
        issuer, this.issuer);

    return false;
}
 
Example #23
Source File: AuthorizationRequestParseRequestObjectHandlerTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void override_max_age() throws Exception {
    RSAKey rsaKey = getRSAKey();
    JWSSigner signer = new RSASSASigner(rsaKey);

    JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
            .subject("alice")
            .issuer("https://c2id.com")
            .claim("max_age", 360000)
            .expirationTime(new Date(new Date().getTime() + 60 * 1000))
            .build();

    SignedJWT signedJWT = new SignedJWT(
            new JWSHeader.Builder(JWSAlgorithm.RS256).keyID("rsa-signature").build(),
            claimsSet);

    signedJWT.sign(signer);

    String jwt = signedJWT.serialize();
    System.out.println(jwt);
}
 
Example #24
Source File: OpenIdConnectJwtValidation.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Check whether the token has been released by the expected issuer
 */
private Boolean validateTokenIssuer(JWTClaimsSet claims) {

    String issuer = claims.getIssuer();
    if (issuer == null) {
        log.error("The authorization token doesn't have an issuer (iss)");
        return false;
    }

    if (issuer.toLowerCase().equals(this.issuer)) {
        return true;
    }

    log.error("The authorization token issuer `{}` doesn't match the expected issuer `{}`",
        issuer, this.issuer);

    return false;
}
 
Example #25
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 #26
Source File: ClientAssertionServiceTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void testPlainJwt() {
    String assertion = new PlainJWT(
            new JWTClaimsSet.Builder()
                    .issuer(ISSUER)
                    .subject(CLIENT_ID)
                    .audience(AUDIENCE)
                    .expirationTime(Date.from(Instant.now().plus(1, ChronoUnit.DAYS)))
                    .build()
    ).serialize();

    OpenIDProviderMetadata openIDProviderMetadata = Mockito.mock(OpenIDProviderMetadata.class);
    String basePath="/";

    when(openIDProviderMetadata.getTokenEndpoint()).thenReturn(AUDIENCE);
    when(openIDDiscoveryService.getConfiguration(basePath)).thenReturn(openIDProviderMetadata);

    TestObserver testObserver = clientAssertionService.assertClient(JWT_BEARER_TYPE,assertion,basePath).test();

    testObserver.assertError(InvalidClientException.class);
    testObserver.assertNotComplete();
}
 
Example #27
Source File: OpenIdConnectJwtValidation.java    From remote-monitoring-services-java with MIT License 6 votes vote down vote up
/**
 * Check whether the token has been released to the expected audience
 */
private boolean validateTokenAudience(JWTClaimsSet claims) {
    List<String> audiences = claims.getAudience();

    if (audiences == null) {
        log.error("The authorization token doesn't have an audience (aud)");
        return false;
    }

    if (audiences.contains(this.audience)) {
        return true;
    }

    log.error("The authorization token audience `{}` doesn't match the expected audience `{}`",
        audiences, this.audience);

    return false;
}
 
Example #28
Source File: MACVerifierExtendedTest.java    From shiro-jwt with MIT License 6 votes vote down vote up
@Test
public void invalidTokenNotBeforeTime() throws JOSEException, ParseException {
    JWTClaimsSet jwtClaims = getJWTClaimsSet("issuer", "subject", new Date(), new Date(new Date().getTime() + 100000), new Date(new Date().getTime() + 200000));

    JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);

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

    JWSObject jwsObject = new JWSObject(header, payload);

    JWSSigner signer = new MACSigner(sharedKey);
    jwsObject.sign(signer);
    String token = jwsObject.serialize();

    SignedJWT signed = SignedJWT.parse(token);
    JWSVerifier verifier = new MACVerifierExtended(sharedKey, signed.getJWTClaimsSet());
    signed.verify(verifier);

    Assert.assertFalse("Must be invalid", signed.verify(verifier));
}
 
Example #29
Source File: Tokens.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static String asToken(final String claims) throws Exception {
    final PrivateKey pk = readPrivateKey("/testkey.pem");

    try {
        final JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.RS256)
                .type(JOSEObjectType.JWT)
                .build();

        final JWTClaimsSet claimsSet = JWTClaimsSet.parse(claims);

        final SignedJWT jwt = new SignedJWT(header, claimsSet);

        jwt.sign(new RSASSASigner(pk));

        return jwt.serialize();
    } catch (Exception e) {
        throw new RuntimeException("Could not sign JWT");
    }
}
 
Example #30
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);
}