Search in sources :

Example 1 with SignedJwt

use of org.forgerock.json.jose.jws.SignedJwt in project OpenAM by OpenRock.

the class RestAuthenticationHandler method authenticate.

/**
     * Handles either the creation or retrieval of the Login Process, dependent on if the request is a new
     * authentication request or a continuation of one.
     *
     * @param request The HttpServletRequest.
     * @param response The HttpServletResponse.
     * @param postBody The post body of the request.
     * @param authIndexType The authentication index type.
     * @param indexValue The authentication index value.
     * @param sessionUpgradeSSOTokenId The SSO Token Id of the user's current session, null if not performing a session
     *                                 upgrade.
     * @return The Response of the authentication request.
     */
private JsonValue authenticate(HttpServletRequest request, HttpServletResponse response, JsonValue postBody, String authIndexType, String indexValue, String sessionUpgradeSSOTokenId) throws RestAuthException {
    LoginProcess loginProcess = null;
    try {
        AuthIndexType indexType = getAuthIndexType(authIndexType);
        String authId = null;
        String sessionId = null;
        if (postBody != null) {
            authId = getAuthId(postBody);
            if (authId != null) {
                SignedJwt jwt = authIdHelper.reconstructAuthId(authId);
                sessionId = getSessionId(jwt);
                indexType = getAuthIndexType(jwt);
                indexValue = getAuthIndexValue(jwt);
                String realmDN = getRealmDomainName(jwt);
                AuditRequestContext.putProperty(SESSION_ID, sessionId);
                authIdHelper.verifyAuthId(realmDN, authId);
            }
        }
        LoginConfiguration loginConfiguration = new LoginConfiguration().httpRequest(request).httpResponse(response).indexType(indexType).indexValue(indexValue).sessionId(sessionId).forceAuth(request.getParameter(AuthUtils.FORCE_AUTH)).sessionUpgrade(sessionUpgradeSSOTokenId);
        loginProcess = loginAuthenticator.getLoginProcess(loginConfiguration);
        return processAuthentication(request, response, postBody, authId, loginProcess, loginConfiguration);
    } catch (RestAuthException e) {
        if (loginProcess != null) {
            String failureUrl = urlValidator.getRedirectUrl(loginProcess.getAuthContext().getOrgDN(), loginProcess.getFailureURL(), null);
            e.setFailureUrl(failureUrl);
        }
        throw e;
    } catch (L10NMessageImpl e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JsonException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (SignatureException e) {
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, e);
    } catch (AuthLoginException e) {
        throw new RestAuthException(amAuthErrorCodeResponseStatusMapping.getAuthLoginExceptionResponseStatus(e.getErrorCode()), e);
    } catch (JwsSigningException jse) {
        DEBUG.error("JwsSigningException", jse);
        throw new RestAuthException(ResourceException.INTERNAL_ERROR, "JwsSigningException, " + jse.getMessage());
    }
}
Also used : RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) JsonException(org.forgerock.json.JsonException) JwsSigningException(org.forgerock.json.jose.exceptions.JwsSigningException) L10NMessageImpl(com.sun.identity.shared.locale.L10NMessageImpl) AuthIndexType(org.forgerock.openam.core.rest.authn.core.AuthIndexType) LoginConfiguration(org.forgerock.openam.core.rest.authn.core.LoginConfiguration) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) SignatureException(java.security.SignatureException) LoginProcess(org.forgerock.openam.core.rest.authn.core.LoginProcess)

Example 2 with SignedJwt

use of org.forgerock.json.jose.jws.SignedJwt in project OpenAM by OpenRock.

the class AuthIdHelperTest method shouldVerifyAuthIdAndFail.

@Test
public void shouldVerifyAuthIdAndFail() throws SignatureException, SSOException, SMSException {
    //Given
    SignedJwt signedJwt = mock(SignedJwt.class);
    PublicKey publicKey = mock(PublicKey.class);
    SigningHandler signingHandler = mock(SigningHandler.class);
    given(jwtBuilderFactory.reconstruct("AUTH_ID", SignedJwt.class)).willReturn(signedJwt);
    given(signedJwt.verify(signingHandler)).willReturn(false);
    mockGetSigningKey("REALM_DN", false);
    //When
    boolean exceptionCaught = false;
    try {
        authIdHelper.verifyAuthId("REALM_DN", "AUTH_ID");
        fail();
    } catch (RestAuthException e) {
        exceptionCaught = true;
    }
    //Then
    verify(jwtBuilderFactory).reconstruct("AUTH_ID", SignedJwt.class);
    verify(signedJwt).verify(Matchers.<SigningHandler>anyObject());
    assertTrue(exceptionCaught);
}
Also used : RestAuthException(org.forgerock.openam.core.rest.authn.exceptions.RestAuthException) PublicKey(java.security.PublicKey) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) SigningHandler(org.forgerock.json.jose.jws.handlers.SigningHandler) Test(org.testng.annotations.Test)

Example 3 with SignedJwt

use of org.forgerock.json.jose.jws.SignedJwt in project OpenAM by OpenRock.

the class JwtHandler method validateJwt.

/**
     * Validate the integrity of the JWT OIDC token, according to the spec
     * (http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation). Specifically check that the issuer is
     * the expected issuer, the token has not expired, the token has at least one audience claim, and if there is an
     * authorized party claim ("azp"), does it appear in the audience list contained within the token?
     *
     * @param jwtValue The encoded JWT string.
     * @return The validated JWT claims.
     * @throws AuthLoginException
     */
public JwtClaimsSet validateJwt(String jwtValue) throws AuthLoginException {
    final SignedJwt signedJwt = getSignedJwt(jwtValue);
    JwtClaimsSet jwtClaimSet = signedJwt.getClaimsSet();
    final String jwtClaimSetIssuer = jwtClaimSet.getIssuer();
    if (!config.getConfiguredIssuer().equals(jwtClaimSetIssuer)) {
        logger.error("The issuer configured for the module, " + config.getConfiguredIssuer() + ", and the " + "issuer found in the token, " + jwtClaimSetIssuer + ", do not match. This means that the token " + "authentication was directed at the wrong module, or the targeted module is mis-configured.");
        throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_TOKEN_ISSUER_MISMATCH, null);
    }
    // See if a resolver is present corresponding to jwt issuer, and if not, add, then dispatch validation to
    // resolver.
    OpenIdResolver resolver = openIdResolverCache.getResolverForIssuer(config.getCryptoContextValue());
    if (resolver == null) {
        if (logger.messageEnabled()) {
            if (CRYPTO_CONTEXT_TYPE_CLIENT_SECRET.equals(config.getCryptoContextType())) {
                logger.message("Creating OpenIdResolver for issuer " + jwtClaimSetIssuer + " using client secret");
            } else {
                logger.message("Creating OpenIdResolver for issuer " + jwtClaimSetIssuer + " using config url " + config.getCryptoContextValue());
            }
        }
        try {
            resolver = openIdResolverCache.createResolver(jwtClaimSetIssuer, config.getCryptoContextType(), config.getCryptoContextValue(), config.getCryptoContextUrlValue());
        } catch (IllegalStateException e) {
            logger.error("Could not create OpenIdResolver for issuer " + jwtClaimSetIssuer + " using crypto context value " + config.getCryptoContextValue() + " :" + e);
            throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_ISSUER_MISMATCH, null);
        } catch (FailedToLoadJWKException e) {
            logger.error("Could not create OpenIdResolver for issuer " + jwtClaimSetIssuer + " using crypto context value " + config.getCryptoContextValue() + " :" + e, e);
            throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_JWK_NOT_LOADED, null);
        }
    }
    try {
        resolver.validateIdentity(signedJwt);
        List<String> audienceClaim = jwtClaimSet.getAudience();
        if (!jwtHasAudienceClaim(jwtClaimSet)) {
            logger.error("No audience claim present in ID token.");
            throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_NO_AUDIENCE_CLAIM, null);
        }
        if (jwtHasAuthorizedPartyClaim(jwtClaimSet)) {
            String authorizedPartyClaim = (String) jwtClaimSet.getClaim(AUTHORIZED_PARTY_CLAIM_KEY);
            if (!audienceClaim.contains(authorizedPartyClaim)) {
                logger.error("Authorized party was present in ID token, but its value was not found in the " + "audience claim.");
                throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_AUTHORIZED_PARTY_NOT_IN_AUDIENCE, null);
            }
        }
    } catch (OpenIdConnectVerificationException oice) {
        logger.warning("Verification of ID Token failed: " + oice);
        throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_VERIFICATION_FAILED, null);
    } catch (JwsSigningException jse) {
        logger.error("JwsSigningException", jse);
        throw new AuthLoginException(RESOURCE_BUNDLE_NAME, BUNDLE_KEY_JWS_SIGNING_EXCEPTION, null);
    }
    return jwtClaimSet;
}
Also used : JwsSigningException(org.forgerock.json.jose.exceptions.JwsSigningException) JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) OpenIdResolver(org.forgerock.jaspi.modules.openid.resolvers.OpenIdResolver) FailedToLoadJWKException(org.forgerock.jaspi.modules.openid.exceptions.FailedToLoadJWKException) AuthLoginException(com.sun.identity.authentication.spi.AuthLoginException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) OpenIdConnectVerificationException(org.forgerock.jaspi.modules.openid.exceptions.OpenIdConnectVerificationException)

Example 4 with SignedJwt

use of org.forgerock.json.jose.jws.SignedJwt in project OpenAM by OpenRock.

the class OpenIDConnectEndSession method endSession.

/**
     * Ends an OpenId Connect session.
     *
     * @param idToken The OpenId Token.
     * @throws BadRequestException If the request is malformed.
     * @throws ServerException If any internal server error occurs.
     */
public void endSession(String idToken) throws BadRequestException, ServerException {
    if (idToken == null || idToken.isEmpty()) {
        logger.warn("No id_token_hint parameter supplied to the endSession endpoint");
        throw new BadRequestException("The endSession endpoint requires an id_token_hint parameter");
    }
    JwtReconstruction jwtReconstruction = new JwtReconstruction();
    SignedJwt jwt = jwtReconstruction.reconstructJwt(idToken, SignedJwt.class);
    JwtClaimsSet claims = jwt.getClaimsSet();
    String opsId = (String) claims.getClaim(OAuth2Constants.JWTTokenParams.OPS);
    if (opsId == null) {
        opsId = (String) claims.getClaim(OAuth2Constants.JWTTokenParams.LEGACY_OPS);
    }
    openIDConnectProvider.destroySession(opsId);
}
Also used : JwtClaimsSet(org.forgerock.json.jose.jwt.JwtClaimsSet) JwtReconstruction(org.forgerock.json.jose.common.JwtReconstruction) BadRequestException(org.forgerock.oauth2.core.exceptions.BadRequestException) SignedJwt(org.forgerock.json.jose.jws.SignedJwt)

Example 5 with SignedJwt

use of org.forgerock.json.jose.jws.SignedJwt in project OpenAM by OpenRock.

the class OpenIdConnectTokenGenerationImpl method generate.

@Override
public String generate(SSOToken subjectToken, STSInstanceState stsInstanceState, TokenGenerationServiceInvocationState invocationState) throws TokenCreationException {
    final OpenIdConnectTokenConfig tokenConfig = stsInstanceState.getConfig().getOpenIdConnectTokenConfig();
    final long issueInstant = System.currentTimeMillis();
    final String subject = ssoTokenIdentity.validateAndGetTokenPrincipal(subjectToken);
    STSOpenIdConnectToken openIdConnectToken = buildToken(subjectToken, tokenConfig, invocationState.getOpenIdConnectTokenGenerationState(), issueInstant / 1000, subject);
    final JwsAlgorithm jwsAlgorithm = tokenConfig.getSignatureAlgorithm();
    final JwsAlgorithmType jwsAlgorithmType = jwsAlgorithm.getAlgorithmType();
    String tokenString;
    if (JwsAlgorithmType.HMAC.equals(jwsAlgorithmType)) {
        final SignedJwt signedJwt = symmetricSign(openIdConnectToken, jwsAlgorithm, tokenConfig.getClientSecret());
        tokenString = signedJwt.build();
    } else if (JwsAlgorithmType.RSA.equals(jwsAlgorithmType)) {
        final SignedJwt signedJwt = asymmetricSign(openIdConnectToken, jwsAlgorithm, getKeyPair(stsInstanceState.getOpenIdConnectTokenPKIProvider(), tokenConfig.getSignatureKeyAlias(), tokenConfig.getSignatureKeyPassword()), determinePublicKeyReferenceType(tokenConfig));
        tokenString = signedJwt.build();
    } else {
        throw new TokenCreationException(ResourceException.BAD_REQUEST, "Unknown JwsAlgorithmType: " + jwsAlgorithmType);
    }
    if (stsInstanceState.getConfig().persistIssuedTokensInCTS()) {
        try {
            ctsTokenPersistence.persistToken(invocationState.getStsInstanceId(), TokenType.OPENIDCONNECT, tokenString, subject, issueInstant, tokenConfig.getTokenLifetimeInSeconds());
        } catch (CTSTokenPersistenceException e) {
            throw new TokenCreationException(e.getCode(), e.getMessage(), e);
        }
    }
    return tokenString;
}
Also used : JwsAlgorithm(org.forgerock.json.jose.jws.JwsAlgorithm) JwsAlgorithmType(org.forgerock.json.jose.jws.JwsAlgorithmType) SignedJwt(org.forgerock.json.jose.jws.SignedJwt) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) CTSTokenPersistenceException(org.forgerock.openam.sts.CTSTokenPersistenceException) OpenIdConnectTokenConfig(org.forgerock.openam.sts.config.user.OpenIdConnectTokenConfig)

Aggregations

SignedJwt (org.forgerock.json.jose.jws.SignedJwt)17 JwtClaimsSet (org.forgerock.json.jose.jwt.JwtClaimsSet)8 Test (org.testng.annotations.Test)5 SSOToken (com.iplanet.sso.SSOToken)4 ClientRegistration (org.forgerock.oauth2.core.ClientRegistration)3 OpenIdConnectTokenConfig (org.forgerock.openam.sts.config.user.OpenIdConnectTokenConfig)3 AuthLoginException (com.sun.identity.authentication.spi.AuthLoginException)2 PublicKey (java.security.PublicKey)2 SignatureException (java.security.SignatureException)2 JsonValue (org.forgerock.json.JsonValue)2 JwtBuilderFactory (org.forgerock.json.jose.builders.JwtBuilderFactory)2 JwtReconstruction (org.forgerock.json.jose.common.JwtReconstruction)2 JwsSigningException (org.forgerock.json.jose.exceptions.JwsSigningException)2 SigningHandler (org.forgerock.json.jose.jws.handlers.SigningHandler)2 InvalidClientException (org.forgerock.oauth2.core.exceptions.InvalidClientException)2 NotFoundException (org.forgerock.oauth2.core.exceptions.NotFoundException)2 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)2 LoginConfiguration (org.forgerock.openam.core.rest.authn.core.LoginConfiguration)2 LoginProcess (org.forgerock.openam.core.rest.authn.core.LoginProcess)2 RestAuthException (org.forgerock.openam.core.rest.authn.exceptions.RestAuthException)2