Search in sources :

Example 1 with OpenIdConnectClientRegistration

use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.

the class OpenAMScopeValidator method getUserInfo.

/**
     * {@inheritDoc}
     */
public UserInfoClaims getUserInfo(AccessToken token, OAuth2Request request) throws UnauthorizedClientException, NotFoundException {
    Map<String, Object> response = new HashMap<>();
    Bindings scriptVariables = new SimpleBindings();
    SSOToken ssoToken = getUsersSession(request);
    String realm;
    Set<String> scopes;
    AMIdentity id;
    OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    Map<String, Set<String>> requestedClaimsValues = gatherRequestedClaims(providerSettings, request, token);
    try {
        if (token != null) {
            OpenIdConnectClientRegistration clientRegistration;
            try {
                clientRegistration = clientRegistrationStore.get(token.getClientId(), request);
            } catch (InvalidClientException e) {
                logger.message("Unable to retrieve client from store.");
                throw new NotFoundException("No valid client registration found.");
            }
            final String subId = clientRegistration.getSubValue(token.getResourceOwnerId(), providerSettings);
            //data comes from token when we have one
            realm = token.getRealm();
            scopes = token.getScope();
            id = identityManager.getResourceOwnerIdentity(token.getResourceOwnerId(), realm);
            response.put(OAuth2Constants.JWTTokenParams.SUB, subId);
            response.put(OAuth2Constants.JWTTokenParams.UPDATED_AT, getUpdatedAt(token.getResourceOwnerId(), token.getRealm(), request));
        } else {
            //otherwise we're simply reading claims into the id_token, so grab it from the request/ssoToken
            realm = DNMapper.orgNameToRealmName(ssoToken.getProperty(ISAuthConstants.ORGANIZATION));
            id = identityManager.getResourceOwnerIdentity(ssoToken.getProperty(ISAuthConstants.USER_ID), realm);
            String scopeStr = request.getParameter(OAuth2Constants.Params.SCOPE);
            scopes = splitScope(scopeStr);
        }
        scriptVariables.put(OAuth2Constants.ScriptParams.SCOPES, getScriptFriendlyScopes(scopes));
        scriptVariables.put(OAuth2Constants.ScriptParams.IDENTITY, id);
        scriptVariables.put(OAuth2Constants.ScriptParams.LOGGER, logger);
        scriptVariables.put(OAuth2Constants.ScriptParams.CLAIMS, response);
        scriptVariables.put(OAuth2Constants.ScriptParams.SESSION, ssoToken);
        scriptVariables.put(OAuth2Constants.ScriptParams.REQUESTED_CLAIMS, requestedClaimsValues);
        ScriptObject script = getOIDCClaimsExtensionScript(realm);
        try {
            return scriptEvaluator.evaluateScript(script, scriptVariables);
        } catch (ScriptException e) {
            logger.message("Error running OIDC claims script", e);
            throw new ServerException("Error running OIDC claims script: " + e.getMessage());
        }
    } catch (ServerException e) {
        //API does not allow ServerExceptions to be thrown!
        throw new NotFoundException(e.getMessage());
    } catch (SSOException e) {
        throw new NotFoundException(e.getMessage());
    }
}
Also used : ScriptObject(org.forgerock.openam.scripting.ScriptObject) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) SSOToken(com.iplanet.sso.SSOToken) Set(java.util.Set) HashSet(java.util.HashSet) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AMHashMap(com.iplanet.am.sdk.AMHashMap) HashMap(java.util.HashMap) NotFoundException(org.forgerock.oauth2.core.exceptions.NotFoundException) SSOException(com.iplanet.sso.SSOException) SimpleBindings(javax.script.SimpleBindings) Bindings(javax.script.Bindings) ScriptException(javax.script.ScriptException) SimpleBindings(javax.script.SimpleBindings) AMIdentity(com.sun.identity.idm.AMIdentity) InvalidClientException(org.forgerock.oauth2.core.exceptions.InvalidClientException) JSONObject(org.json.JSONObject) ScriptObject(org.forgerock.openam.scripting.ScriptObject) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 2 with OpenIdConnectClientRegistration

use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.

the class OpenAMTokenStore method createAuthorizationCode.

/**
     * {@inheritDoc}
     */
public AuthorizationCode createAuthorizationCode(Set<String> scope, ResourceOwner resourceOwner, String clientId, String redirectUri, String nonce, OAuth2Request request, String codeChallenge, String codeChallengeMethod) throws ServerException, NotFoundException {
    logger.message("DefaultOAuthTokenStoreImpl::Creating Authorization code");
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String code = UUID.randomUUID().toString();
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAuthorizationCodeLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAuthorizationCodeLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final String ssoTokenId = getSsoTokenId(request);
    final OpenAMAuthorizationCode authorizationCode = new OpenAMAuthorizationCode(code, resourceOwner.getId(), clientId, redirectUri, scope, getClaimsFromRequest(request), expiryTime, nonce, realmNormaliser.normalise(request.<String>getParameter(REALM)), getAuthModulesFromSSOToken(request), getAuthenticationContextClassReferenceFromRequest(request), ssoTokenId, codeChallenge, codeChallengeMethod);
    // Store in CTS
    try {
        tokenStore.create(authorizationCode);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_AUTHORIZATION_CODE", authorizationCode.toString() };
            auditLogger.logAccessMessage("CREATED_AUTHORIZATION_CODE", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_AUTHORIZATION_CODE", authorizationCode.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_AUTHORIZATION_CODE", obs, null);
        }
        logger.error("Unable to create authorization code " + authorizationCode.getTokenInfo(), e);
        throw new ServerException("Could not create token in CTS");
    }
    request.setToken(AuthorizationCode.class, authorizationCode);
    return authorizationCode;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 3 with OpenIdConnectClientRegistration

use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.

the class ClientCredentialsReader method extractCredentials.

/**
     * Extracts the client's credentials from the OAuth2 request.
     *
     * @param request The OAuth2 request.
     * @param endpoint The endpoint this request should be for, or null to disable audience verification.
     * @return The client's credentials.
     * @throws InvalidRequestException If the request contains multiple client credentials.
     * @throws InvalidClientException If the request does not contain the client's id.
     */
public ClientCredentials extractCredentials(OAuth2Request request, String endpoint) throws InvalidRequestException, InvalidClientException, NotFoundException {
    final Request req = request.getRequest();
    boolean basicAuth = false;
    if (req.getChallengeResponse() != null) {
        basicAuth = true;
    }
    final ClientCredentials client;
    Client.TokenEndpointAuthMethod method = CLIENT_SECRET_POST;
    //jwt type first
    if (JWT_PROFILE_CLIENT_ASSERTION_TYPE.equalsIgnoreCase(request.<String>getParameter(CLIENT_ASSERTION_TYPE))) {
        client = verifyJwtBearer(request, basicAuth, endpoint);
        method = PRIVATE_KEY_JWT;
    } else {
        String clientId = request.getParameter(OAuth2Constants.Params.CLIENT_ID);
        String clientSecret = request.getParameter(OAuth2Constants.Params.CLIENT_SECRET);
        if (basicAuth && clientId != null) {
            logger.error("Client (" + clientId + ") using multiple authentication methods");
            throw new InvalidRequestException("Client authentication failed");
        }
        if (req.getChallengeResponse() != null) {
            final ChallengeResponse challengeResponse = req.getChallengeResponse();
            clientId = challengeResponse.getIdentifier();
            clientSecret = "";
            if (challengeResponse.getSecret() != null && challengeResponse.getSecret().length > 0) {
                clientSecret = String.valueOf(req.getChallengeResponse().getSecret());
            }
            method = CLIENT_SECRET_BASIC;
        }
        if (clientId == null || clientId.isEmpty()) {
            logger.error("Client Id is not set");
            throw failureFactory.getException(request, "Client authentication failed");
        }
        client = new ClientCredentials(clientId, clientSecret == null ? null : clientSecret.toCharArray(), false, basicAuth);
    }
    final OpenIdConnectClientRegistration cr = clientRegistrationStore.get(client.getClientId(), request);
    final Set<String> scopes = cr.getAllowedScopes();
    //if we're accessing the token endpoint, check we're authenticating using the appropriate method
    if (scopes.contains(OAuth2Constants.Params.OPENID) && req.getResourceRef().getLastSegment().equals(OAuth2Constants.Params.ACCESS_TOKEN) && !cr.getTokenEndpointAuthMethod().equals(method.getType())) {
        throw failureFactory.getException(request, "Invalid authentication method for accessing this endpoint.");
    }
    return client;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) TokenEndpointAuthMethod(org.forgerock.openidconnect.Client.TokenEndpointAuthMethod) Request(org.restlet.Request) OAuth2Request(org.forgerock.oauth2.core.OAuth2Request) InvalidRequestException(org.forgerock.oauth2.core.exceptions.InvalidRequestException) Client(org.forgerock.openidconnect.Client) ChallengeResponse(org.restlet.data.ChallengeResponse)

Example 4 with OpenIdConnectClientRegistration

use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.

the class OpenAMTokenStore method createRefreshToken.

@Override
public RefreshToken createRefreshToken(String grantType, String clientId, String resourceOwnerId, String redirectUri, Set<String> scope, OAuth2Request request, String validatedClaims) throws ServerException, NotFoundException {
    final String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    logger.message("Create refresh token");
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    final long lifeTime;
    if (clientRegistration == null) {
        lifeTime = providerSettings.getRefreshTokenLifetime();
    } else {
        lifeTime = clientRegistration.getRefreshTokenLifeTime(providerSettings);
    }
    long expiryTime = lifeTime < 0 ? -1 : lifeTime + System.currentTimeMillis();
    AuthorizationCode token = request.getToken(AuthorizationCode.class);
    String authModules = null;
    String acr = null;
    if (token != null) {
        authModules = token.getAuthModules();
        acr = token.getAuthenticationContextClassReference();
    }
    RefreshToken currentRefreshToken = request.getToken(RefreshToken.class);
    if (currentRefreshToken != null) {
        authModules = currentRefreshToken.getAuthModules();
        acr = currentRefreshToken.getAuthenticationContextClassReference();
    }
    OpenAMRefreshToken refreshToken = new OpenAMRefreshToken(id, resourceOwnerId, clientId, redirectUri, scope, expiryTime, OAuth2Constants.Bearer.BEARER, OAuth2Constants.Token.OAUTH_REFRESH_TOKEN, grantType, realm, authModules, acr, auditId);
    if (!StringUtils.isBlank(validatedClaims)) {
        refreshToken.setClaims(validatedClaims);
    }
    try {
        tokenStore.create(refreshToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logAccessMessage("CREATED_REFRESH_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_REFRESH_TOKEN", refreshToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_REFRESH_TOKEN", obs, null);
        }
        logger.error("Unable to create refresh token: " + refreshToken.getTokenInfo(), e);
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(RefreshToken.class, refreshToken);
    return refreshToken;
}
Also used : AuthorizationCode(org.forgerock.oauth2.core.AuthorizationCode) OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) RefreshToken(org.forgerock.oauth2.core.RefreshToken) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Example 5 with OpenIdConnectClientRegistration

use of org.forgerock.openidconnect.OpenIdConnectClientRegistration in project OpenAM by OpenRock.

the class OpenAMTokenStore method createAccessToken.

/**
     * {@inheritDoc}
     */
public AccessToken createAccessToken(String grantType, String accessTokenType, String authorizationCode, String resourceOwnerId, String clientId, String redirectUri, Set<String> scope, RefreshToken refreshToken, String nonce, String claims, OAuth2Request request) throws ServerException, NotFoundException {
    OpenIdConnectClientRegistration clientRegistration = getClientRegistration(clientId, request);
    final OAuth2ProviderSettings providerSettings = providerSettingsFactory.get(request);
    final String id = UUID.randomUUID().toString();
    final String auditId = UUID.randomUUID().toString();
    String realm = realmNormaliser.normalise(request.<String>getParameter(REALM));
    long expiryTime = 0;
    if (clientRegistration == null) {
        expiryTime = providerSettings.getAccessTokenLifetime() + System.currentTimeMillis();
    } else {
        expiryTime = clientRegistration.getAccessTokenLifeTime(providerSettings) + System.currentTimeMillis();
    }
    final AccessToken accessToken;
    if (refreshToken == null) {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, null, OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    } else {
        accessToken = new OpenAMAccessToken(id, authorizationCode, resourceOwnerId, clientId, redirectUri, scope, expiryTime, refreshToken.getTokenId(), OAuth2Constants.Token.OAUTH_ACCESS_TOKEN, grantType, nonce, realm, claims, auditId);
    }
    try {
        tokenStore.create(accessToken);
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "CREATED_TOKEN", accessToken.toString() };
            auditLogger.logAccessMessage("CREATED_TOKEN", obs, null);
        }
    } catch (CoreTokenException e) {
        logger.error("Could not create token in CTS: " + e.getMessage());
        if (auditLogger.isAuditLogEnabled()) {
            String[] obs = { "FAILED_CREATE_TOKEN", accessToken.toString() };
            auditLogger.logErrorMessage("FAILED_CREATE_TOKEN", obs, null);
        }
        throw new ServerException("Could not create token in CTS: " + e.getMessage());
    }
    request.setToken(AccessToken.class, accessToken);
    return accessToken;
}
Also used : OpenIdConnectClientRegistration(org.forgerock.openidconnect.OpenIdConnectClientRegistration) ServerException(org.forgerock.oauth2.core.exceptions.ServerException) AccessToken(org.forgerock.oauth2.core.AccessToken) CoreTokenException(org.forgerock.openam.cts.exceptions.CoreTokenException) OAuth2ProviderSettings(org.forgerock.oauth2.core.OAuth2ProviderSettings)

Aggregations

OpenIdConnectClientRegistration (org.forgerock.openidconnect.OpenIdConnectClientRegistration)6 OAuth2ProviderSettings (org.forgerock.oauth2.core.OAuth2ProviderSettings)5 ServerException (org.forgerock.oauth2.core.exceptions.ServerException)5 CoreTokenException (org.forgerock.openam.cts.exceptions.CoreTokenException)4 AMHashMap (com.iplanet.am.sdk.AMHashMap)1 SSOException (com.iplanet.sso.SSOException)1 SSOToken (com.iplanet.sso.SSOToken)1 AMIdentity (com.sun.identity.idm.AMIdentity)1 KeyPair (java.security.KeyPair)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Set (java.util.Set)1 Bindings (javax.script.Bindings)1 ScriptException (javax.script.ScriptException)1 SimpleBindings (javax.script.SimpleBindings)1 AccessToken (org.forgerock.oauth2.core.AccessToken)1 AuthorizationCode (org.forgerock.oauth2.core.AuthorizationCode)1 OAuth2Request (org.forgerock.oauth2.core.OAuth2Request)1 OAuth2Uris (org.forgerock.oauth2.core.OAuth2Uris)1 RefreshToken (org.forgerock.oauth2.core.RefreshToken)1