Search in sources :

Example 1 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByClientCredentialsGrant.

@Test
public void testGetNewAccessTokenByClientCredentialsGrant() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200 - client credentials grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE, null, null, null, -2L, null, null, null, null);
    // //mocked response from /token service
    OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
    // //expected response from key manager
    AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
    Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateClientCredentialsGrantAccessToken(tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(newTokenResponse);
    try {
        AccessTokenInfo newToken = kmImpl.getNewAccessToken(tokenRequest);
        Assert.assertEquals(newToken, accessTokenInfo);
    } catch (Exception ex) {
        Assert.fail(ex.getMessage());
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) Gson(com.google.gson.Gson) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) OAuth2ServiceStubs(org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) OAuth2TokenInfo(org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo) Test(org.testng.annotations.Test)

Example 2 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class DASThriftTestServer method start.

public void start(int receiverPort) throws DataBridgeException {
    DataPublisherTestUtil.setKeyStoreParams();
    streamDefinitionStore = getStreamDefinitionStore();
    numberOfEventsReceived = new AtomicInteger(0);
    DataBridge databridge = new DataBridge(new AuthenticationHandler() {

        public boolean authenticate(String userName, String password) {
            // allays authenticate to true
            return true;
        }

        public void initContext(AgentSession agentSession) {
        // To change body of implemented methods use File | Settings |
        // File Templates.
        }

        public void destroyContext(AgentSession agentSession) {
        }
    }, streamDefinitionStore, DataPublisherTestUtil.getDataBridgeConfigPath());
    thriftDataReceiver = new ThriftDataReceiver(receiverPort, databridge);
    databridge.subscribe(new AgentCallback() {

        int totalSize = 0;

        @Override
        public void definedStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition " + streamDefinition);
        }

        @Override
        public void removeStream(StreamDefinition streamDefinition) {
            log.info("StreamDefinition remove " + streamDefinition);
        }

        /**
         * Retrving and handling all the events to DAS event receiver
         * @param eventList list of event it received
         * @param credentials client credentials
         */
        public void receive(List<Event> eventList, Credentials credentials) {
            for (Event event : eventList) {
                String streamKey = event.getStreamId();
                if (!dataTables.containsKey(streamKey)) {
                    dataTables.put(streamKey, new ArrayList<Event>());
                }
                dataTables.get(streamKey).add(event);
                log.info("===  " + event.toString());
            }
            numberOfEventsReceived.addAndGet(eventList.size());
            log.info("Received events : " + numberOfEventsReceived);
        }
    });
    String address = "localhost";
    log.info("DAS Test Thrift Server starting on " + address);
    thriftDataReceiver.start(address);
    log.info("DAS Test Thrift Server Started");
}
Also used : AgentSession(org.wso2.carbon.databridge.core.Utils.AgentSession) StreamDefinition(org.wso2.carbon.databridge.commons.StreamDefinition) ArrayList(java.util.ArrayList) AgentCallback(org.wso2.carbon.databridge.core.AgentCallback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThriftDataReceiver(org.wso2.carbon.databridge.receiver.thrift.ThriftDataReceiver) Event(org.wso2.carbon.databridge.commons.Event) AuthenticationHandler(org.wso2.carbon.databridge.core.internal.authentication.AuthenticationHandler) Credentials(org.wso2.carbon.databridge.commons.Credentials) DataBridge(org.wso2.carbon.databridge.core.DataBridge)

Example 3 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials 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 4 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project product-iots by wso2.

the class WindowsEnrollment method testBST.

@Test(groups = Constants.WindowsEnrollment.WINDOWS_ENROLLMENT_GROUP, description = "Test Windows BST.")
public void testBST() throws Exception {
    JSONObject bsdObject = new JSONObject(Constants.WindowsEnrollment.BSD_PAYLOAD);
    JSONObject childObject = bsdObject.getJSONObject("credentials");
    JSONObject modifiedObject = new JSONObject();
    modifiedObject.put("token", OAuthUtil.getOAuthToken(backendHTTPURL, backendHTTPSURL));
    childObject.put("token", modifiedObject);
    HttpResponse response = client.post(Constants.WindowsEnrollment.BSD_URL, Constants.WindowsEnrollment.BSD_PAYLOAD);
    bsd = response.getData();
    Assert.assertEquals(response.getResponseCode(), HttpStatus.SC_OK);
}
Also used : JSONObject(org.json.JSONObject) HttpResponse(org.wso2.carbon.automation.test.utils.http.client.HttpResponse) Test(org.testng.annotations.Test)

Example 5 with Credentials

use of org.wso2.carbon.databridge.commons.Credentials in project carbon-apimgt by wso2.

the class APIStateChangeWSWorkflowExecutor method setOAuthApplicationInfo.

/**
 * set information that are needed to invoke callback service
 */
private void setOAuthApplicationInfo(APIStateWorkflowDTO apiStateWorkFlowDTO) throws WorkflowException {
    // if credentials are not defined in the workflow-extension.xml file call dcr endpoint and generate a
    // oauth application and pass the client id and secret
    WorkflowProperties workflowProperties = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService().getAPIManagerConfiguration().getWorkflowProperties();
    if (clientId == null || clientSecret == null) {
        String dcrUsername = workflowProperties.getdCREndpointUser();
        String dcrPassword = workflowProperties.getdCREndpointPassword();
        byte[] encodedAuth = Base64.encodeBase64((dcrUsername + ":" + dcrPassword).getBytes(Charset.forName("ISO-8859-1")));
        JSONObject payload = new JSONObject();
        payload.put(PayloadConstants.KEY_OAUTH_APPNAME, WorkflowConstants.WORKFLOW_OAUTH_APP_NAME);
        payload.put(PayloadConstants.KEY_OAUTH_OWNER, dcrUsername);
        payload.put(PayloadConstants.KEY_OAUTH_SAASAPP, "true");
        payload.put(PayloadConstants.KEY_OAUTH_GRANT_TYPES, WorkflowConstants.WORKFLOW_OAUTH_APP_GRANT_TYPES);
        URL serviceEndpointURL = new URL(workflowProperties.getdCREndPoint());
        HttpClient httpClient = APIUtil.getHttpClient(serviceEndpointURL.getPort(), serviceEndpointURL.getProtocol());
        HttpPost httpPost = new HttpPost(workflowProperties.getdCREndPoint());
        String authHeader = "Basic " + new String(encodedAuth);
        httpPost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);
        StringEntity requestEntity = new StringEntity(payload.toJSONString(), ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);
        try {
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
                String responseStr = EntityUtils.toString(entity);
                if (log.isDebugEnabled()) {
                    log.debug("Workflow oauth app created: " + responseStr);
                }
                JSONParser parser = new JSONParser();
                JSONObject obj = (JSONObject) parser.parse(responseStr);
                clientId = (String) obj.get(PayloadConstants.VARIABLE_CLIENTID);
                clientSecret = (String) obj.get(PayloadConstants.VARIABLE_CLIENTSECRET);
            } else {
                String error = "Error while starting the process:  " + response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase();
                log.error(error);
                throw new WorkflowException(error);
            }
        } catch (ClientProtocolException e) {
            String errorMsg = "Error while creating the http client";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Error while connecting to dcr endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing response from DCR endpoint";
            log.error(errorMsg, e);
            throw new WorkflowException(errorMsg, e);
        } finally {
            httpPost.reset();
        }
    }
    apiStateWorkFlowDTO.setClientId(clientId);
    apiStateWorkFlowDTO.setClientSecret(clientSecret);
    apiStateWorkFlowDTO.setScope(WorkflowConstants.API_WF_SCOPE);
    apiStateWorkFlowDTO.setTokenAPI(workflowProperties.getTokenEndPoint());
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) WorkflowProperties(org.wso2.carbon.apimgt.impl.dto.WorkflowProperties) URL(org.apache.axis2.util.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringEntity(org.apache.http.entity.StringEntity) JSONObject(org.json.simple.JSONObject) HttpClient(org.apache.http.client.HttpClient) JSONParser(org.json.simple.parser.JSONParser) ParseException(org.json.simple.parser.ParseException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)18 HttpClient (org.apache.http.client.HttpClient)12 URL (java.net.URL)10 ArrayList (java.util.ArrayList)9 HttpGet (org.apache.http.client.methods.HttpGet)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 HttpResponse (org.apache.http.HttpResponse)8 Gson (com.google.gson.Gson)6 JSONObject (org.json.simple.JSONObject)6 Test (org.junit.Test)6 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)6 Test (org.testng.annotations.Test)6 Response (feign.Response)4 WorkflowProperties (org.wso2.carbon.apimgt.impl.dto.WorkflowProperties)4 JSONParser (org.json.simple.parser.JSONParser)3 ParseException (org.json.simple.parser.ParseException)3 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)3 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)3 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)3