Search in sources :

Example 11 with Credentials

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

the class DBRetriever method invokeService.

private CloseableHttpResponse invokeService(String endpoint, String tenantDomain) throws IOException, ArtifactSynchronizerException {
    HttpGet method = new HttpGet(endpoint);
    URL url = new URL(endpoint);
    String username = eventHubConfigurationDto.getUsername();
    String password = eventHubConfigurationDto.getPassword();
    byte[] credentials = Base64.encodeBase64((username + APIConstants.DELEM_COLON + password).getBytes(APIConstants.DigestAuthConstants.CHARSET));
    int port = url.getPort();
    String protocol = url.getProtocol();
    method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, APIConstants.DigestAuthConstants.CHARSET));
    if (tenantDomain != null) {
        method.setHeader(APIConstants.HEADER_TENANT, tenantDomain);
    }
    HttpClient httpClient = APIUtil.getHttpClient(port, protocol);
    try {
        return APIUtil.executeHTTPRequest(method, httpClient);
    } catch (APIManagementException e) {
        throw new ArtifactSynchronizerException(e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) URL(java.net.URL)

Example 12 with Credentials

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

the class AMDefaultKeyManagerImpl method getNewApplicationAccessToken.

@Override
public AccessTokenInfo getNewApplicationAccessToken(AccessTokenRequest tokenRequest) throws APIManagementException {
    AccessTokenInfo tokenInfo;
    if (tokenRequest == null) {
        log.warn("No information available to generate Token.");
        return null;
    }
    // When validity time set to a negative value, a token is considered never to expire.
    if (tokenRequest.getValidityPeriod() == OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) {
        // Setting a different -ve value if the set value is -1 (-1 will be ignored by TokenValidator)
        tokenRequest.setValidityPeriod(-2L);
    }
    // Generate New Access Token
    String scopes = String.join(" ", tokenRequest.getScope());
    TokenInfo tokenResponse;
    try {
        String credentials = tokenRequest.getClientId() + ':' + tokenRequest.getClientSecret();
        String authToken = Base64.getEncoder().encodeToString(credentials.getBytes(StandardCharsets.UTF_8));
        if (APIConstants.OAuthConstants.TOKEN_EXCHANGE.equals(tokenRequest.getGrantType())) {
            tokenResponse = authClient.generate(tokenRequest.getClientId(), tokenRequest.getClientSecret(), tokenRequest.getGrantType(), scopes, (String) tokenRequest.getRequestParam(APIConstants.OAuthConstants.SUBJECT_TOKEN), APIConstants.OAuthConstants.JWT_TOKEN_TYPE);
        } else {
            tokenResponse = authClient.generate(authToken, GRANT_TYPE_VALUE, scopes);
        }
    } catch (KeyManagerClientException e) {
        throw new APIManagementException("Error occurred while calling token endpoint - " + e.getReason(), e);
    }
    tokenInfo = new AccessTokenInfo();
    if (StringUtils.isNotEmpty(tokenResponse.getScope())) {
        tokenInfo.setScope(tokenResponse.getScope().split(" "));
    } else {
        tokenInfo.setScope(new String[0]);
    }
    tokenInfo.setAccessToken(tokenResponse.getToken());
    tokenInfo.setValidityPeriod(tokenResponse.getExpiry());
    return tokenInfo;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) KeyManagerClientException(org.wso2.carbon.apimgt.impl.kmclient.KeyManagerClientException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) TokenInfo(org.wso2.carbon.apimgt.impl.kmclient.model.TokenInfo) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo)

Example 13 with Credentials

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

the class BasicAuthenticationInterceptor method handleMessage.

/**
 * This method handles the incoming message by checking if an anonymous api is being called or invalid
 * authorization headers are present in the request. If not, authenticate the request.
 *
 * @param inMessage cxf Message
 */
@Override
@MethodStats
public void handleMessage(Message inMessage) {
    // by-passes the interceptor if user calls an anonymous api
    if (RestApiUtil.checkIfAnonymousAPI(inMessage)) {
        return;
    }
    String tenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    inMessage.put(RestApiConstants.TENANT_DOMAIN, tenantDomain);
    // Extract and check if "Authorization: Basic" is present in the request. If not, by-passes the interceptor.
    // If yes, set the request_authentication_scheme property in the message as basic_auth and execute the basic
    // authentication flow.
    AuthorizationPolicy policy = inMessage.get(AuthorizationPolicy.class);
    if (policy != null) {
        inMessage.put(RestApiConstants.REQUEST_AUTHENTICATION_SCHEME, RestApiConstants.BASIC_AUTHENTICATION);
        // Extract user credentials from the auth header and validate.
        String username = StringUtils.trim(policy.getUserName());
        String password = StringUtils.trim(policy.getPassword());
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            String errorMessage = StringUtils.isEmpty(username) ? "username cannot be null/empty." : "password cannot be null/empty.";
            log.error("Basic Authentication failed: " + errorMessage);
            throw new AuthenticationException("Unauthenticated request");
        } else if (!authenticate(inMessage, username, password)) {
            throw new AuthenticationException("Unauthenticated request");
        }
        log.debug("User logged into web app using Basic Authentication");
    }
}
Also used : AuthorizationPolicy(org.apache.cxf.configuration.security.AuthorizationPolicy) AuthenticationException(org.apache.cxf.interceptor.security.AuthenticationException) MethodStats(org.wso2.carbon.apimgt.rest.api.util.MethodStats)

Example 14 with Credentials

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

the class OAuthTokenGeneratorTest method testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired.

/**
 * Test OAuth backend security with client credentials grant type and when token is expired
 */
@Test
public void testOauthBackendSecurityWithClientCredentialsGrantWhenTokenExpired() throws ParseException, IOException, APIManagementException, APISecurityException {
    // Assign values for test specific properties of mock token response and oAuthEndpoint object.
    // expires_in value is subtracted to replicate the token expiry behaviour.
    mockTokenResponse.setExpiresIn("1800");
    long validTill = System.currentTimeMillis() / 1000 - Long.parseLong(mockTokenResponse.getExpiresIn());
    mockTokenResponse.setValidTill(validTill);
    mockTokenResponse.setRefreshToken(null);
    oAuthEndpoint.setId("testID2");
    oAuthEndpoint.setGrantType("CLIENT_CREDENTIALS");
    // First token generation operation. Token endpoint will be called and the token response will be cached.
    TokenResponse tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    Assert.assertNotNull(tokenCache.getTokenMap().get(oAuthEndpoint.getId()));
    // Second token generation operation. Since the token is expired, the token endpoint will be called during
    // this operation.
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Third token generation operation (replicating the behaviour when the mock token response contains a refresh
    // token).
    mockTokenResponse.setRefreshToken("testRefreshToken");
    tokenResponse = OAuthTokenGenerator.generateToken(oAuthEndpoint, latch);
    Assert.assertNotNull(tokenResponse);
    // Token endpoint will be called three times (during the first, second and third token generation operations).
    PowerMockito.verifyStatic(OAuthClient.class, Mockito.times(3));
    OAuthClient.generateToken(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.any(), Mockito.anyString());
}
Also used : TokenResponse(org.wso2.carbon.apimgt.gateway.mediators.oauth.client.TokenResponse) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 15 with Credentials

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

the class RecommenderDetailsExtractor method getRecommendations.

public String getRecommendations(String userName, String tenantDomain) {
    String recommendationEndpointURL = recommendationEnvironment.getRecommendationServerURL() + APIConstants.RECOMMENDATIONS_GET_RESOURCE;
    AccessTokenGenerator accessTokenGenerator = ServiceReferenceHolder.getInstance().getAccessTokenGenerator();
    try {
        String userID = apiMgtDAO.getUserID(userName);
        URL serverURL = new URL(recommendationEndpointURL);
        int serverPort = serverURL.getPort();
        String serverProtocol = serverURL.getProtocol();
        HttpGet method = new HttpGet(recommendationEndpointURL);
        HttpClient httpClient = APIUtil.getHttpClient(serverPort, serverProtocol);
        if (recommendationEnvironment.getOauthURL() != null) {
            String accessToken = accessTokenGenerator.getAccessToken();
            method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BEARER + accessToken);
        } else {
            byte[] credentials = org.apache.commons.codec.binary.Base64.encodeBase64((recommendationEnvironment.getUserName() + ":" + recommendationEnvironment.getPassword()).getBytes(StandardCharsets.UTF_8));
            method.setHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT, APIConstants.AUTHORIZATION_BASIC + new String(credentials, StandardCharsets.UTF_8));
        }
        method.setHeader(APIConstants.RECOMMENDATIONS_USER_HEADER, userID);
        method.setHeader(APIConstants.RECOMMENDATIONS_ACCOUNT_HEADER, tenantDomain);
        HttpResponse httpResponse = httpClient.execute(method);
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            log.info("Recommendations received for the user " + userName + " from recommendations server");
            String contentString = EntityUtils.toString(httpResponse.getEntity());
            if (log.isDebugEnabled()) {
                log.debug("Recommendations received for user " + userName + " is " + contentString);
            }
            return contentString;
        } else if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED && accessTokenGenerator != null) {
            log.warn("Error getting recommendations from server. Invalid credentials used");
            accessTokenGenerator.removeInvalidToken(new String[] { APIConstants.OAUTH2_DEFAULT_SCOPE });
        } else {
            log.warn("Error getting recommendations from server. Server responded with " + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (IOException e) {
        log.error("Connection failure for the recommendation engine", e);
    } catch (APIManagementException e) {
        log.error("Error while getting recommendations for user " + userName, e);
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) HttpGet(org.apache.http.client.methods.HttpGet) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

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