Search in sources :

Example 21 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handlePreConsent.

/**
 * Handle user consent from claims that will be shared in OIDC responses. Claims that require consent will be
 * sent to the consent page as query params. Consent page will interpret the query params and prompt the user
 * for consent.
 *
 * @param oauth2Params
 * @param user                Authenticated User
 * @param useExistingConsents Whether to consider existing user consents
 * @return
 * @throws ConsentHandlingFailedException
 * @throws OAuthSystemException
 */
private String handlePreConsent(OAuth2Parameters oauth2Params, AuthenticatedUser user, boolean useExistingConsents) throws ConsentHandlingFailedException, OAuthSystemException {
    String additionalQueryParam = StringUtils.EMPTY;
    String clientId = oauth2Params.getClientId();
    String spTenantDomain = oauth2Params.getTenantDomain();
    ServiceProvider serviceProvider = getServiceProvider(clientId);
    Map<String, Object> params = new HashMap<>();
    params.put("clientId", clientId);
    try {
        params.put("user", user.getUserId());
    } catch (UserIdNotFoundException e) {
        if (StringUtils.isNotBlank(user.getAuthenticatedSubjectIdentifier())) {
            params.put("user", user.getAuthenticatedSubjectIdentifier());
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Initiating consent handling for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
    }
    if (isConsentHandlingFromFrameworkSkipped(oauth2Params)) {
        if (log.isDebugEnabled()) {
            log.debug("Consent handling from framework skipped for client_id: " + clientId + " of tenantDomain: " + spTenantDomain + " for user: " + user.toFullQualifiedUsername());
        }
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> configs = new HashMap<>();
            configs.put("skipConsent", "true");
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "'skipConsent' is enabled for the OAuth client. Hence consent claims not generated.", "generate-consent-claims", configs);
        }
        return StringUtils.EMPTY;
    }
    try {
        ConsentClaimsData claimsForApproval = getConsentRequiredClaims(user, serviceProvider, useExistingConsents, oauth2Params);
        if (claimsForApproval != null) {
            String requestClaimsQueryParam = null;
            // Get the mandatory claims and append as query param.
            String mandatoryClaimsQueryParam = null;
            // Remove the claims which dont have values given by the user.
            claimsForApproval.setRequestedClaims(removeConsentRequestedNullUserAttributes(claimsForApproval.getRequestedClaims(), user.getUserAttributes(), spTenantDomain));
            List<ClaimMetaData> requestedOidcClaimsList = getRequestedOidcClaimsList(claimsForApproval, oauth2Params, spTenantDomain);
            if (CollectionUtils.isNotEmpty(requestedOidcClaimsList)) {
                requestClaimsQueryParam = REQUESTED_CLAIMS + "=" + buildConsentClaimString(requestedOidcClaimsList);
            }
            if (CollectionUtils.isNotEmpty(claimsForApproval.getMandatoryClaims())) {
                mandatoryClaimsQueryParam = MANDATORY_CLAIMS + "=" + buildConsentClaimString(claimsForApproval.getMandatoryClaims());
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> configs = new HashMap<>();
                List<String> requestedClaims = new ArrayList<>();
                requestedOidcClaimsList.forEach(claim -> requestedClaims.add(claim.getClaimUri()));
                List<String> mandatoryClaims = new ArrayList<>();
                claimsForApproval.getMandatoryClaims().forEach(claim -> mandatoryClaims.add(claim.getClaimUri()));
                configs.put("skipConsent", "false");
                configs.put("requestedClaims", requestedClaims);
                configs.put("mandatoryClaims", mandatoryClaims);
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Consent claims generation successful. Consent claims query parameter: " + additionalQueryParam, "generate-consent-claims", configs);
            }
            additionalQueryParam = buildQueryParamString(requestClaimsQueryParam, mandatoryClaimsQueryParam);
        }
    } catch (UnsupportedEncodingException | SSOConsentServiceException e) {
        String msg = "Error while handling user consent for claim for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain;
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", null);
        }
        throw new ConsentHandlingFailedException(msg, e);
    } catch (ClaimMetadataException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", null);
        }
        throw new ConsentHandlingFailedException("Error while getting claim mappings for " + OIDC_DIALECT, e);
    } catch (RequestObjectException e) {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "System error occurred.", "generate-consent-claims", null);
        }
        throw new ConsentHandlingFailedException("Error while getting essential claims for the session data key " + ": " + oauth2Params.getSessionDataKey(), e);
    }
    if (log.isDebugEnabled()) {
        log.debug("Additional Query param to be sent to consent page for user: " + user.toFullQualifiedUsername() + " for client_id: " + clientId + " is '" + additionalQueryParam + "'");
    }
    return additionalQueryParam;
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Example 22 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthCacheRemoveListener method entryRemoved.

@Override
public void entryRemoved(CacheEntryEvent<? extends OAuthCacheKey, ? extends CacheEntry> cacheEntryEvent) throws CacheEntryListenerException {
    CacheEntry cacheEntry = cacheEntryEvent.getValue();
    if (!(cacheEntry instanceof AccessTokenDO)) {
        return;
    }
    AccessTokenDO accessTokenDO = (AccessTokenDO) cacheEntry;
    if (StringUtils.equalsIgnoreCase(cacheEntryEvent.getKey().getCacheKeyString(), accessTokenDO.getAccessToken())) {
        if (log.isDebugEnabled()) {
            log.debug("OAuth cache removed for consumer id : " + accessTokenDO.getConsumerKey() + " and token " + "identifier: " + accessTokenDO.getTokenId());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("OAuth cache removed for cache key: " + cacheEntryEvent.getKey().getCacheKeyString());
        }
    }
    OAuthCache oauthCache = OAuthCache.getInstance();
    OAuthCacheKey oauthcacheKey = new OAuthCacheKey(accessTokenDO.getAccessToken());
    oauthCache.clearCacheEntry(oauthcacheKey, accessTokenDO.getAuthzUser().getTenantDomain());
    try {
        String userId = accessTokenDO.getAuthzUser().getUserId();
        String cacheKeyString;
        cacheKeyString = accessTokenDO.getConsumerKey() + ":" + userId + ":" + OAuth2Util.buildScopeString(accessTokenDO.getScope()) + ":" + accessTokenDO.getAuthzUser().getFederatedIdPName();
        oauthcacheKey = new OAuthCacheKey(cacheKeyString);
        oauthCache.clearCacheEntry(oauthcacheKey);
    } catch (UserIdNotFoundException e) {
        throw new CacheEntryListenerException("User id not found for user: " + accessTokenDO.getAuthzUser().getLoggableUserId());
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) OAuthCache(org.wso2.carbon.identity.oauth.cache.OAuthCache) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) CacheEntry(org.wso2.carbon.identity.oauth.cache.CacheEntry) CacheEntryListenerException(javax.cache.event.CacheEntryListenerException)

Example 23 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuthUtil method clearOAuthCache.

/**
 * @deprecated use {@link #clearOAuthCache(String, AuthenticatedUser)} instead.
 * @param consumerKey
 * @param authorizedUser
 */
@Deprecated
public static void clearOAuthCache(String consumerKey, User authorizedUser) {
    if (authorizedUser instanceof AuthenticatedUser) {
        clearOAuthCache(consumerKey, (AuthenticatedUser) authorizedUser);
    } else {
        if (LOG.isDebugEnabled()) {
            LOG.debug("User object is not an instance of AuthenticatedUser therefore cannot resolve " + "authenticatedIDP name.");
        }
        AuthenticatedUser authenticatedUser = new AuthenticatedUser(authorizedUser);
        String userId;
        try {
            userId = authenticatedUser.getUserId();
        } catch (UserIdNotFoundException e) {
            LOG.error("User id cannot be found for user: " + authenticatedUser.getLoggableUserId());
            return;
        }
        clearOAuthCache(consumerKey, userId);
        clearOAuthCacheWithAuthenticatedIDP(consumerKey, userId, null);
    }
}
Also used : UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 24 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method handleAuthenticationResponse.

private Response handleAuthenticationResponse(OAuthMessage oAuthMessage) throws OAuthSystemException, URISyntaxException, ConsentHandlingFailedException {
    if (LoggerUtils.isDiagnosticLogsEnabled()) {
        Map<String, Object> requestParams = new HashMap<>();
        if (oAuthMessage.getRequest() != null && MapUtils.isNotEmpty(oAuthMessage.getRequest().getParameterMap())) {
            oAuthMessage.getRequest().getParameterMap().forEach((key, value) -> {
                if (ArrayUtils.isNotEmpty(value)) {
                    requestParams.put(key, Arrays.asList(value));
                }
            });
        }
        LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, requestParams, OAuthConstants.LogConstants.SUCCESS, "Received authentication response from Framework.", "receive-authn-response", null);
    }
    updateAuthTimeInSessionDataCacheEntry(oAuthMessage);
    addSessionDataKeyToSessionDataCacheEntry(oAuthMessage);
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oauth2Params.getClientId());
    setSPAttributeToRequest(oAuthMessage.getRequest(), oauth2Params.getApplicationName(), tenantDomain);
    String sessionDataKeyFromLogin = getSessionDataKeyFromLogin(oAuthMessage);
    AuthenticationResult authnResult = getAuthenticationResult(oAuthMessage, sessionDataKeyFromLogin);
    if (isAuthnResultFound(authnResult)) {
        removeAuthenticationResult(oAuthMessage, sessionDataKeyFromLogin);
        if (authnResult.isAuthenticated()) {
            String userIdentifier = null;
            if (authnResult.getSubject() != null) {
                try {
                    userIdentifier = authnResult.getSubject().getUserId();
                } catch (UserIdNotFoundException e) {
                    if (StringUtils.isNotBlank(authnResult.getSubject().getAuthenticatedSubjectIdentifier())) {
                        userIdentifier = authnResult.getSubject().getAuthenticatedSubjectIdentifier().replaceAll(".", "*");
                    }
                }
            }
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", oAuthMessage.getClientId());
                if (userIdentifier != null) {
                    params.put("authenticatedUser", userIdentifier);
                }
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Authentication is successful.", "validate-authn-status", null);
            }
            return handleSuccessfulAuthentication(oAuthMessage, oauth2Params, authnResult);
        } else {
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> params = new HashMap<>();
                params.put("clientId", oAuthMessage.getClientId());
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Authentication failed.", "validate-authn-status", null);
            }
            return handleFailedAuthentication(oAuthMessage, oauth2Params, authnResult);
        }
    } else {
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oAuthMessage.getClientId());
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Authentication status is empty.", "validate-authn-status", null);
        }
        return handleEmptyAuthenticationResult(oAuthMessage);
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult)

Example 25 with UserIdNotFoundException

use of org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException in project identity-inbound-auth-oauth by wso2-extensions.

the class RoleBasedInternalScopeValidator method getRolesOfTheUser.

private List<String> getRolesOfTheUser(AuthenticatedUser authenticatedUser) throws IdentityOAuth2Exception {
    try {
        RealmService realmService = OAuthComponentServiceHolder.getInstance().getRealmService();
        int tenantId = realmService.getTenantManager().getTenantId(authenticatedUser.getTenantDomain());
        AbstractUserStoreManager userStoreManager = (AbstractUserStoreManager) realmService.getTenantUserRealm(tenantId).getUserStoreManager();
        String userName = userStoreManager.getUserNameFromUserID(authenticatedUser.getUserId());
        return userStoreManager.getHybridRoleListOfUser(userName, authenticatedUser.getUserStoreDomain());
    } catch (UserStoreException e) {
        String error = "Error occurred while getting roles of the user: " + authenticatedUser.getLoggableUserId();
        throw new IdentityOAuth2Exception(error, e);
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("User id not available for user: " + authenticatedUser.getLoggableUserId(), e);
    }
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) RealmService(org.wso2.carbon.user.core.service.RealmService) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AbstractUserStoreManager(org.wso2.carbon.user.core.common.AbstractUserStoreManager) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)

Aggregations

UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)29 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)14 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)9 HashMap (java.util.HashMap)8 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)7 UserStoreException (org.wso2.carbon.user.api.UserStoreException)7 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)6 AbstractUserStoreManager (org.wso2.carbon.user.core.common.AbstractUserStoreManager)6 OAuth2AuthorizeReqDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO)5 ArrayList (java.util.ArrayList)4 FrameworkException (org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException)4 RealmService (org.wso2.carbon.user.core.service.RealmService)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)3 OAuthSystemException (org.apache.oltu.oauth2.common.exception.OAuthSystemException)3 JSONObject (org.json.JSONObject)3 ClaimMapping (org.wso2.carbon.identity.application.common.model.ClaimMapping)3 Timestamp (java.sql.Timestamp)2 Date (java.util.Date)2 SequenceConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.SequenceConfig)2 StepConfig (org.wso2.carbon.identity.application.authentication.framework.config.model.StepConfig)2