Search in sources :

Example 6 with AiravataSecurityException

use of org.apache.airavata.security.AiravataSecurityException in project airavata by apache.

the class OAuthTokenRetrievalClient method retrieveAccessToken.

/**
 * Retrieve the OAuth Access token via the specified grant type.
 * @param consumerId
 * @param consumerSecret
 * @param userName
 * @param password
 * @param grantType
 * @return
 * @throws SecurityException
 */
public String retrieveAccessToken(String consumerId, String consumerSecret, String userName, String password, int grantType) throws AiravataSecurityException {
    HttpPost postMethod = null;
    try {
        // initialize trust store to handle SSL handshake with WSO2 IS properly.
        TrustStoreManager trustStoreManager = new TrustStoreManager();
        SSLContext sslContext = trustStoreManager.initializeTrustStoreManager(Properties.TRUST_STORE_PATH, Properties.TRUST_STORE_PASSWORD);
        // create https scheme with the trust store
        org.apache.http.conn.ssl.SSLSocketFactory sf = new org.apache.http.conn.ssl.SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, Properties.authzServerPort);
        HttpClient httpClient = new DefaultHttpClient();
        // set the https scheme in the httpclient
        httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme);
        postMethod = new HttpPost(Properties.oauthTokenEndPointURL);
        // build the HTTP request with relevant params for resource owner credential grant type
        String authInfo = consumerId + ":" + consumerSecret;
        String authHeader = new String(Base64.encodeBase64(authInfo.getBytes()));
        postMethod.setHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.setHeader("Authorization", "Basic " + authHeader);
        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        if (grantType == 1) {
            urlParameters.add(new BasicNameValuePair("grant_type", "password"));
            urlParameters.add(new BasicNameValuePair("username", userName));
            urlParameters.add(new BasicNameValuePair("password", password));
        } else if (grantType == 2) {
            urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
        }
        postMethod.setEntity(new UrlEncodedFormEntity(urlParameters));
        HttpResponse response = httpClient.execute(postMethod);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuilder result = new StringBuilder();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        JSONParser parser = new JSONParser();
        JSONObject jsonObject = (JSONObject) parser.parse(result.toString());
        return (String) jsonObject.get("access_token");
    } catch (ClientProtocolException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (IOException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (ParseException e) {
        throw new AiravataSecurityException(e.getMessage(), e);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) Scheme(org.apache.http.conn.scheme.Scheme) ArrayList(java.util.ArrayList) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) InputStreamReader(java.io.InputStreamReader) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SSLContext(javax.net.ssl.SSLContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) JSONObject(org.json.simple.JSONObject) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException)

Example 7 with AiravataSecurityException

use of org.apache.airavata.security.AiravataSecurityException in project airavata by apache.

the class SecureClient method main.

public static void main(String[] args) throws Exception {
    Scanner scanner = new Scanner(System.in);
    // register client or use existing client
    System.out.println("");
    System.out.println("Please select from the following options:");
    System.out.println("1. Register the client as an OAuth application.");
    System.out.println("2. Client is already registered. Use the existing credentials.");
    String opInput = scanner.next();
    int option = Integer.valueOf(opInput.trim());
    String consumerId = null;
    String consumerSecret = null;
    if (option == 1) {
        // register OAuth application - this happens once during initialization of the gateway.
        /**
         **********************Start obtaining input from user****************************
         */
        System.out.println("");
        System.out.println("Registering an OAuth application representing the client....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("OAuth application name: (default:" + Properties.appName + ", press 'd' to use default value.)");
        String appNameInput = scanner.next();
        String appName = null;
        if (appNameInput.trim().equals("d")) {
            appName = Properties.appName;
        } else {
            appName = appNameInput.trim();
        }
        System.out.println("Consumer Id: (default:" + Properties.consumerID + ", press 'd' to use default value.)");
        String consumerIdInput = scanner.next();
        if (consumerIdInput.trim().equals("d")) {
            consumerId = Properties.consumerID;
        } else {
            consumerId = consumerIdInput.trim();
        }
        System.out.println("Consumer Secret: (default:" + Properties.consumerSecret + ", press 'd' to use default value.)");
        String consumerSecInput = scanner.next();
        if (consumerSecInput.trim().equals("d")) {
            consumerSecret = Properties.consumerSecret;
        } else {
            consumerSecret = consumerSecInput.trim();
        }
        /**
         ********************* Perform registration of the client as an OAuth app**************************
         */
        try {
            ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null);
            OAuthAppRegisteringClient authAppRegisteringClient = new OAuthAppRegisteringClient(Properties.oauthAuthzServerURL, Properties.adminUserName, Properties.adminPassword, configContext);
            OAuthConsumerAppDTO appDTO = authAppRegisteringClient.registerApplication(appName, consumerId, consumerSecret);
            /**
             ******************* Complete registering the client **********************************************
             */
            System.out.println("");
            System.out.println("Registered OAuth app successfully. Following is app's details:");
            System.out.println("App Name: " + appDTO.getApplicationName());
            System.out.println("Consumer ID: " + appDTO.getOauthConsumerKey());
            System.out.println("Consumer Secret: " + appDTO.getOauthConsumerSecret());
            System.out.println("");
        } catch (AiravataSecurityException e) {
            e.printStackTrace();
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    } else if (option == 2) {
        System.out.println("");
        System.out.println("Enter Consumer Id: ");
        consumerId = scanner.next().trim();
        System.out.println("Enter Consumer Secret: ");
        consumerSecret = scanner.next().trim();
    }
    // obtain OAuth access token
    /**
     **********************Start obtaining input from user****************************
     */
    System.out.println("");
    System.out.println("Please select the preferred grant type: (or press d to use the default option" + Properties.grantType + ")");
    System.out.println("1. Resource Owner Password Credential.");
    System.out.println("2. Client Credential.");
    String grantTypeInput = scanner.next().trim();
    int grantType = 0;
    if (grantTypeInput.equals("d")) {
        grantType = Properties.grantType;
    } else {
        grantType = Integer.valueOf(grantTypeInput);
    }
    String userName = null;
    String password = null;
    if (grantType == 1) {
        System.out.println("Obtaining OAuth access token via 'Resource Owner Password' grant type....");
        System.out.println("Please enter following information as you prefer, or use defaults.");
        System.out.println("End user's name: (default:" + Properties.userName + ", press 'd' to use default value.)");
        String userNameInput = scanner.next();
        if (userNameInput.trim().equals("d")) {
            userName = Properties.userName;
        } else {
            userName = userNameInput.trim();
        }
        System.out.println("End user's password: (default:" + Properties.password + ", press 'd' to use default value.)");
        String passwordInput = scanner.next();
        if (passwordInput.trim().equals("d")) {
            password = Properties.password;
        } else {
            password = passwordInput.trim();
        }
    } else if (grantType == 2) {
        System.out.println("");
        System.out.println("Please enter the user name to be passed: ");
        String userNameInput = scanner.next();
        userName = userNameInput.trim();
        System.out.println("");
        System.out.println("Obtaining OAuth access token via 'Client Credential' grant type...' grant type....");
    }
    /**
     *************************** Finish obtaining input from user******************************************
     */
    try {
        // obtain the OAuth token for the specified end user.
        String accessToken = new OAuthTokenRetrievalClient().retrieveAccessToken(consumerId, consumerSecret, userName, password, grantType);
        System.out.println("");
        System.out.println("OAuth access token is: " + accessToken);
        // invoke Airavata API by the SecureClient, on behalf of the user.
        System.out.println("");
        System.out.println("Invoking Airavata API...");
        System.out.println("Enter the access token to be used: (default:" + accessToken + ", press 'd' to use default value.)");
        String accessTokenInput = scanner.next();
        String acTk = null;
        if (accessTokenInput.trim().equals("d")) {
            acTk = accessToken;
        } else {
            acTk = accessTokenInput.trim();
        }
        // obtain as input, the method to be invoked
        System.out.println("");
        System.out.println("Enter the number corresponding to the method to be invoked: ");
        System.out.println("1. getAPIVersion");
        System.out.println("2. getAllAppModules");
        System.out.println("3. addGateway");
        String methodNumberString = scanner.next();
        int methodNumber = Integer.valueOf(methodNumberString.trim());
        Airavata.Client client = createAiravataClient(Properties.SERVER_HOST, Properties.SERVER_PORT);
        AuthzToken authzToken = new AuthzToken();
        authzToken.setAccessToken(acTk);
        Map<String, String> claimsMap = new HashMap<>();
        claimsMap.put("userName", userName);
        claimsMap.put("email", "hasini@gmail.com");
        authzToken.setClaimsMap(claimsMap);
        if (methodNumber == 1) {
            String version = client.getAPIVersion(authzToken);
            System.out.println("");
            System.out.println("Airavata API version: " + version);
            System.out.println("");
        } else if (methodNumber == 2) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            List<ApplicationModule> appModules = client.getAllAppModules(authzToken, gatewayId);
            System.out.println("Output of getAllAppModuels: ");
            for (ApplicationModule appModule : appModules) {
                System.out.println(appModule.getAppModuleName());
            }
            System.out.println("");
            System.out.println("");
        } else if (methodNumber == 3) {
            System.out.println("");
            System.out.println("Enter the gateway id: ");
            String gatewayId = scanner.next().trim();
            Gateway gateway = new Gateway(gatewayId, GatewayApprovalStatus.REQUESTED);
            gateway.setDomain("airavata.org");
            gateway.setEmailAddress("airavata@apache.org");
            gateway.setGatewayName("airavataGW");
            String output = client.addGateway(authzToken, gateway);
            System.out.println("");
            System.out.println("Output of addGateway: " + output);
            System.out.println("");
        }
    } catch (InvalidRequestException e) {
        e.printStackTrace();
    } catch (TException e) {
        e.printStackTrace();
    } catch (AiravataSecurityException e) {
        e.printStackTrace();
    }
}
Also used : TException(org.apache.thrift.TException) Scanner(java.util.Scanner) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) HashMap(java.util.HashMap) OAuthConsumerAppDTO(org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO) TException(org.apache.thrift.TException) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataClientException(org.apache.airavata.model.error.AiravataClientException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) ApplicationModule(org.apache.airavata.model.appcatalog.appdeployment.ApplicationModule) Gateway(org.apache.airavata.model.workspace.Gateway) AuthzToken(org.apache.airavata.model.security.AuthzToken) List(java.util.List) InvalidRequestException(org.apache.airavata.model.error.InvalidRequestException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) Airavata(org.apache.airavata.api.Airavata)

Example 8 with AiravataSecurityException

use of org.apache.airavata.security.AiravataSecurityException 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 9 with AiravataSecurityException

use of org.apache.airavata.security.AiravataSecurityException in project airavata by apache.

the class DefaultAiravataSecurityManager method initializeSecurityInfra.

@Override
public void initializeSecurityInfra() throws AiravataSecurityException {
    /* in the default security manager, this method checks if the xacml authorization policy is published,
         * and if not, publish the policy to the PDP (of WSO2 Identity Server)
         */
    try {
        if (ServerSettings.isAPISecured()) {
            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());
            List<GatewayResourceProfile> gwProfiles = getRegistryServiceClient().getAllGatewayResourceProfiles();
            // read the policy as a string
            BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(ServerSettings.getAuthorizationPoliyName() + ".xml")));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            String defaultXACMLPolicy = stringBuilder.toString();
            CredentialStoreService.Client csClient = getCredentialStoreServiceClient();
            for (GatewayResourceProfile gwrp : gwProfiles) {
                if (gwrp.getIdentityServerPwdCredToken() != null && gwrp.getIdentityServerTenant() != null) {
                    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();
                    DefaultPAPClient PAPClient = new DefaultPAPClient(ServerSettings.getRemoteAuthzServerUrl(), username, password, configContext);
                    boolean policyAdded = PAPClient.isPolicyAdded(ServerSettings.getAuthorizationPoliyName());
                    if (policyAdded) {
                        logger.debug("Authorization policy is already added in the authorization server.");
                    } else {
                        // publish the policy and enable it in a separate thread
                        PAPClient.addPolicy(defaultXACMLPolicy);
                        logger.debug("Authorization policy is published in the authorization server.");
                    }
                } else {
                    logger.warn("Identity Server configuration missing for gateway : " + gwrp.getGatewayID());
                }
            }
        }
    } catch (AxisFault axisFault) {
        logger.error(axisFault.getMessage(), axisFault);
        throw new AiravataSecurityException("Error in initializing the configuration context for creating the " + "PAP client.");
    } catch (ApplicationSettingsException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading configuration when creating the PAP client.");
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading authorization policy.");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading the authorization policy.");
    } catch (RegistryServiceException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in reading the Gateway Profiles from App Catalog.");
    } 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) 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) DefaultPAPClient(org.apache.airavata.service.security.xacml.DefaultPAPClient) TrustStoreManager(org.apache.airavata.security.util.TrustStoreManager) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreService(org.apache.airavata.credential.store.cpi.CredentialStoreService)

Example 10 with AiravataSecurityException

use of org.apache.airavata.security.AiravataSecurityException in project airavata by apache.

the class KeyCloakSecurityManager method isUserAuthorized.

/**
 * Implement this method with the user authentication/authorization logic in your SecurityManager.
 *
 * @param authzToken : this includes OAuth token and user's claims
 * @param metaData   : this includes other meta data needed for security enforcements.
 * @return
 * @throws AiravataSecurityException
 */
@Override
public boolean isUserAuthorized(AuthzToken authzToken, Map<String, String> metaData) throws AiravataSecurityException {
    String subject = authzToken.getClaimsMap().get(Constants.USER_NAME);
    String accessToken = authzToken.getAccessToken();
    String gatewayId = authzToken.getClaimsMap().get(Constants.GATEWAY_ID);
    String action = "/airavata/" + metaData.get(Constants.API_METHOD_NAME);
    try {
        if (!ServerSettings.isAPISecured()) {
            return true;
        }
        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.");
                String[] roles = getUserRolesFromOAuthToken(subject, accessToken, gatewayId);
                boolean authorizationDecision = hasPermission(roles, action);
                // cache the authorization decision
                long currentTime = System.currentTimeMillis();
                // TODO get the actual token expiration time
                authzCacheManager.addToAuthzCache(new AuthzCacheIndex(subject, gatewayId, accessToken, action), new AuthzCacheEntry(authorizationDecision, currentTime + 1000 * 60 * 60, currentTime));
                return authorizationDecision;
            } else {
                // undefined status returned from the authz cache manager
                throw new AiravataSecurityException("Error in reading from the authorization cache.");
            }
        } else {
            String[] roles = getUserRolesFromOAuthToken(subject, accessToken, gatewayId);
            return hasPermission(roles, action);
        }
    } catch (ApplicationSettingsException e) {
        e.printStackTrace();
        throw new AiravataSecurityException(e.getMessage(), e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AiravataSecurityException(e.getMessage(), e);
    }
}
Also used : ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) RegistryServiceException(org.apache.airavata.registry.api.exception.RegistryServiceException) AiravataSecurityException(org.apache.airavata.security.AiravataSecurityException) CredentialStoreException(org.apache.airavata.credential.store.exception.CredentialStoreException) TException(org.apache.thrift.TException) ApplicationSettingsException(org.apache.airavata.common.exception.ApplicationSettingsException)

Aggregations

AiravataSecurityException (org.apache.airavata.security.AiravataSecurityException)16 ApplicationSettingsException (org.apache.airavata.common.exception.ApplicationSettingsException)8 TrustStoreManager (org.apache.airavata.security.util.TrustStoreManager)5 TException (org.apache.thrift.TException)5 RegistryServiceException (org.apache.airavata.registry.api.exception.RegistryServiceException)4 RemoteException (java.rmi.RemoteException)3 GatewayResourceProfile (org.apache.airavata.model.appcatalog.gatewayprofile.GatewayResourceProfile)3 AxisFault (org.apache.axis2.AxisFault)3 ConfigurationContext (org.apache.axis2.context.ConfigurationContext)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 SSLContext (javax.net.ssl.SSLContext)2 CredentialStoreService (org.apache.airavata.credential.store.cpi.CredentialStoreService)2 CredentialStoreException (org.apache.airavata.credential.store.exception.CredentialStoreException)2 PasswordCredential (org.apache.airavata.model.credential.store.PasswordCredential)2 AiravataSecurityManager (org.apache.airavata.service.security.AiravataSecurityManager)2 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1