Search in sources :

Example 1 with IdentityOAuth2Exception

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception in project carbon-apimgt by wso2.

the class SystemScopesIssuer method configureForJWTGrant.

protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
    SignedJWT signedJWT = null;
    JWTClaimsSet claimsSet = null;
    String[] roles = null;
    try {
        signedJWT = getSignedJWT(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        log.error("Couldn't retrieve signed JWT", e);
    }
    if (signedJWT != null) {
        claimsSet = getClaimSet(signedJWT);
    }
    String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
    String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
    try {
        identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
        if (identityProvider != null) {
            if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                if (identityProvider == null) {
                    log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                }
            }
        } else {
            log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
        }
    } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
        log.error("Couldn't initiate identity provider instance", e);
    }
    try {
        roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
    } catch (ParseException e) {
        log.error("Couldn't retrieve roles:", e);
    }
    List<String> updatedRoles = new ArrayList<>();
    if (roles != null) {
        for (String role : roles) {
            String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
            if (updatedRoleClaimValue != null) {
                updatedRoles.add(updatedRoleClaimValue);
            } else {
                updatedRoles.add(role);
            }
        }
    }
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
    String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
    if (roleClaim != null) {
        userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
        tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
    }
    user.setUserAttributes(userAttributes);
    tokReqMsgCtx.setAuthorizedUser(user);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 2 with IdentityOAuth2Exception

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception in project carbon-apimgt by wso2.

the class SystemScopesIssuer method getSignedJWT.

/**
 * Method to parse the assertion and retrieve the signed JWT
 *
 * @param tokReqMsgCtx request
 * @return SignedJWT object
 * @throws IdentityOAuth2Exception exception thrown due to a parsing error
 */
private SignedJWT getSignedJWT(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    RequestParameter[] params = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
    String assertion = null;
    SignedJWT signedJWT;
    for (RequestParameter param : params) {
        if (param.getKey().equals(APIConstants.SystemScopeConstants.OAUTH_JWT_ASSERTION)) {
            assertion = param.getValue()[0];
            break;
        }
    }
    if (StringUtils.isEmpty(assertion)) {
        String errorMessage = "Error while retrieving assertion";
        throw new IdentityOAuth2Exception(errorMessage);
    }
    try {
        signedJWT = SignedJWT.parse(assertion);
        if (log.isDebugEnabled()) {
            log.debug(signedJWT);
        }
    } catch (ParseException e) {
        String errorMessage = "Error while parsing the JWT.";
        throw new IdentityOAuth2Exception(errorMessage, e);
    }
    return signedJWT;
}
Also used : IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) RequestParameter(org.wso2.carbon.identity.oauth2.model.RequestParameter) SignedJWT(com.nimbusds.jwt.SignedJWT) ParseException(java.text.ParseException)

Example 3 with IdentityOAuth2Exception

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception 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 4 with IdentityOAuth2Exception

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception in project carbon-apimgt by wso2.

the class SystemScopeIssuerImplTest method init.

@Before
public void init() throws IdentityOAuth2Exception {
    systemScopesIssuer = Mockito.mock(SystemScopesIssuer.class);
    oAuth2AuthorizeReqDTO = new OAuth2AuthorizeReqDTO();
    String[] scopes = { "test", "test1" };
    restAPIScopes.put("test", "test");
    authenticatedUser = Mockito.mock(AuthenticatedUser.class);
    Mockito.when(systemScopesIssuer.getAppScopes(Mockito.anyString(), Mockito.anyObject(), Mockito.anyList())).thenReturn(restAPIScopes);
    Mockito.when(systemScopesIssuer.validateScope((OAuthAuthzReqMessageContext) Mockito.anyObject())).thenReturn(true);
    oAuth2AuthorizeReqDTO.setScopes(scopes);
    oAuth2AuthorizeReqDTO.setUser(authenticatedUser);
    oAuthAuthzReqMessageContext = new OAuthAuthzReqMessageContext(oAuth2AuthorizeReqDTO);
    oAuth2AccessTokenReqDTO = new OAuth2AccessTokenReqDTO();
    oAuth2AccessTokenReqDTO.setScope(scopes);
    oAuthTokenReqMessageContext = new OAuthTokenReqMessageContext(oAuth2AccessTokenReqDTO);
    Mockito.when(systemScopesIssuer.validateScope((OAuthTokenReqMessageContext) Mockito.anyObject())).thenReturn(true);
    oAuth2TokenValidationRequestDTO = new OAuth2TokenValidationRequestDTO();
    oAuth2TokenValidationResponseDTO = new OAuth2TokenValidationResponseDTO();
    oAuth2TokenValidationMessageContext = new OAuth2TokenValidationMessageContext(oAuth2TokenValidationRequestDTO, oAuth2TokenValidationResponseDTO);
    Mockito.when(systemScopesIssuer.validateScope((OAuth2TokenValidationMessageContext) Mockito.anyObject())).thenReturn(true);
}
Also used : OAuth2TokenValidationMessageContext(org.wso2.carbon.identity.oauth2.validators.OAuth2TokenValidationMessageContext) OAuthTokenReqMessageContext(org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext) OAuthAuthzReqMessageContext(org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext) OAuth2AuthorizeReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeReqDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) OAuth2AccessTokenReqDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) Before(org.junit.Before)

Example 5 with IdentityOAuth2Exception

use of org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception in project carbon-apimgt by wso2.

the class SessionDataPublisherImpl method publishSessionTermination.

/**
 * Overridden method which implements the access token revocation
 * @param request termination request
 * @param context termination context
 * @param sessionContext termination sessionContext
 * @param params termination params
 */
@Override
public void publishSessionTermination(HttpServletRequest request, AuthenticationContext context, SessionContext sessionContext, Map<String, Object> params) {
    OAuthConsumerAppDTO[] appDTOs = new OAuthConsumerAppDTO[0];
    List<OAuthConsumerAppDTO> revokeAppList = new ArrayList<>();
    AuthenticatedUser authenticatedUser = (AuthenticatedUser) params.get(user);
    String username = authenticatedUser.getUserName();
    String tenantDomain = authenticatedUser.getTenantDomain();
    String userStoreDomain = authenticatedUser.getUserStoreDomain();
    AuthenticatedUser federatedUser;
    SystemApplicationDTO[] systemApplicationDTOS = new SystemApplicationDTO[0];
    if (authenticatedUser.isFederatedUser()) {
        try {
            federatedUser = buildAuthenticatedUser(authenticatedUser);
            authenticatedUser = federatedUser;
        } catch (IdentityOAuth2Exception e) {
            log.error("Error thrown while building authenticated user in logout flow for user " + authenticatedUser.getUserName(), e);
        }
    }
    SystemApplicationDAO systemApplicationDAO = new SystemApplicationDAO();
    try {
        systemApplicationDTOS = systemApplicationDAO.getApplications(tenantDomain);
        if (systemApplicationDTOS.length < 0) {
            if (log.isDebugEnabled()) {
                log.debug("The tenant: " + tenantDomain + " doesn't have any system apps");
            }
        }
    } catch (APIMgtDAOException e) {
        log.error("Error thrown while retrieving system applications for the tenant domain " + tenantDomain, e);
    }
    try {
        appDTOs = getAppsAuthorizedByUser(authenticatedUser);
        if (appDTOs.length > 0) {
            if (log.isDebugEnabled()) {
                log.debug("The user: " + authenticatedUser.getUserName() + " has " + appDTOs.length + " OAuth apps");
            }
        }
    } catch (IdentityOAuthAdminException e) {
        log.error("Error while retrieving applications authorized for the user " + authenticatedUser.getUserName(), e);
    }
    for (OAuthConsumerAppDTO appDTO : appDTOs) {
        for (SystemApplicationDTO systemApplicationDTO : systemApplicationDTOS) {
            if (StringUtils.equalsIgnoreCase(appDTO.getOauthConsumerKey(), systemApplicationDTO.getConsumerKey())) {
                revokeAppList.add(appDTO);
            }
        }
    }
    for (OAuthConsumerAppDTO appDTO : revokeAppList) {
        Set<AccessTokenDO> accessTokenDOs = null;
        try {
            // Retrieve all ACTIVE or EXPIRED access tokens for particular client authorized by this user
            accessTokenDOs = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getAccessTokens(appDTO.getOauthConsumerKey(), authenticatedUser, authenticatedUser.getUserStoreDomain(), true);
        } catch (IdentityOAuth2Exception e) {
            log.error("Error while retrieving access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
        }
        AuthenticatedUser authzUser;
        if (accessTokenDOs != null) {
            for (AccessTokenDO accessTokenDO : accessTokenDOs) {
                // Clear cache with AccessTokenDO
                authzUser = accessTokenDO.getAuthzUser();
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()), "NONE");
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser, OAuth2Util.buildScopeString(accessTokenDO.getScope()));
                OAuthUtil.clearOAuthCache(accessTokenDO.getConsumerKey(), authzUser);
                OAuthUtil.clearOAuthCache(accessTokenDO.getAccessToken());
                Cache restApiTokenCache = CacheProvider.getRESTAPITokenCache();
                if (restApiTokenCache != null) {
                    restApiTokenCache.remove(accessTokenDO.getAccessToken());
                }
                AccessTokenDO scopedToken = null;
                try {
                    // Retrieve latest access token for particular client, user and scope combination if
                    // its ACTIVE or EXPIRED.
                    scopedToken = OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().getLatestAccessToken(appDTO.getOauthConsumerKey(), authenticatedUser, userStoreDomain, OAuth2Util.buildScopeString(accessTokenDO.getScope()), true);
                } catch (IdentityOAuth2Exception e) {
                    log.error("Error while retrieving scoped access tokens for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                }
                if (scopedToken != null) {
                    // Revoking token from database
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getAccessTokenDAO().revokeAccessTokens(new String[] { scopedToken.getAccessToken() });
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                    // Revoking the oauth consent from database.
                    try {
                        OAuthTokenPersistenceFactory.getInstance().getTokenManagementDAO().revokeOAuthConsentByApplicationAndUser(authzUser.getAuthenticatedSubjectIdentifier(), tenantDomain, username);
                    } catch (IdentityOAuth2Exception e) {
                        log.error("Error while revoking access tokens related for the application " + appDTO.getApplicationName() + "and the for user " + authenticatedUser.getUserName(), e);
                    }
                }
            }
        }
    }
}
Also used : IdentityOAuthAdminException(org.wso2.carbon.identity.oauth.IdentityOAuthAdminException) APIMgtDAOException(org.wso2.carbon.apimgt.api.APIMgtDAOException) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) AccessTokenDO(org.wso2.carbon.identity.oauth2.model.AccessTokenDO) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) SystemApplicationDTO(org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO) SystemApplicationDAO(org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO) Cache(javax.cache.Cache)

Aggregations

AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)5 IdentityOAuth2Exception (org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception)5 AccessTokenDO (org.wso2.carbon.identity.oauth2.model.AccessTokenDO)3 SignedJWT (com.nimbusds.jwt.SignedJWT)2 ParseException (java.text.ParseException)2 APIMgtDAOException (org.wso2.carbon.apimgt.api.APIMgtDAOException)2 SystemApplicationDAO (org.wso2.carbon.apimgt.impl.dao.SystemApplicationDAO)2 SystemApplicationDTO (org.wso2.carbon.apimgt.impl.dto.SystemApplicationDTO)2 IdentityOAuthAdminException (org.wso2.carbon.identity.oauth.IdentityOAuthAdminException)2 OAuthConsumerAppDTO (org.wso2.carbon.identity.oauth.dto.OAuthConsumerAppDTO)2 IdentityProviderManagementException (org.wso2.carbon.idp.mgt.IdentityProviderManagementException)2 JWTClaimsSet (com.nimbusds.jwt.JWTClaimsSet)1 Cache (javax.cache.Cache)1 Before (org.junit.Before)1 IdentityApplicationManagementException (org.wso2.carbon.identity.application.common.IdentityApplicationManagementException)1 CacheEntry (org.wso2.carbon.identity.oauth.cache.CacheEntry)1 OAuthCacheKey (org.wso2.carbon.identity.oauth.cache.OAuthCacheKey)1 InvalidOAuthClientException (org.wso2.carbon.identity.oauth.common.exception.InvalidOAuthClientException)1 OAuthAppDAO (org.wso2.carbon.identity.oauth.dao.OAuthAppDAO)1 OAuthAppDO (org.wso2.carbon.identity.oauth.dao.OAuthAppDO)1