Java Code Examples for org.gluu.oxauth.model.jwt.Jwt

The following examples show how to use org.gluu.oxauth.model.jwt.Jwt. These examples are extracted from open source projects. 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 Project: oxAuth   Source File: UserInfoRestWebServiceImpl.java    License: MIT License 6 votes vote down vote up
private String getJwtResponse(SignatureAlgorithm signatureAlgorithm, User user, AuthorizationGrant authorizationGrant,
                              Collection<String> scopes) throws Exception {
    log.trace("Building JWT reponse with next scopes {0} for user {1} and user custom attributes {0}", scopes, user.getUserId(), user.getCustomAttributes());

    Jwt jwt = new Jwt();

    // Header
    jwt.getHeader().setType(JwtType.JWT);
    jwt.getHeader().setAlgorithm(signatureAlgorithm);

    String keyId = new ServerCryptoProvider(cryptoProvider).getKeyId(webKeysConfiguration, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
    if (keyId != null) {
        jwt.getHeader().setKeyId(keyId);
    }

    // Claims
    jwt.setClaims(createJwtClaims(user, authorizationGrant, scopes));

    // Signature
    String sharedSecret = clientService.decryptSecret(authorizationGrant.getClient().getClientSecret());
    String signature = cryptoProvider.sign(jwt.getSigningInput(), jwt.getHeader().getKeyId(), sharedSecret, signatureAlgorithm);
    jwt.setEncodedSignature(signature);

    return jwt.toString();
}
 
Example 2
Source Project: oxd   Source File: ValidateOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IOpResponse execute(ValidateParams params) throws Exception {
    validateParams(params);

    Rp rp = getRp();
    OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponseByOxdId(params.getOxdId());

    final Jwt idToken = Jwt.parse(params.getIdToken());

    final Validator validator = new Validator.Builder()
            .discoveryResponse(discoveryResponse)
            .idToken(idToken)
            .keyService(getKeyService())
            .opClientFactory(getOpClientFactory())
            .oxdServerConfiguration(getConfigurationService().getConfiguration())
            .rp(rp)
            .build();
    validator.validateNonce(getStateService());
    validator.validateIdToken(rp.getClientId());
    validator.validateAccessToken(params.getAccessToken());
    validator.validateAuthorizationCode(params.getCode());

    return new POJOResponse("");
}
 
Example 3
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void tokenWithNAzpNotClientId_shouldNotValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-134-3b487caf8","another_aud"],
    //"azp":"Not_equal_to_client_id"
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiLCJhbm90aGVyX2F1ZCJdLCJhenAiOiJOb3RfZXF1YWxfdG9fY2xpZW50X2lkIiwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.Tnw-jF4p7VHgIE2_wcuP7WxRqtGFw2pmKltIri63hznYikYFC4frUZcJ44OKCt_tki2ZJY6EDhM1o9cPEz-_Vt-gsavfyDc711xlgNaPOBjGasdPvx5iilPLIogy4BXB4T3ROgqQpLQZf-00AQBBsrpZX5I2VJtLcyJL6_l3bKw");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
        assertTrue(false);
    } catch (Exception e) {
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException)e;
            assertTrue(httpException.getCode().getCode().equals("invalid_id_token_bad_authorized_party"));
        }
    }
}
 
Example 4
Source Project: oxAuth   Source File: JwtCrossCheckTest.java    License: MIT License 6 votes vote down vote up
private static String createOxauthJwt(OxAuthCryptoProvider cryptoProvider, String kid, SignatureAlgorithm algorithm) throws Exception {
    Jwt jwt = new Jwt();

    jwt.getHeader().setKeyId(kid);
    jwt.getHeader().setType(JwtType.JWT);
    jwt.getHeader().setAlgorithm(algorithm);

    jwt.getClaims().setSubjectIdentifier("1202.d50a4eeb-ab5d-474b-aaaf-e4aa47bc54a5");
    jwt.getClaims().setIssuer("1202.d50a4eeb-ab5d-474b-aaaf-e4aa47bc54a5");
    jwt.getClaims().setExpirationTime(new Date(1575559276888000L));
    jwt.getClaims().setIssuedAt(new Date(1575559276888000L));
    jwt.getClaims().setAudience("https://gomer-vbox/oxauth/restv1/token");

    String signature = cryptoProvider.sign(jwt.getSigningInput(), jwt.getHeader().getKeyId(), null, algorithm);
    jwt.setEncodedSignature(signature);
    return jwt.toString();
}
 
Example 5
Source Project: oxAuth   Source File: JwtSigner.java    License: MIT License 6 votes vote down vote up
public Jwt newJwt() throws Exception {
    jwt = new Jwt();

    // Header
    String keyId = cryptoProvider.getKeyId(webKeys, Algorithm.fromString(signatureAlgorithm.getName()), Use.SIGNATURE);
    if (keyId != null) {
        jwt.getHeader().setKeyId(keyId);
    }
    jwt.getHeader().setType(JwtType.JWT);
    jwt.getHeader().setAlgorithm(signatureAlgorithm);

    // Claims
    jwt.getClaims().setIssuer(appConfiguration.getIssuer());
    jwt.getClaims().setAudience(audience);
    return jwt;
}
 
Example 6
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Test
public void jwtStateHS384Test() throws Exception {
    showTitle("jwtStateHS384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    String sharedKey = "shared_key";

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.HS384, sharedKey, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, sharedKey, SignatureAlgorithm.HS384);
    assertTrue(validJwt);
}
 
Example 7
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Test
public void jwtStateHS512Test() throws Exception {
    showTitle("jwtStateHS512Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider();
    String sharedKey = "shared_key";

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.HS512, sharedKey, cryptoProvider);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), null,
            null, sharedKey, SignatureAlgorithm.HS512);
    assertTrue(validJwt);
}
 
Example 8
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "RS256_keyId"})
@Test
public void jwtStateRS256Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateRS256Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.RS256, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.RS256);
    assertTrue(validJwt);
}
 
Example 9
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "RS384_keyId"})
@Test
public void jwtStateRS384Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateRS384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.RS384, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.RS384);
    assertTrue(validJwt);
}
 
Example 10
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "ES256_keyId"})
@Test
public void jwtStateES256Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateES256Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES256, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES256);
    assertTrue(validJwt);
}
 
Example 11
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "ES512_keyId"})
@Test
public void jwtStateES512Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStateES512Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.ES512, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.ES512);
    assertTrue(validJwt);
}
 
Example 12
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "PS256_keyId"})
@Test
public void jwtStatePS256Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStatePS256Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.PS256, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.PS256);
    assertTrue(validJwt);
}
 
Example 13
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "PS384_keyId"})
@Test
public void jwtStatePS384Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStatePS384Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.PS384, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.PS384);
    assertTrue(validJwt);
}
 
Example 14
Source Project: oxAuth   Source File: EncodeClaimsInStateParameter.java    License: MIT License 6 votes vote down vote up
@Parameters({"keyStoreFile", "keyStoreSecret", "dnName", "PS512_keyId"})
@Test
public void jwtStatePS512Test(final String keyStoreFile, final String keyStoreSecret,
                              final String dnName, final String keyId) throws Exception {
    showTitle("jwtStatePS512Test");

    OxAuthCryptoProvider cryptoProvider = new OxAuthCryptoProvider(keyStoreFile, keyStoreSecret, dnName);

    String rfp = UUID.randomUUID().toString();
    String jti = UUID.randomUUID().toString();

    JwtState jwtState = new JwtState(SignatureAlgorithm.PS512, cryptoProvider);
    jwtState.setKeyId(keyId);
    jwtState.setRfp(rfp);
    jwtState.setJti(jti);
    jwtState.setAdditionalClaims(new JSONObject(additionalClaims));

    String encodedState = jwtState.getEncodedJwt();
    assertNotNull(encodedState);
    System.out.println("Signed JWS State: " + encodedState);

    Jwt jwt = Jwt.parse(encodedState);
    boolean validJwt = cryptoProvider.verifySignature(jwt.getSigningInput(), jwt.getEncodedSignature(), keyId,
            null, null, SignatureAlgorithm.PS512);
    assertTrue(validJwt);
}
 
Example 15
Source Project: oxAuth   Source File: SessionIdService.java    License: MIT License 6 votes vote down vote up
private Jwt generateJwt(SessionId sessionId, String audience) {
    try {
        JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, SignatureAlgorithm.RS512, audience);
        Jwt jwt = jwtSigner.newJwt();

        // claims
        jwt.getClaims().setClaim("id", sessionId.getId());
        jwt.getClaims().setClaim("authentication_time", sessionId.getAuthenticationTime());
        jwt.getClaims().setClaim("user_dn", sessionId.getUserDn());
        jwt.getClaims().setClaim("state", sessionId.getState() != null ?
                sessionId.getState().getValue() : "");

        jwt.getClaims().setClaim("session_attributes", JwtSubClaimObject.fromMap(sessionId.getSessionAttributes()));

        jwt.getClaims().setClaim("last_used_at", sessionId.getLastUsedAt());
        jwt.getClaims().setClaim("permission_granted", sessionId.getPermissionGranted());
        jwt.getClaims().setClaim("permission_granted_map", JwtSubClaimObject.fromBooleanMap(sessionId.getPermissionGrantedMap().getPermissionGranted()));

        // sign
        return jwtSigner.sign();
    } catch (Exception e) {
        log.error("Failed to sign session jwt! " + e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 16
Source Project: oxd   Source File: CheckAccessTokenOperation.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public IOpResponse execute(CheckAccessTokenParams params) throws Exception {
    final OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponseByOxdId(params.getOxdId());
    final String idToken = params.getIdToken();
    final String accessToken = params.getAccessToken();

    final Jwt jwt = Jwt.parse(idToken);

    final Date issuedAt = jwt.getClaims().getClaimAsDate(JwtClaimName.ISSUED_AT);
    final Date expiresAt = jwt.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);

    final CheckAccessTokenResponse opResponse = new CheckAccessTokenResponse();
    opResponse.setActive(isAccessTokenValid(accessToken, jwt, discoveryResponse));
    opResponse.setIssuedAt(issuedAt);
    opResponse.setExpiresAt(expiresAt);
    return opResponse;
}
 
Example 17
Source Project: oxTrust   Source File: OpenIdClient.java    License: MIT License 5 votes vote down vote up
protected CommonProfile retrieveUserProfileFromUserInfoResponse(final WebContext context, final Jwt jwt, final UserInfoResponse userInfoResponse) {
	final CommonProfile profile = new CommonProfile();

	String nonceResponse = (String) jwt.getClaims().getClaim(JwtClaimName.NONCE);
       final String nonceSession = (String) context.getSessionAttribute(getName() + SESSION_NONCE_PARAMETER);
       logger.debug("Session nonce: '{}'", nonceSession);
       if (!StringHelper.equals(nonceSession, nonceResponse)) {
           logger.error("User info response:  nonce is not matching.");
           throw new CommunicationException("Nonce is not match" + nonceResponse + " : " + nonceSession);
       }

	String id = getFirstClaim(userInfoResponse, JwtClaimName.USER_NAME);
	if (StringHelper.isEmpty(id)) {
		id = getFirstClaim(userInfoResponse, JwtClaimName.SUBJECT_IDENTIFIER);
	}
	profile.setId(id);

	List<ClaimToAttributeMapping> claimMappings = this.appConfiguration.getOpenIdClaimMapping();
	if ((claimMappings == null) || (claimMappings.size() == 0)) {
		logger.info("Using default claims to attributes mapping");
		profile.setUserName(id);
		profile.setEmail(getFirstClaim(userInfoResponse, JwtClaimName.EMAIL));

		profile.setDisplayName(getFirstClaim(userInfoResponse, JwtClaimName.NAME));
		profile.setFirstName(getFirstClaim(userInfoResponse, JwtClaimName.GIVEN_NAME));
		profile.setFamilyName(getFirstClaim(userInfoResponse, JwtClaimName.FAMILY_NAME));
		profile.setZone(getFirstClaim(userInfoResponse, JwtClaimName.ZONEINFO));
		profile.setLocale(getFirstClaim(userInfoResponse, JwtClaimName.LOCALE));
	} else {
		for (ClaimToAttributeMapping mapping : claimMappings) {
			String attribute = mapping.getAttribute();
			String value = getFirstClaim(userInfoResponse, mapping.getClaim());
			profile.addAttribute(attribute, value);
			logger.trace("Adding attribute '{}' with value '{}'", attribute, value);
		}
	}

	return profile;
}
 
Example 18
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithAudArrayStringWithMultiElements_shouldBeValid() throws InvalidJwtException {
    //"aud": "[\"6b578a9b-7513-477a-9a7f-1343b487caf8\",\"another_element\"]",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IltcIjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOFwiLFwiYW5vdGhlcl9lbGVtZW50XCJdIiwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.Z185fBjN4B6ghJaF7Szvvwq2_aNK8xnBdJWY_jZtSrb4DMqB8kXkEF9c11eIldt2fY3lj3cEPUIBjvW9-Bye-ClfGgqZ7eXGCXOEQ3pNdTV0YDSJDMjYOSTAnmeccx8hUsqKbSd0JoZUzaDWZgLYxXX1GodV_V_Nx_Xr3rWGGrc");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 19
Source Project: oxAuth   Source File: UmaRptService.java    License: MIT License 5 votes vote down vote up
private void runScriptAndInjectValuesIntoJwt(Jwt jwt, ExecutionContext executionContext) {
    JSONObject responseAsJsonObject = new JSONObject();

    ExternalUmaRptClaimsContext context = new ExternalUmaRptClaimsContext(executionContext);
    if (externalUmaRptClaimsService.externalModify(responseAsJsonObject, context)) {
        log.trace("Successfully run external RPT Claim scripts.");

        if (context.isTranferPropertiesIntoJwtClaims()) {
            log.trace("Transfering claims into jwt ...");
            JwtUtil.transferIntoJwtClaims(responseAsJsonObject, jwt);
            log.trace("Transfered.");
        }
    }
}
 
Example 20
Source Project: oxAuth   Source File: JwtUtil.java    License: MIT License 5 votes vote down vote up
public static void transferIntoJwtClaims(JSONObject jsonObject, Jwt jwt) {
    if (jsonObject == null || jwt == null) {
        return;
    }

    for (String key : jsonObject.keySet()) {
        final Object value = jsonObject.opt(key);
        jwt.getClaims().setClaimObject(key, value, true);
    }
}
 
Example 21
Source Project: oxd   Source File: AccessTokenAsJwtTest.java    License: Apache License 2.0 5 votes vote down vote up
@Parameters({"opHost", "redirectUrls",  "postLogoutRedirectUrls"})
@Test
public void testWithAccessTokenAsJwt(String opHost, String redirectUrls, String postLogoutRedirectUrls) throws Exception {

    final DevelopersApi apiClient = api();

    final RegisterSiteParams siteParams = new io.swagger.client.model.RegisterSiteParams();
    siteParams.setOpHost(opHost);
    siteParams.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    siteParams.setPostLogoutRedirectUris(Lists.newArrayList(postLogoutRedirectUrls.split(" ")));
    siteParams.setScope(Lists.newArrayList("openid", "uma_protection", "profile"));
    siteParams.setAccessTokenAsJwt(true);
    siteParams.setGrantTypes(Lists.newArrayList(
            GrantType.AUTHORIZATION_CODE.getValue(),
            GrantType.CLIENT_CREDENTIALS.getValue()));

    final RegisterSiteResponse resp = apiClient.registerSite(siteParams);
    assertNotNull(resp);

    final GetClientTokenParams tokenParams = new GetClientTokenParams();
    tokenParams.setOpHost(opHost);
    tokenParams.setScope(Lists.newArrayList("openid"));
    tokenParams.setClientId(resp.getClientId());
    tokenParams.setClientSecret(resp.getClientSecret());

    GetClientTokenResponse tokenResponse = apiClient.getClientToken(tokenParams);

    assertNotNull(tokenResponse);
    assertTrue(!Strings.isNullOrEmpty(tokenResponse.getAccessToken()));

    final Jwt parse = Jwt.parse(tokenResponse.getAccessToken());
    assertNotNull(parse);
    System.out.println("access token as JWT: " + tokenResponse.getAccessToken() + ", claims: " + parse.getClaims());
}
 
Example 22
Source Project: oxd   Source File: AccessTokenAsJwtTest.java    License: Apache License 2.0 5 votes vote down vote up
@Parameters({"host", "opHost", "redirectUrls", "postLogoutRedirectUrls"})
@Test
public void getClientToken(String host, String opHost, String redirectUrls, String postLogoutRedirectUrls) throws InvalidJwtException {
    final RegisterSiteParams params = new RegisterSiteParams();
    params.setOpHost(opHost);
    params.setRedirectUris(Lists.newArrayList(redirectUrls.split(" ")));
    params.setPostLogoutRedirectUris(Lists.newArrayList(postLogoutRedirectUrls.split(" ")));
    params.setScope(Lists.newArrayList("openid", "uma_protection", "profile"));
    params.setAccessTokenAsJwt(true);
    params.setGrantTypes(Lists.newArrayList(
            GrantType.AUTHORIZATION_CODE.getValue(),
            GrantType.CLIENT_CREDENTIALS.getValue()));

    final RegisterSiteResponse resp = org.gluu.oxd.server.Tester.newClient(host).registerSite(params);
    assertResponse(resp);

    final GetClientTokenParams tokenParams = new GetClientTokenParams();
    tokenParams.setOpHost(opHost);
    tokenParams.setScope(Lists.newArrayList("openid"));
    tokenParams.setClientId(resp.getClientId());
    tokenParams.setClientSecret(resp.getClientSecret());

    GetClientTokenResponse tokenResponse = org.gluu.oxd.server.Tester.newClient(host).getClientToken(tokenParams);

    assertNotNull(tokenResponse);
    notEmpty(tokenResponse.getAccessToken());

    final Jwt parse = Jwt.parse(tokenResponse.getAccessToken());
    assertNotNull(parse);
    System.out.println("access token as JWT: " + tokenResponse.getAccessToken() + ", claims: " + parse.getClaims());
}
 
Example 23
Source Project: oxAuth   Source File: AccessTokenAsJwtHttpTest.java    License: MIT License 5 votes vote down vote up
/**
 * Test for the complete Authorization Code Flow.
 */
@Parameters({"userId", "userSecret", "redirectUris", "redirectUri", "sectorIdentifierUri"})
@Test
public void accessTokenAsJwt(
        final String userId, final String userSecret, final String redirectUris, final String redirectUri,
        final String sectorIdentifierUri) throws Exception {
    showTitle("accessTokenAsJwt");

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN, ResponseType.TOKEN);
    List<String> scopes = Arrays.asList("openid", "profile", "address", "email", "phone", "user_name");

    RegisterResponse registerResponse = registerClient(redirectUri, responseTypes, scopes);

    String clientId = registerResponse.getClientId();

    // Request authorization and receive the authorization code.
    String nonce = UUID.randomUUID().toString();
    AuthorizationResponse authorizationResponse = requestAuthorization(userId, userSecret, redirectUri, responseTypes, scopes, clientId, nonce);

    String accessToken = authorizationResponse.getAccessToken();

    // Validate access token as jwt
    Jwt jwt = Jwt.parse(accessToken);
    assertEquals(clientId, jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE));
    assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM));
    assertNotNull(jwt.getClaims().getClaimAsString("scope"));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER));
    assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER));
}
 
Example 24
Source Project: oxAuth   Source File: IntrospectionWsHttpTest.java    License: MIT License 5 votes vote down vote up
@Test
@Parameters({"umaPatClientId", "umaPatClientSecret"})
public void bearerWithResponseAsJwt(final String umaPatClientId, final String umaPatClientSecret) throws Exception {
    final ClientExecutor clientExecutor = clientExecutor(true);
    final Token authorization = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret, clientExecutor);
    final Token tokenToIntrospect = UmaClient.requestPat(tokenEndpoint, umaPatClientId, umaPatClientSecret, clientExecutor);

    final IntrospectionService introspectionService = ClientFactory.instance().createIntrospectionService(introspectionEndpoint, clientExecutor);
    final String jwtAsString = introspectionService.introspectTokenWithResponseAsJwt("Bearer " + authorization.getAccessToken(), tokenToIntrospect.getAccessToken(), true);
    final Jwt jwt = Jwt.parse(jwtAsString);
    assertTrue(Boolean.parseBoolean(jwt.getClaims().getClaimAsString("active")));
}
 
Example 25
Source Project: oxAuth   Source File: UmaValidationService.java    License: MIT License 5 votes vote down vote up
public boolean isIdTokenValid(Jwt idToken) {
    try {
        final String issuer = idToken.getClaims().getClaimAsString(JwtClaimName.ISSUER);
        //final String nonceFromToken = idToken.getClaims().getClaimAsString(JwtClaimName.NONCE);
        //final String audienceFromToken = idToken.getClaims().getClaimAsString(JwtClaimName.AUDIENCE);

        final Date expiresAt = idToken.getClaims().getClaimAsDate(JwtClaimName.EXPIRATION_TIME);
        final Date now = new Date();
        if (now.after(expiresAt)) {
            log.error("ID Token is expired. (It is after " + now + ").");
            return false;
        }

        // 1. validate issuer
        if (!issuer.equals(appConfiguration.getIssuer())) {
            log.error("ID Token issuer is invalid. Token issuer: " + issuer + ", server issuer: " + appConfiguration.getIssuer());
            return false;
        }

        // 2. validate signature
        final String kid = idToken.getHeader().getClaimAsString(JwtHeaderName.KEY_ID);
        final String algorithm = idToken.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM);
        RSAPublicKey publicKey = getPublicKey(kid);
        if (publicKey != null) {
            RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.fromString(algorithm), publicKey);
            boolean signature = rsaSigner.validate(idToken);
            if (signature) {
                log.debug("ID Token is successfully validated.");
                return true;
            }
            log.error("ID Token signature is invalid.");
        } else {
            log.error("Failed to get RSA public key.");
        }
        return false;
    } catch (Exception e) {
        log.error("Failed to validate id_token. Message: " + e.getMessage(), e);
        return false;
    }
}
 
Example 26
Source Project: oxAuth   Source File: AuthorizationGrant.java    License: MIT License 5 votes vote down vote up
private String createAccessTokenAsJwt(AccessToken accessToken, ExecutionContext context) throws Exception {
    final User user = getUser();
    final Client client = getClient();

    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm
            .fromString(appConfiguration.getDefaultSignatureAlgorithm());
    if (client.getAccessTokenSigningAlg() != null
            && SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg()) != null) {
        signatureAlgorithm = SignatureAlgorithm.fromString(client.getAccessTokenSigningAlg());
    }

    final JwtSigner jwtSigner = new JwtSigner(appConfiguration, webKeysConfiguration, signatureAlgorithm,
            client.getClientId(), clientService.decryptSecret(client.getClientSecret()));
    final Jwt jwt = jwtSigner.newJwt();
    jwt.getClaims().setClaim("scope", Lists.newArrayList(getScopes()));
    jwt.getClaims().setClaim("client_id", getClientId());
    jwt.getClaims().setClaim("username", user != null ? user.getAttribute("displayName") : null);
    jwt.getClaims().setClaim("token_type", accessToken.getTokenType().getName());
    jwt.getClaims().setExpirationTime(accessToken.getExpirationDate());
    jwt.getClaims().setIssuedAt(accessToken.getCreationDate());
    jwt.getClaims().setSubjectIdentifier(getSub());
    jwt.getClaims().setClaim("x5t#S256", accessToken.getX5ts256());
    Audience.setAudience(jwt.getClaims(), getClient());

    if (client.getAttributes().getRunIntrospectionScriptBeforeAccessTokenAsJwtCreationAndIncludeClaims()) {
        runIntrospectionScriptAndInjectValuesIntoJwt(jwt, context);
    }

    return jwtSigner.sign().toString();
}
 
Example 27
Source Project: oxAuth   Source File: JwtSigner.java    License: MIT License 5 votes vote down vote up
public Jwt sign() throws Exception {
    // Signature
    String signature = cryptoProvider.sign(jwt.getSigningInput(), jwt.getHeader().getKeyId(), hmacSharedSecret, signatureAlgorithm);
    jwt.setEncodedSignature(signature);

    return jwt;
}
 
Example 28
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithSingleAudArrayAndNoAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": ["6b578a9b-7513-477a-9a7f-1343b487caf8"],
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6WyI2YjU3OGE5Yi03NTEzLTQ3N2EtOWE3Zi0xMzQzYjQ4N2NhZjgiXSwic3ViIjoicy1fWmlyVnQ3Tk9EZG5XREFVR3JqVDJxVVp3SzZjWFRoYjlxVjk5di10ZyIsImF1dGhfdGltZSI6MTU2ODE4NTMyNywiaXNzIjoiaHR0cHM6Ly9kdW1teS1pc3N1ZXIub3JnIiwiZXhwIjoxOTY4MTg4OTMwLCJpYXQiOjE1NjgxODUzMzAsIm5vbmNlIjoiN3I0NnV0NmVtdTlnaTExZ244MDQ0dW02NDAiLCJveE9wZW5JRENvbm5lY3RWZXJzaW9uIjoib3BlbmlkY29ubmVjdC0xLjAifQ.cP6DGPkYYnzDTHrH04F4Q48cPqH2T4R4RjGJmLr5QGA1pUYOOxvLj8Ak0EqmzV_83Zy0wgvyzFCv0xdi06BguUgnM4u6LL8V0hLzrdHIwJHvz5L5Gqbvs5Vg61CpP409lo0sHUN08zfN_WU3EWXK6JlSvFtE59jWSJWBF5pmLX4");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 29
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithSingleAudStringAndNoAzp_shouldBeValid() throws InvalidJwtException {
    //"aud": "6b578a9b-7513-477a-9a7f-1343b487caf8",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOCIsInN1YiI6InMtX1ppclZ0N05PRGRuV0RBVUdyalQycVVad0s2Y1hUaGI5cVY5OXYtdGciLCJhdXRoX3RpbWUiOjE1NjgxODUzMjcsImlzcyI6Imh0dHBzOi8vZHVtbXktaXNzdWVyLm9yZyIsImV4cCI6MTk2ODE4ODkzMCwiaWF0IjoxNTY4MTg1MzMwLCJub25jZSI6IjdyNDZ1dDZlbXU5Z2kxMWduODA0NHVtNjQwIiwib3hPcGVuSURDb25uZWN0VmVyc2lvbiI6Im9wZW5pZGNvbm5lY3QtMS4wIn0.PqnRiAhXqdeTbW1_JdRl6rLDMn36ists9Eq1n_2vOKYjGs_VxxkcdQfCt93KfC3WqEObhjlKDzwp6YUXi_7Wqta58ftUz0FU2jB7np3mq5m8lY_hKVhoZJMvxzMbCkiH-8jwtq9MZKEw3qyrwQEHQ0l21tograWD80gRedaQuD4");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}
 
Example 30
Source Project: oxd   Source File: ValidatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tokenWithAudArrayStringWithOneElement_shouldBeValid() throws InvalidJwtException {
    //"aud": "[\"6b578a9b-7513-477a-9a7f-1343b487caf8\"]",
    final Jwt idToken = Jwt.parse("eyJraWQiOiJjZmFiMzRlYy0xNjhkLTQ4OTUtODRiOC0xZjAyNzgwNDkxYzciLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdF9oYXNoIjoiMnI1clZ2STdpMWxfcnNXZUV4bGRuUSIsImF1ZCI6IltcIjZiNTc4YTliLTc1MTMtNDc3YS05YTdmLTEzNDNiNDg3Y2FmOFwiXSIsInN1YiI6InMtX1ppclZ0N05PRGRuV0RBVUdyalQycVVad0s2Y1hUaGI5cVY5OXYtdGciLCJhdXRoX3RpbWUiOjE1NjgxODUzMjcsImlzcyI6Imh0dHBzOi8vZHVtbXktaXNzdWVyLm9yZyIsImV4cCI6MTk2ODE4ODkzMCwiaWF0IjoxNTY4MTg1MzMwLCJub25jZSI6IjdyNDZ1dDZlbXU5Z2kxMWduODA0NHVtNjQwIiwib3hPcGVuSURDb25uZWN0VmVyc2lvbiI6Im9wZW5pZGNvbm5lY3QtMS4wIn0.bFgbYtgt5OA2hdwAXXCwaVMUYprArsGoURJgaA0d-YfsDYu8HU9zVDraDhflSc2Wg9uMv4RAKqEfldDwLIRIocGk5XwjyeOHFAWAlDMeDSPUAWy7d7oNGwPrRNZu37RUT1ncRS9ZAIsOhtJjflUTD0J12DeD-wT_V6Jpv8jn3Mo");
    String clientId = "6b578a9b-7513-477a-9a7f-1343b487caf8";
    try {
        Validator.validateAudience(idToken, clientId);
    } catch (Exception e) {
        assertFalse(e instanceof HttpException);
    }
}