Search in sources :

Example 1 with OAuth2TokenValidationResponseDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.

the class DefaultOAuthClient method validateAccessToken.

/**
 * Validates the OAuth 2.0 access token
 *
 * @param accessToken
 * @return
 * @throws Exception
 */
public OAuth2TokenValidationResponseDTO validateAccessToken(String accessToken) throws AiravataSecurityException {
    try {
        OAuth2TokenValidationRequestDTO oauthReq = new OAuth2TokenValidationRequestDTO();
        OAuth2TokenValidationRequestDTO_OAuth2AccessToken token = new OAuth2TokenValidationRequestDTO_OAuth2AccessToken();
        token.setIdentifier(accessToken);
        token.setTokenType(BEARER_TOKEN_TYPE);
        oauthReq.setAccessToken(token);
        return stub.validate(oauthReq);
    } catch (RemoteException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in validating the OAuth access token.");
    }
}
Also used : OAuth2TokenValidationRequestDTO_OAuth2AccessToken(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO_OAuth2AccessToken) RemoteException(java.rmi.RemoteException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO)

Example 2 with OAuth2TokenValidationResponseDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.

the class DefaultAiravataSecurityManager method isUserAuthorized.

public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
    try {
        String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
        String accessToken = authzToken.getAccessToken();
        String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
        String action = metaData.get(Constants.API_METHOD_NAME);
        // if the authz cache is enabled, check in the cache if the authz decision is cached and if so, what the status is
        if (ServerSettings.isAuthzCacheEnabled()) {
            // obtain an instance of AuthzCacheManager implementation.
            AuthzCacheManager authzCacheManager = AuthzCacheManagerFactory.getAuthzCacheManager();
            // check in the cache
            AuthzCachedStatus authzCachedStatus = authzCacheManager.getAuthzCachedStatus(new AuthzCacheIndex(subject, gatewayId, accessToken, action));
            if (AuthzCachedStatus.AUTHORIZED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
                return true;
            } else if (AuthzCachedStatus.NOT_AUTHORIZED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is retrieved from cache.");
                return false;
            } else if (AuthzCachedStatus.NOT_CACHED.equals(authzCachedStatus)) {
                logger.debug("Authz decision for: (" + subject + ", " + accessToken + ", " + action + ") is not in the cache. " + "Obtaining it from the authorization server.");
                CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
                GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
                PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
                String username = credential.getLoginUserName();
                if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
                    username = username + "@" + gwrp.getIdentityServerTenant();
                String password = credential.getPassword();
                // talk to Authorization Server, obtain the decision, cache it and return the result.
                ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
                // initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
                TrustStoreManager trustStoreManager = new TrustStoreManager();
                trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
                DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
                if (validationResponse.getValid()) {
                    String authorizedUserName = validationResponse.getAuthorizedUser();
                    if (authorizedUserName.contains("@")) {
                        authorizedUserName = authorizedUserName.split("@")[0];
                    }
                    if (subject.contains("@")) {
                        subject = subject.split("@")[0];
                    }
                    // cannot impersonate users
                    if (!authorizedUserName.toLowerCase().equals(subject.toLowerCase()))
                        return false;
                    long expiryTimestamp = validationResponse.getExpiryTime();
                    // check for fine grained authorization for the API invocation, based on XACML.
                    DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                    boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
                    // cache the authorization decision
                    authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, expiryTimestamp, System.currentTimeMillis()));
                    return authorizationDecision;
                } else {
                    return false;
                }
            } else {
                // undefined status returned from the authz cache manager
                throw new AiravataSecurityException("Error in reading from the authorization cache.");
            }
        } else {
            CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
            GatewayResourceProfile gwrp = getRegistryServiceClient().getGatewayResourceProfile(gatewayId);
            PasswordCredential credential = csClient.getPasswordCredential(gwrp.getIdentityServerPwdCredToken(), gwrp.getGatewayID());
            String username = credential.getLoginUserName();
            if (gwrp.getIdentityServerTenant() != null && !gwrp.getIdentityServerTenant().isEmpty())
                username = username + "@" + gwrp.getIdentityServerTenant();
            String password = credential.getPassword();
            // talk to Authorization Server, obtain the decision and return the result (authz cache is not enabled).
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            // initialize SSL context with the trust store that contains the public cert of WSO2 Identity Server.
            TrustStoreManager trustStoreManager = new TrustStoreManager();
            trustStoreManager.initializeTrustStoreManager(ServerSettings.getTrustStorePath(), ServerSettings.getTrustStorePassword());
            DefaultOAuthClient oauthClient = new DefaultOAuthClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
            OAuth2TokenValidationResponseDTO validationResponse = oauthClient.validateAccessToken(authzToken.getAccessToken());
            boolean isOAuthTokenValid = validationResponse.getValid();
            // if XACML based authorization is enabled, check for role based authorization for the API invocation
            DefaultXACMLPEP entitlementClient = new DefaultXACMLPEP(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
            boolean authorizationDecision = entitlementClient.getAuthorizationDecision(authzToken, metaData);
            return (isOAuthTokenValid && authorizationDecision);
        }
    } catch (AxisFault axisFault) {
        logger.error(axisFault.getMessage(), axisFault);
        throw new AiravataSecurityException("Error in initializing the configuration context for creating the OAuth validation client.");
    } catch (ApplicationSettingsException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading OAuth server configuration.");
    } catch (RegistryServiceException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in accessing AppCatalog.");
    } catch (TException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in connecting to Credential Store Service.");
    }
}
Also used : AxisFault(org.apache.axis2.AxisFault) TException(org.apache.thrift.TException) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) DefaultXACMLPEP(org.apache.airavata.service.security.xacml.DefaultXACMLPEP) ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException) GatewayResourceProfile(org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile) RegistryServiceException(org.apache.airavata.registry.api.exception.RegistryServiceException) PasswordCredential(org.apache.airavata.model.credential.store.PasswordCredential) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO) DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreService(org.apache.airavata.credential.store.cpi.CredentialStoreService)

Example 3 with OAuth2TokenValidationResponseDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO in project airavata by apache.

the class AuthResponse method main.

public static void main(String[] args) throws AuthenticationException, AiravataSecurityException, AxisFault {
    String accessToken = authenticate("master@master.airavata", "master").getAccess_token();
    ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
    DefaultOAuthClient defaultOAuthClient = new DefaultOAuthClient(hostName + "/services/", username, password, configContext);
    OAuth2TokenValidationResponseDTO tokenValidationRequestDTO = defaultOAuthClient.validateAccessToken(accessToken);
    String authorizedUser = tokenValidationRequestDTO.getAuthorizedUser();
    AuthzToken authzToken = new AuthzToken();
    authzToken.setAccessToken(accessToken);
    Map<String, String> claimsMap = new HashMap<>();
    claimsMap.put(Constants.USER_NAME, "scigap_admin");
    claimsMap.put(Constants.API_METHOD_NAME, "/airavata/getAPIVersion");
    authzToken.setClaimsMap(claimsMap);
    DefaultXACMLPEP defaultXACMLPEP = new DefaultXACMLPEP(hostName + "/services/", username, password, configContext);
    HashMap<String, String> metaDataMap = new HashMap();
    boolean result = defaultXACMLPEP.getAuthorizationDecision(authzToken, metaDataMap);
    System.out.println(result);
}
Also used : DefaultOAuthClient(org.apache.airavata.service.security.oauth.DefaultOAuthClient) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) DefaultXACMLPEP(org.apache.airavata.service.security.xacml.DefaultXACMLPEP) HashMap(java.util.HashMap) AuthzToken(org.apache.airavata.model.security.AuthzToken) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO)

Example 4 with OAuth2TokenValidationResponseDTO

use of org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO 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 OAuth2TokenValidationResponseDTO

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

the class OAuthOpaqueAuthenticatorImpl method getTokenMetaData.

@MethodStats
public OAuthTokenInfo getTokenMetaData(String accessToken) throws APIManagementException {
    OAuthTokenInfo tokenInfo = new OAuthTokenInfo();
    OAuth2TokenValidationRequestDTO requestDTO = new OAuth2TokenValidationRequestDTO();
    OAuth2TokenValidationRequestDTO.OAuth2AccessToken token = requestDTO.new OAuth2AccessToken();
    token.setIdentifier(accessToken);
    token.setTokenType("bearer");
    requestDTO.setAccessToken(token);
    OAuth2TokenValidationRequestDTO.TokenValidationContextParam[] contextParams = new OAuth2TokenValidationRequestDTO.TokenValidationContextParam[1];
    requestDTO.setContext(contextParams);
    OAuth2ClientApplicationDTO clientApplicationDTO = findOAuthConsumerIfTokenIsValid(requestDTO);
    OAuth2TokenValidationResponseDTO responseDTO = clientApplicationDTO.getAccessTokenValidationResponse();
    if (!responseDTO.isValid()) {
        tokenInfo.setTokenValid(responseDTO.isValid());
        log.error("Invalid OAuth Token : " + responseDTO.getErrorMsg());
        return tokenInfo;
    }
    tokenInfo.setTokenValid(responseDTO.isValid());
    tokenInfo.setEndUserName(responseDTO.getAuthorizedUser());
    tokenInfo.setConsumerKey(clientApplicationDTO.getConsumerKey());
    // Convert Expiry Time to milliseconds.
    if (responseDTO.getExpiryTime() == Long.MAX_VALUE) {
        tokenInfo.setValidityPeriod(Long.MAX_VALUE);
    } else {
        tokenInfo.setValidityPeriod(responseDTO.getExpiryTime() * 1000L);
    }
    tokenInfo.setIssuedTime(System.currentTimeMillis());
    tokenInfo.setScopes(responseDTO.getScope());
    return tokenInfo;
}
Also used : OAuth2ClientApplicationDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2ClientApplicationDTO) OAuthTokenInfo(org.wso2.carbon.apimgt.api.OAuthTokenInfo) OAuth2TokenValidationRequestDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO) OAuth2TokenValidationResponseDTO(org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Aggregations

AiravataSecurityException (org.apache.airavata.security.AiravataSecurityException)2 DefaultOAuthClient (org.apache.airavata.service.security.oauth.DefaultOAuthClient)2 DefaultXACMLPEP (org.apache.airavata.service.security.xacml.DefaultXACMLPEP)2 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)2 OAuth2TokenValidationRequestDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationRequestDTO)2 OAuth2TokenValidationResponseDTO (org.wso2.carbon.identity.oauth2.dto.OAuth2TokenValidationResponseDTO)2 OAuth2TokenValidationResponseDTO (org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationResponseDTO)2 RemoteException (java.rmi.RemoteException)1 HashMap (java.util.HashMap)1 ApplicationSettingsException (org.apache.airavata.common.exception.ApplicationSettingsException)1 CredentialStoreService (org.apache.airavata.credential.store.cpi.CredentialStoreService)1 GatewayResourceProfile (org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile)1 PasswordCredential (org.apache.airavata.model.credential.store.PasswordCredential)1 AuthzToken (org.apache.airavata.model.security.AuthzToken)1 RegistryServiceException (org.apache.airavata.registry.api.exception.RegistryServiceException)1 TrustStoreManager (org.apache.airavata.security.util.TrustStoreManager)1 AxisFault (org.apache.axis2.AxisFault)1 TException (org.apache.thrift.TException)1 Before (org.junit.Before)1 OAuthTokenInfo (org.wso2.carbon.apimgt.api.OAuthTokenInfo)1