Search in sources :

Example 11 with UserIdNotFoundException

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

the class OAuthAdminServiceImpl method updateAppAndRevokeTokensAndAuthzCodes.

void updateAppAndRevokeTokensAndAuthzCodes(String consumerKey, Properties properties) throws IdentityOAuthAdminException {
    int countToken = 0;
    try {
        Set<AccessTokenDO> activeDetailedTokens = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getActiveAcessTokenDataByConsumerKey(consumerKey);
        String[] accessTokens = new String[activeDetailedTokens.size()];
        for (AccessTokenDO detailToken : activeDetailedTokens) {
            String token = detailToken.getAccessToken();
            accessTokens[countToken] = token;
            countToken++;
            OAuthCacheKey cacheKeyToken = new OAuthCacheKey(token);
            OAuthCache.getInstance().clearCacheEntry(cacheKeyToken);
            String scope = buildScopeString(detailToken.getScope());
            String authorizedUser = detailToken.getAuthzUser().getUserId();
            String authenticatedIDP = detailToken.getAuthzUser().getFederatedIdPName();
            boolean isUsernameCaseSensitive = IdentityUtil.isUserStoreInUsernameCaseSensitive(authorizedUser);
            String cacheKeyString;
            if (isUsernameCaseSensitive) {
                cacheKeyString = consumerKey + ":" + authorizedUser + ":" + scope + ":" + authenticatedIDP;
            } else {
                cacheKeyString = consumerKey + ":" + authorizedUser.toLowerCase() + ":" + scope + ":" + authenticatedIDP;
            }
            OAuthCacheKey cacheKeyUser = new OAuthCacheKey(cacheKeyString);
            OAuthCache.getInstance().clearCacheEntry(cacheKeyUser);
            String tokenBindingRef = NONE;
            if (detailToken.getTokenBinding() != null) {
                tokenBindingRef = detailToken.getTokenBinding().getBindingReference();
            }
            OAuthUtil.clearOAuthCache(consumerKey, detailToken.getAuthzUser(), OAuth2Util.buildScopeString(detailToken.getScope()), tokenBindingRef);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Access tokens and token of users are removed from the cache for OAuth App with " + "consumerKey: " + consumerKey);
        }
        Set<String> authorizationCodes = OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().getActiveAuthorizationCodesByConsumerKey(consumerKey);
        for (String authorizationCode : authorizationCodes) {
            OAuthCacheKey cacheKey = new OAuthCacheKey(authorizationCode);
            OAuthCache.getInstance().clearCacheEntry(cacheKey);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Access tokens are removed from the cache for OAuth App with consumerKey: " + consumerKey);
        }
        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().updateAppAndRevokeTokensAndAuthzCodes(consumerKey, properties, authorizationCodes.toArray(new String[0]), accessTokens);
    } catch (IdentityOAuth2Exception | IdentityApplicationManagementException | UserIdNotFoundException e) {
        throw handleError("Error in updating oauth app & revoking access tokens and authz " + "codes for OAuth App with consumerKey: " + consumerKey, e);
    }
}
Also used : AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) IdentityApplicationManagementException(org.wso2.carbon.identity.application.common.IdentityApplicationManagementException) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) OAuth2Util.buildScopeString(org.wso2.carbon.identity.oauth2.util.OAuth2Util.buildScopeString)

Example 12 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 doUserAuthorization.

/**
 * prompt : none
 * The Authorization Server MUST NOT display any authentication
 * or consent user interface pages. An error is returned if the
 * End-User is not already authenticated or the Client does not
 * have pre-configured consent for the requested scopes. This
 * can be used as a method to check for existing authentication
 * and/or consent.
 * <p/>
 * prompt : consent
 * The Authorization Server MUST prompt the End-User for consent before
 * returning information to the Client.
 * <p/>
 * prompt Error : consent_required
 * The Authorization Server requires End-User consent. This
 * error MAY be returned when the prompt parameter in the
 * Authorization Request is set to none to request that the
 * Authorization Server should not display any user
 * interfaces to the End-User, but the Authorization Request
 * cannot be completed without displaying a user interface
 * for End-User consent.
 *
 * @return String URL
 * @throws OAuthSystemException OAuthSystemException
 */
private String doUserAuthorization(OAuthMessage oAuthMessage, String sessionDataKeyFromLogin, OIDCSessionState sessionState) throws OAuthSystemException, ConsentHandlingFailedException, OAuthProblemException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    AuthenticatedUser authenticatedUser = getLoggedInUser(oAuthMessage);
    boolean hasUserApproved = isUserAlreadyApproved(oauth2Params, authenticatedUser);
    if (hasPromptContainsConsent(oauth2Params)) {
        // Remove any existing consents.
        String clientId = oauth2Params.getClientId();
        OpenIDConnectUserRPStore.getInstance().removeConsentForUser(authenticatedUser, clientId);
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oauth2Params.getClientId());
            params.put("prompt", oauth2Params.getPrompt());
            if (authenticatedUser != null) {
                try {
                    params.put("user", authenticatedUser.getUserId());
                } catch (UserIdNotFoundException e) {
                    if (StringUtils.isNotBlank(authenticatedUser.getAuthenticatedSubjectIdentifier())) {
                        params.put("user", authenticatedUser.getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
                    }
                }
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "'prompt' contains consent. Hence existing user consent is revoked.", "remove-user-consent", null);
        }
        if (log.isDebugEnabled()) {
            log.debug("Prompt parameter contains 'consent'. Existing consents for user: " + authenticatedUser.toFullQualifiedUsername() + " for oauth app with clientId: " + clientId + " are revoked and user will be prompted to give consent again.");
        }
        // Need to prompt for consent and get user consent for claims as well.
        return promptUserForConsent(sessionDataKeyFromLogin, oauth2Params, authenticatedUser, true, oAuthMessage);
    } else if (isPromptNone(oauth2Params)) {
        return handlePromptNone(oAuthMessage, sessionState, oauth2Params, authenticatedUser, hasUserApproved);
    } else if (isPromptLogin(oauth2Params) || isPromptParamsNotPresent(oauth2Params)) {
        return handleConsent(oAuthMessage, sessionDataKeyFromLogin, sessionState, oauth2Params, authenticatedUser, hasUserApproved);
    } else {
        return StringUtils.EMPTY;
    }
}
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) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 13 with UserIdNotFoundException

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

the class JDBCPermissionBasedInternalScopeValidator method getUserAllowedScopes.

private List<Scope> getUserAllowedScopes(AuthenticatedUser authenticatedUser, String[] requestedScopes, String clientId) {
    List<Scope> userAllowedScopes = new ArrayList<>();
    try {
        if (requestedScopes == null) {
            return new ArrayList<>();
        }
        boolean isSystemScope = ArrayUtils.contains(requestedScopes, SYSTEM_SCOPE);
        int tenantId = IdentityTenantUtil.getTenantId(authenticatedUser.getTenantDomain());
        startTenantFlow(authenticatedUser.getTenantDomain(), tenantId);
        AuthorizationManager authorizationManager = OAuthComponentServiceHolder.getInstance().getRealmService().getTenantUserRealm(tenantId).getAuthorizationManager();
        String[] allowedUIResourcesForUser;
        /*
            Here we handle scope validation for federated user and local user separately.
            For local users - user store is used to get user roles.
            For federated user - get user roles from user attributes.
            Note that if there is association between a federated user and local user () 'Assert identity using
            mapped local subject identifier' flag will be set as true. So authenticated user will be associated
            local user not federated user.
             */
        if (authenticatedUser.isFederatedUser()) {
            /*
                There is a flow where 'Assert identity using mapped local subject identifier' flag enabled but the
                federated user doesn't have any association in localIDP, to handle this case we check for 'Assert
                identity using mapped local subject identifier' flag and get roles from userStore.
                 */
            if (isSPAlwaysSendMappedLocalSubjectId(clientId)) {
                allowedUIResourcesForUser = getAllowedUIResourcesOfUser(authenticatedUser, authorizationManager);
            } else {
                // Handle not account associated federated users.
                allowedUIResourcesForUser = getAllowedUIResourcesForNotAssociatedFederatedUser(authenticatedUser, authorizationManager);
            }
        } else {
            allowedUIResourcesForUser = getAllowedUIResourcesOfUser(authenticatedUser, authorizationManager);
        }
        Set<Scope> allScopes = getScopesOfPermissionType(tenantId);
        if (ArrayUtils.contains(allowedUIResourcesForUser, ROOT) || ArrayUtils.contains(allowedUIResourcesForUser, PERMISSION_ROOT)) {
            return new ArrayList<>(allScopes);
        } else if (ArrayUtils.contains(allowedUIResourcesForUser, ADMIN_PERMISSION_ROOT)) {
            return new ArrayList<>(getAdminAllowedScopes(allScopes, requestedScopes));
        }
        for (Scope scope : allScopes) {
            if (!isSystemScope && !ArrayUtils.contains(requestedScopes, scope.getName())) {
                continue;
            }
            List<ScopeBinding> bindings = scope.getScopeBindings();
            boolean isScopeAllowed = true;
            for (ScopeBinding scopeBinding : bindings) {
                if (PERMISSION_BINDING_TYPE.equalsIgnoreCase(scopeBinding.getBindingType())) {
                    for (String binding : scopeBinding.getBindings()) {
                        boolean isAllowed = false;
                        for (String allowedScope : allowedUIResourcesForUser) {
                            if ((binding + "/").startsWith(allowedScope + "/")) {
                                isAllowed = true;
                                break;
                            }
                        }
                        if (!isAllowed) {
                            isScopeAllowed = false;
                            break;
                        }
                    }
                }
            }
            if (isScopeAllowed) {
                userAllowedScopes.add(scope);
            }
        }
    } catch (UserStoreException e) {
        log.error("Error while accessing Authorization Manager.", e);
    } catch (IdentityOAuth2Exception e) {
        log.error("Error while accessing identity provider manager.", e);
    } catch (IdentityOAuth2ScopeServerException e) {
        log.error("Error while retrieving oAuth2 scopes.", e);
    } catch (UserIdNotFoundException e) {
        log.error("User id not available for user: " + authenticatedUser.getLoggableUserId(), e);
    } finally {
        endTenantFlow();
    }
    return userAllowedScopes;
}
Also used : IdentityOAuth2ScopeServerException(org.wso2.carbon.identity.oauth2.IdentityOAuth2ScopeServerException) ArrayList(java.util.ArrayList) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) Scope(org.wso2.carbon.identity.oauth2.bean.Scope) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserStoreException(org.wso2.carbon.user.api.UserStoreException) AuthorizationManager(org.wso2.carbon.user.api.AuthorizationManager) ScopeBinding(org.wso2.carbon.identity.oauth2.bean.ScopeBinding)

Example 14 with UserIdNotFoundException

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

the class AccessTokenIssuer method getDefaultSubject.

private String getDefaultSubject(ServiceProvider serviceProvider, AuthenticatedUser authenticatedUser) throws UserIdNotFoundException {
    String subject;
    boolean useUserIdForDefaultSubject = false;
    ServiceProviderProperty[] spProperties = serviceProvider.getSpProperties();
    if (spProperties != null) {
        for (ServiceProviderProperty prop : spProperties) {
            if (IdentityApplicationConstants.USE_USER_ID_FOR_DEFAULT_SUBJECT.equals(prop.getName())) {
                useUserIdForDefaultSubject = Boolean.parseBoolean(prop.getValue());
                break;
            }
        }
    }
    if (useUserIdForDefaultSubject) {
        subject = authenticatedUser.getUserId();
    } else {
        subject = authenticatedUser.getUserName();
    }
    return subject;
}
Also used : ServiceProviderProperty(org.wso2.carbon.identity.application.common.model.ServiceProviderProperty)

Example 15 with UserIdNotFoundException

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

the class AbstractAuthorizationGrantHandler method issue.

@Override
public OAuth2AccessTokenRespDTO issue(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    String scope = OAuth2Util.buildScopeString(tokReqMsgCtx.getScope());
    String consumerKey = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
    String authorizedUserId;
    try {
        authorizedUserId = tokReqMsgCtx.getAuthorizedUser().getUserId();
    } catch (UserIdNotFoundException e) {
        throw new IdentityOAuth2Exception("User id is not available for user: " + tokReqMsgCtx.getAuthorizedUser().getLoggableUserId(), e);
    }
    String authenticatedIDP = OAuth2Util.getAuthenticatedIDP(tokReqMsgCtx.getAuthorizedUser());
    String tokenBindingReference = getTokenBindingReference(tokReqMsgCtx);
    OauthTokenIssuer oauthTokenIssuer;
    try {
        oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(consumerKey);
    } catch (InvalidOAuthClientException e) {
        throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + consumerKey, e);
    }
    synchronized ((consumerKey + ":" + authorizedUserId + ":" + scope + ":" + tokenBindingReference).intern()) {
        AccessTokenDO existingTokenBean = null;
        if (isHashDisabled) {
            existingTokenBean = getExistingToken(tokReqMsgCtx, getOAuthCacheKey(scope, consumerKey, authorizedUserId, authenticatedIDP, tokenBindingReference));
        }
        if (existingTokenBean != null) {
            if (log.isDebugEnabled()) {
                log.debug("Latest access token is found in the OAuthCache for the app: " + consumerKey);
            }
            if (accessTokenRenewedPerRequest(oauthTokenIssuer, tokReqMsgCtx)) {
                if (log.isDebugEnabled()) {
                    log.debug("TokenRenewalPerRequest is enabled. " + "Proceeding to revoke any existing active tokens and issue new token for client Id: " + consumerKey + ", user: " + authorizedUserId + " and scope: " + scope + ".");
                }
                return renewAccessToken(tokReqMsgCtx, scope, consumerKey, existingTokenBean, oauthTokenIssuer);
            }
            long expireTime = getAccessTokenExpiryTimeMillis(existingTokenBean);
            if (isExistingTokenValid(existingTokenBean, expireTime)) {
                if (log.isDebugEnabled()) {
                    log.debug("Existing token is active for client Id: " + consumerKey + ", user: " + authorizedUserId + " and scope: " + scope + ". Therefore issuing the same token.");
                }
                return issueExistingAccessToken(tokReqMsgCtx, scope, expireTime, existingTokenBean);
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("No active access token found for client Id: " + consumerKey + ", user: " + authorizedUserId + " and scope: " + scope + ". Therefore issuing new token.");
        }
        return generateNewAccessToken(tokReqMsgCtx, scope, consumerKey, existingTokenBean, true, oauthTokenIssuer);
    }
}
Also used : OauthTokenIssuer(org.wso2.carbon.identity.oauth2.token.OauthTokenIssuer) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) InvalidOAuthClientException(org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)

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