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

The following examples show how to use org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext#getOauth2AccessTokenReqDTO() . 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: AbstractClientAuthHandler.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public boolean authenticateClient(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    //Skipping credential validation for saml2 bearer if not configured as needed
    if (StringUtils.isEmpty(oAuth2AccessTokenReqDTO.getClientSecret()) && org.wso2.carbon.identity.oauth.common
            .GrantType.SAML20_BEARER.toString().equals(oAuth2AccessTokenReqDTO.getGrantType()) && JavaUtils
            .isFalseExplicitly(authConfig)) {
        if (log.isDebugEnabled()) {
            log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
                    "Strict client validation set to : " + authConfig + " Authenticating without client secret");
        }
        return true;
    }

    if (log.isDebugEnabled()) {
        log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType() + " " +
                "Strict client validation set to : " + authConfig);
    }
    return false;
}
 
Example 2
Source File: AbstractClientAuthHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean canAuthenticate(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();

    if (StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientId()) &&
            StringUtils.isNotEmpty(oAuth2AccessTokenReqDTO.getClientSecret())) {
        if (log.isDebugEnabled()) {
            log.debug("Can authenticate with client ID and Secret." +
                    " Client ID: "+ oAuth2AccessTokenReqDTO.getClientId());
        }
        return true;

    } else {
        if (org.wso2.carbon.identity.oauth.common.GrantType.SAML20_BEARER.toString().equals(
                oAuth2AccessTokenReqDTO.getGrantType())) {

            //Getting configured value for client credential validation requirements
            authConfig = properties.getProperty(
                    OAuthConstants.CLIENT_AUTH_CREDENTIAL_VALIDATION);

            if (log.isDebugEnabled()) {
                log.debug("Grant type : " + oAuth2AccessTokenReqDTO.getGrantType());
            }

            //If user has set strict validation to false, can authenticate without credentials
            if (StringUtils.isNotEmpty(authConfig) && JavaUtils.isFalseExplicitly(authConfig)) {
                if (log.isDebugEnabled()) {
                    log.debug("Client auth credential validation set to : " + authConfig + ". " +
                            "can authenticate without client secret");
                }
                return true;
            }
        }
    }
    return false;
}
 
Example 3
Source File: AbstractAuthorizationGrantHandler.java    From carbon-identity with Apache License 2.0 5 votes vote down vote up
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
        throws IdentityOAuth2Exception {

    OAuth2AccessTokenReqDTO tokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
    String grantType = tokenReqDTO.getGrantType();

    // Load application data from the cache
    AppInfoCache appInfoCache = AppInfoCache.getInstance();
    OAuthAppDO oAuthAppDO = appInfoCache.getValueFromCache(tokenReqDTO.getClientId());
    if (oAuthAppDO == null) {
        try {
            oAuthAppDO = new OAuthAppDAO().getAppInformation(tokenReqDTO.getClientId());
            appInfoCache.addToCache(tokenReqDTO.getClientId(), oAuthAppDO);
        } catch (InvalidOAuthClientException e) {
            throw new IdentityOAuth2Exception(e.getMessage(), e);
        }
    }
    // If the application has defined a limited set of grant types, then check the grant
    if (oAuthAppDO.getGrantTypes() != null && !oAuthAppDO.getGrantTypes().contains(grantType)) {
        if (log.isDebugEnabled()) {
            //Do not change this log format as these logs use by external applications
            log.debug("Unsupported Grant Type : " + grantType + " for client id : " + tokenReqDTO.getClientId());
        }
        return false;
    }
    return true;
}
 
Example 4
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 5
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;
}