Java Code Examples for org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext#setScope()

The following examples show how to use org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext#setScope() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractAuthorizationGrantHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {
    OAuthCallback scopeValidationCallback = new OAuthCallback(tokReqMsgCtx.getAuthorizedUser(),
            tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId(), OAuthCallback.OAuthCallbackType
            .SCOPE_VALIDATION_TOKEN);
    scopeValidationCallback.setRequestedScope(tokReqMsgCtx.getScope());
    if (tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType().equals(
            org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString())) {
        scopeValidationCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(
                OAuthConstants.OAUTH_SAML2_BEARER_GRANT_ENUM.toString()));
    } else if (tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType().equals(
            org.wso2.carbon.identity.oauth.common.GrantType.IWA_NTLM.toString())) {
        scopeValidationCallback.setCarbonGrantType(org.wso2.carbon.identity.oauth.common.GrantType.valueOf(
                OAuthConstants.OAUTH_IWA_NTLM_GRANT_ENUM.toString()));
    } else {
        scopeValidationCallback.setGrantType(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getGrantType());
    }

    callbackManager.handleCallback(scopeValidationCallback);
    tokReqMsgCtx.setValidityPeriod(scopeValidationCallback.getValidityPeriod());
    tokReqMsgCtx.setScope(scopeValidationCallback.getApprovedScope());
    return scopeValidationCallback.isValidScope();
}
 
Example 2
Source File: ExtendedClientCredentialsGrantHandler.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Override
public boolean validateScope(OAuthTokenReqMessageContext tokReqMsgCtx) {
    // Execute ScopeIssuer
    boolean state = ScopesIssuer.getInstance().setScopes(tokReqMsgCtx);

    // If ScopeIssuer returns true, then see if application scope is set.
    if (state) {
        String[] scopes = tokReqMsgCtx.getScope();

        String applicationScope = TokenMgtDataHolder.getApplicationTokenScope();
        if (scopes != null) {

            // Arrays.asList won't work here, because list.add cannot be called
            // on the returned list as it's immutable.
            ArrayList<String> scopeList = new ArrayList<String>(scopes.length);
            scopeList.addAll(Arrays.asList(scopes));
            // Forcefully add application scope if it's not included in the list.
            if (!scopeList.contains(applicationScope)) {
                scopeList.add(applicationScope);
                tokReqMsgCtx.setScope(scopeList.toArray(new String[scopeList.size()]));
            }
        }
    }

    return state;
}
 
Example 3
Source File: ClientCredentialsGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    if(!super.validateGrant(tokReqMsgCtx)){
        return false;
    }

    // By this time, we have already validated client credentials.
    tokReqMsgCtx.setScope(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope());
    return true;
}
 
Example 4
Source File: ClientCredentialsGrantHandler.java    From attic-stratos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {
    // By this time, we have already validated client credentials.
    tokReqMsgCtx.setScope(tokReqMsgCtx.getOauth2AccessTokenReqDTO().getScope());
    return true;
}
 
Example 5
Source File: AccessTokenGrantHandler.java    From carbon-device-mgt with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
    if (!super.validateGrant(tokReqMsgCtx)) {
        return false;
    } else {
        OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
        String username = null;
        String userTenantDomain = null;
        String clientId = oAuth2AccessTokenReqDTO.getClientId();
        String spTenantDomain = null;
        OAuthValidationResponse response;
        ServiceProvider serviceProvider;
        boolean authStatus = false;

        String accessToken = null;
        RequestParameter[] parameters = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();

        for (RequestParameter parameter : parameters) {
            if (TOKEN_GRANT_PARAM.equals(parameter.getKey())) {
                if (parameter.getValue() != null && parameter.getValue().length > 0) {
                    accessToken = parameter.getValue()[0];
                }
            }
        }

        if (accessToken != null && !accessToken.isEmpty()) {
            try {
                response = tokenValidator.validateToken(accessToken);
            } catch (RemoteException e) {
                log.error("Failed to validate the OAuth token provided.", e);
                return false;
            }
            if (response != null && response.isValid()) {
                authStatus = true;
                username = response.getUserName() + "@" + response.getTenantDomain();
                userTenantDomain = MultitenantUtils.getTenantDomain(username);
                spTenantDomain = response.getTenantDomain();
            } else if (response != null && !response.isValid()) {
                throw new IdentityOAuth2Exception("Authentication failed for the provided access token");
            }
        }

        try {
            serviceProvider = OAuth2ServiceComponentHolder.getApplicationMgtService()
                    .getServiceProviderByClientId(clientId, "oauth2", spTenantDomain);
        } catch (IdentityApplicationManagementException var15) {
            throw new IdentityOAuth2Exception("Error occurred while retrieving OAuth2 application data for client id "
                    + clientId, var15);
        }

        if (!serviceProvider.isSaasApp() && !userTenantDomain.equals(spTenantDomain)) {
            if (log.isDebugEnabled()) {
                log.debug("Non-SaaS service provider tenant domain is not same as user tenant domain; "
                        + spTenantDomain + " != " + userTenantDomain);
            }

            return false;
        } else {
            String tenantAwareUserName = MultitenantUtils.getTenantAwareUsername(username);
            username = tenantAwareUserName + "@" + userTenantDomain;
            if (authStatus) {
                if (!username.contains("/") && StringUtils.isNotBlank(UserCoreUtil.getDomainFromThreadLocal())) {
                    username = UserCoreUtil.getDomainFromThreadLocal() + "/" + username;
                }

                AuthenticatedUser user = OAuth2Util.getUserFromUserName(username);
                user.setAuthenticatedSubjectIdentifier(user.toString());
                tokReqMsgCtx.setAuthorizedUser(user);
                tokReqMsgCtx.setScope(oAuth2AccessTokenReqDTO.getScope());
                return authStatus;
            } else {
                throw new IdentityOAuth2Exception("Authentication failed for " + username);
            }
        }
    }
}
 
Example 6
Source File: RefreshGrantHandler.java    From carbon-identity with Apache License 2.0 4 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    if(!super.validateGrant(tokReqMsgCtx)){
        return false;
    }

    OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    String refreshToken = tokenReqDTO.getRefreshToken();

    RefreshTokenValidationDataDO validationDataDO = tokenMgtDAO.validateRefreshToken(
            tokenReqDTO.getClientId(), refreshToken);

    if (validationDataDO.getAccessToken() == null) {
        log.debug("Invalid Refresh Token provided for Client with " +
                "Client Id : " + tokenReqDTO.getClientId());
        return false;
    }

    if (validationDataDO.getRefreshTokenState() != null &&
            !OAuthConstants.TokenStates.TOKEN_STATE_ACTIVE.equals(
                    validationDataDO.getRefreshTokenState()) &&
            !OAuthConstants.TokenStates.TOKEN_STATE_EXPIRED.equals(
                    validationDataDO.getRefreshTokenState())) {
        if(log.isDebugEnabled()) {
            log.debug("Access Token is not in 'ACTIVE' or 'EXPIRED' state for Client with " +
                    "Client Id : " + tokenReqDTO.getClientId());
        }
        return false;
    }

    String userStoreDomain = null;
    if (OAuth2Util.checkAccessTokenPartitioningEnabled() && OAuth2Util.checkUserNameAssertionEnabled()) {
        try {
            userStoreDomain = OAuth2Util.getUserStoreDomainFromUserId(validationDataDO.getAuthorizedUser().toString());
        } catch (IdentityOAuth2Exception e) {
            String errorMsg = "Error occurred while getting user store domain for User ID : " + validationDataDO.getAuthorizedUser();
            log.error(errorMsg, e);
            throw new IdentityOAuth2Exception(errorMsg, e);
        }
    }

    AccessTokenDO accessTokenDO = tokenMgtDAO.retrieveLatestAccessToken(tokenReqDTO.getClientId(),
            validationDataDO.getAuthorizedUser(),
            userStoreDomain, OAuth2Util.buildScopeString(validationDataDO.getScope()), true);

    if (accessTokenDO == null){
        if(log.isDebugEnabled()){
            log.debug("Error while retrieving the latest refresh token");
        }
        return false;
    }else if(!refreshToken.equals(accessTokenDO.getRefreshToken())){
        if(log.isDebugEnabled()){
            log.debug("Refresh token is not the latest.");
        }
        return false;
    }

    if (log.isDebugEnabled()) {
        log.debug("Refresh token validation successful for " +
                "Client id : " + tokenReqDTO.getClientId() +
                ", Authorized User : " + validationDataDO.getAuthorizedUser() +
                ", Token Scope : " + OAuth2Util.buildScopeString(validationDataDO.getScope()));
    }

    tokReqMsgCtx.setAuthorizedUser(validationDataDO.getAuthorizedUser());
    tokReqMsgCtx.setScope(validationDataDO.getScope());
    // Store the old access token as a OAuthTokenReqMessageContext property, this is already
    // a preprocessed token.
    tokReqMsgCtx.addProperty(PREV_ACCESS_TOKEN, validationDataDO);
    return true;
}
 
Example 7
Source File: ScopesIssuer.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
/**
 * This method is used to validate the scopes in OAuthToken Request and set the authorized scopes back to the
 * context.
 *
 * @param tokReqMsgCtx OAuthTokenReqMessageContext
 * @return true if the requested scopes are authorized, false if no scopes requested or scopes issuers are empty.
 */
public boolean setScopes(OAuthTokenReqMessageContext tokReqMsgCtx) {

    Map<String, List<String>> scopeSets;
    List<String> authorizedScopes;
    List<String> sortedScopes;
    Set<String> authorizedAllScopes = new HashSet<>();
    boolean isAllAuthorized = false;
    String[] requestedScopes = tokReqMsgCtx.getScope();
    String[] defaultScope = new String[]{DEFAULT_SCOPE_NAME};

    // if no issuers are defined
    if (scopesIssuers == null || scopesIssuers.isEmpty()) {

        if (log.isDebugEnabled()) {
            log.debug("Scope Issuers are not loaded");
        }
        tokReqMsgCtx.setScope(defaultScope);
        return true;
    }

    //If no scopes were requested.
    if (requestedScopes == null || requestedScopes.length == 0) {
        tokReqMsgCtx.setScope(defaultScope);
        return true;
    }

    scopeSets = initializeScopeSets(requestedScopes);
    for (Map.Entry<String, List<String>> entry : scopeSets.entrySet()) {
        sortedScopes = entry.getValue();
        if (!sortedScopes.isEmpty()) {
            tokReqMsgCtx.setScope(sortedScopes.toArray(new String[sortedScopes.size()]));
            authorizedScopes = scopesIssuers.get(entry.getKey()).getScopes(tokReqMsgCtx, scopeSkipList);
            authorizedAllScopes.addAll(authorizedScopes);
            isAllAuthorized = true;
        }
    }

    if (isAllAuthorized) {
        tokReqMsgCtx.setScope(authorizedAllScopes.toArray(new String[authorizedAllScopes.size()]));
        return true;
    }
    return false;
}