Search in sources :

Example 1 with CacheEntry

use of org.wso2.carbon.identity.core.cache.CacheEntry in project carbon-apimgt by wso2.

the class SystemScopesIssuer method validateScope.

@Override
public boolean validateScope(OAuth2TokenValidationMessageContext oAuth2TokenValidationMessageContext) throws IdentityOAuth2Exception {
    AccessTokenDO accessTokenDO = (AccessTokenDO) oAuth2TokenValidationMessageContext.getProperty(ACCESS_TOKEN_DO);
    if (accessTokenDO == null) {
        return false;
    }
    String resource = getResourceFromMessageContext(oAuth2TokenValidationMessageContext);
    // Return true if there is no resource to validate the token against.
    if (resource == null) {
        return true;
    }
    // Get the list of scopes associated with the access token
    String[] scopes = accessTokenDO.getScope();
    // If no scopes are associated with the token
    if (scopes == null || scopes.length == 0) {
        return true;
    }
    String resourceScope = null;
    int resourceTenantId = -1;
    boolean cacheHit = false;
    // Check the cache, if caching is enabled.
    OAuthCacheKey cacheKey = new OAuthCacheKey(resource);
    CacheEntry result = OAuthCache.getInstance().getValueFromCache(cacheKey);
    // Cache hit
    if (result != null && result instanceof ResourceScopeCacheEntry) {
        resourceScope = ((ResourceScopeCacheEntry) result).getScope();
        resourceTenantId = ((ResourceScopeCacheEntry) result).getTenantId();
        cacheHit = true;
    }
    // Cache was not hit. So retrieve from database.
    if (!cacheHit) {
        Pair<String, Integer> scopeMap = OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().findTenantAndScopeOfResource(resource);
        if (scopeMap != null) {
            resourceScope = scopeMap.getLeft();
            resourceTenantId = scopeMap.getRight();
        }
        cacheKey = new OAuthCacheKey(resource);
        ResourceScopeCacheEntry cacheEntry = new ResourceScopeCacheEntry(resourceScope);
        cacheEntry.setTenantId(resourceTenantId);
        // Store resourceScope in cache even if it is null (to avoid database calls when accessing resources for
        // which scopes haven't been defined).
        OAuthCache.getInstance().addToCache(cacheKey, cacheEntry);
    }
    // Return TRUE if - There does not exist a scope definition for the resource
    if (resourceScope == null) {
        if (log.isDebugEnabled()) {
            log.debug("Resource '" + resource + "' is not protected with a scope");
        }
        return true;
    }
    List<String> scopeList = new ArrayList<>(Arrays.asList(scopes));
    // If the access token does not bear the scope required for accessing the Resource.
    if (!scopeList.contains(resourceScope)) {
        if (log.isDebugEnabled() && IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
            log.debug("Access token '" + accessTokenDO.getAccessToken() + "' does not bear the scope '" + resourceScope + "'");
        }
        return false;
    }
    // This system property is set at server start using -D option, Thus will be a permanent property.
    if (accessTokenDO.getAuthzUser().isFederatedUser() && (Boolean.parseBoolean(System.getProperty(CHECK_ROLES_FROM_SAML_ASSERTION)) || !(Boolean.parseBoolean(System.getProperty(RETRIEVE_ROLES_FROM_USERSTORE_FOR_SCOPE_VALIDATION))))) {
        return true;
    }
    AuthenticatedUser authenticatedUser = OAuthUtil.getAuthenticatedUser(oAuth2TokenValidationMessageContext.getResponseDTO().getAuthorizedUser());
    String clientId = accessTokenDO.getConsumerKey();
    List<String> requestedScopes = Arrays.asList(scopes);
    List<String> authorizedScopes = null;
    String[] userRoles = null;
    Map<String, String> appScopes = getAppScopes(clientId, authenticatedUser, requestedScopes);
    if (appScopes != null) {
        // If no scopes can be found in the context of the application
        if (isAppScopesEmpty(appScopes, clientId)) {
            authorizedScopes = getAllowedScopes(requestedScopes);
            oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
            return true;
        }
        userRoles = getUserRoles(authenticatedUser);
        authorizedScopes = getAuthorizedScopes(userRoles, requestedScopes, appScopes);
        oAuth2TokenValidationMessageContext.getResponseDTO().setScope(authorizedScopes.toArray(new String[authorizedScopes.size()]));
    }
    if (ArrayUtils.isEmpty(userRoles)) {
        if (log.isDebugEnabled()) {
            log.debug("No roles associated for the user " + authenticatedUser.getUserName());
        }
        return false;
    }
    return true;
}
Also used : ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry) CacheEntry(org.wso2.carbon.identity.oauth.cache.CacheEntry) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) OAuthCacheKey(org.wso2.carbon.identity.oauth.cache.OAuthCacheKey) ResourceScopeCacheEntry(org.wso2.carbon.identity.oauth2.model.ResourceScopeCacheEntry)

Example 2 with CacheEntry

use of org.wso2.carbon.identity.core.cache.CacheEntry in project carbon-identity-framework by wso2.

the class CacheBackedLongWaitStatusDAO method getWaitStatus.

public LongWaitStatus getWaitStatus(String waitKey) throws FrameworkException {
    LongWaitStatus status = null;
    LongWaitResultCacheEntry valueFromCache = LongWaitResultCache.getInstance().getValueFromCache(new LongWaitResultCacheKey(waitKey));
    if (valueFromCache != null) {
        status = valueFromCache.getWaitStatus();
    }
    if (status == null) {
        status = waitStatusDAO.getWaitStatus(waitKey);
        LongWaitResultCacheKey cacheKey = new LongWaitResultCacheKey(waitKey);
        LongWaitResultCacheEntry cacheEntry = new LongWaitResultCacheEntry(status);
        LongWaitResultCache.getInstance().addToCache(cacheKey, cacheEntry);
    }
    return status;
}
Also used : LongWaitResultCacheKey(org.wso2.carbon.identity.application.authentication.framework.cache.LongWaitResultCacheKey) LongWaitStatus(org.wso2.carbon.identity.application.authentication.framework.model.LongWaitStatus) LongWaitResultCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.LongWaitResultCacheEntry)

Example 3 with CacheEntry

use of org.wso2.carbon.identity.core.cache.CacheEntry in project carbon-identity-framework by wso2.

the class FrameworkUtils method addAuthenticationContextToCache.

/**
 * @param contextId
 * @param context
 */
public static void addAuthenticationContextToCache(String contextId, AuthenticationContext context) {
    AuthenticationContextCacheKey cacheKey = new AuthenticationContextCacheKey(contextId);
    AuthenticationContextCacheEntry cacheEntry = new AuthenticationContextCacheEntry(context);
    cacheEntry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
    AuthenticationContextCache.getInstance().addToCache(cacheKey, cacheEntry);
}
Also used : AuthenticationContextCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCacheEntry) AuthenticationContextCacheKey(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationContextCacheKey)

Example 4 with CacheEntry

use of org.wso2.carbon.identity.core.cache.CacheEntry in project carbon-identity-framework by wso2.

the class FrameworkUtils method getCommonAuthReqWithParams.

/**
 * Builds the wrapper, wrapping incoming request and information take from cache entry.
 *
 * @param request    Original request coming to authentication framework
 * @param cacheEntry Cache entry from the cache, which is added from calling servlets
 * @return
 */
public static HttpServletRequest getCommonAuthReqWithParams(HttpServletRequest request, AuthenticationRequestCacheEntry cacheEntry) {
    // add this functionality as a constructor
    Map<String, String[]> modifiableParameters = new TreeMap<String, String[]>();
    if (cacheEntry != null) {
        AuthenticationRequest authenticationRequest = cacheEntry.getAuthenticationRequest();
        if (!authenticationRequest.getRequestQueryParams().isEmpty()) {
            modifiableParameters.putAll(authenticationRequest.getRequestQueryParams());
        }
        // Adding field variables to wrapper
        if (authenticationRequest.getType() != null) {
            modifiableParameters.put(FrameworkConstants.RequestParams.TYPE, new String[] { authenticationRequest.getType() });
        }
        if (authenticationRequest.getCommonAuthCallerPath() != null) {
            modifiableParameters.put(FrameworkConstants.RequestParams.CALLER_PATH, new String[] { authenticationRequest.getCommonAuthCallerPath() });
        }
        if (authenticationRequest.getRelyingParty() != null) {
            modifiableParameters.put(FrameworkConstants.RequestParams.ISSUER, new String[] { authenticationRequest.getRelyingParty() });
        }
        if (authenticationRequest.getTenantDomain() != null && !IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            modifiableParameters.put(FrameworkConstants.RequestParams.TENANT_DOMAIN, new String[] { authenticationRequest.getTenantDomain() });
        }
        modifiableParameters.put(FrameworkConstants.RequestParams.FORCE_AUTHENTICATE, new String[] { String.valueOf(authenticationRequest.getForceAuth()) });
        modifiableParameters.put(FrameworkConstants.RequestParams.PASSIVE_AUTHENTICATION, new String[] { String.valueOf(authenticationRequest.getPassiveAuth()) });
        if (log.isDebugEnabled()) {
            StringBuilder queryStringBuilder = new StringBuilder("");
            for (Map.Entry<String, String[]> entry : modifiableParameters.entrySet()) {
                StringBuilder paramValueBuilder = new StringBuilder("");
                String[] paramValueArr = entry.getValue();
                if (paramValueArr != null) {
                    for (String paramValue : paramValueArr) {
                        paramValueBuilder.append("{").append(paramValue).append("}");
                    }
                }
                queryStringBuilder.append("\n").append(entry.getKey() + "=" + paramValueBuilder.toString());
            }
            log.debug("\nInbound Request parameters: " + queryStringBuilder.toString());
        }
        return new AuthenticationFrameworkWrapper(request, modifiableParameters, authenticationRequest.getRequestHeaders());
    }
    return request;
}
Also used : TreeMap(java.util.TreeMap) AuthenticationRequest(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationRequest) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) AuthenticationFrameworkWrapper(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationFrameworkWrapper)

Example 5 with CacheEntry

use of org.wso2.carbon.identity.core.cache.CacheEntry in project carbon-identity-framework by wso2.

the class FrameworkUtils method addAuthenticationResultToCache.

/**
 * @param key
 * @param authenticationResult
 */
public static void addAuthenticationResultToCache(String key, AuthenticationResult authenticationResult) {
    AuthenticationResultCacheKey cacheKey = new AuthenticationResultCacheKey(key);
    AuthenticationResultCacheEntry cacheEntry = new AuthenticationResultCacheEntry();
    cacheEntry.setResult(authenticationResult);
    cacheEntry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getOperationCleanUpTimeout()));
    AuthenticationResultCache.getInstance().addToCache(cacheKey, cacheEntry);
}
Also used : AuthenticationResultCacheEntry(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheEntry) AuthenticationResultCacheKey(org.wso2.carbon.identity.application.authentication.framework.cache.AuthenticationResultCacheKey)

Aggregations

AuthorizationGrantCacheKey (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey)12 AuthorizationGrantCacheEntry (org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry)11 CacheEntry (org.wso2.carbon.identity.oauth.cache.CacheEntry)10 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)9 HashMap (java.util.HashMap)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Test (org.testng.annotations.Test)7 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)7 OIDCSessionDataCacheEntry (org.wso2.carbon.identity.oidc.session.cache.OIDCSessionDataCacheEntry)6 BeforeTest (org.testng.annotations.BeforeTest)5 PowerMockIdentityBaseTest (org.wso2.carbon.identity.testutil.powermock.PowerMockIdentityBaseTest)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 SessionContextCacheEntry (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheEntry)4 SessionContextCacheKey (org.wso2.carbon.identity.application.authentication.framework.cache.SessionContextCacheKey)4 SessionContext (org.wso2.carbon.identity.application.authentication.framework.context.SessionContext)4 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 IdentityCacheEntry (org.wso2.carbon.identity.entitlement.cache.IdentityCacheEntry)3 IdentityCacheKey (org.wso2.carbon.identity.entitlement.cache.IdentityCacheKey)3 ParseException (java.text.ParseException)2 ArrayList (java.util.ArrayList)2