Search in sources :

Example 6 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest in project carbon-apimgt by wso2.

the class AbstractKeyManager method buildAccessTokenRequestFromJSON.

public AccessTokenRequest buildAccessTokenRequestFromJSON(String jsonInput, AccessTokenRequest tokenRequest) throws APIManagementException {
    if (jsonInput == null || jsonInput.isEmpty()) {
        log.debug("JsonInput is null or Empty.");
        return tokenRequest;
    }
    JSONParser parser = new JSONParser();
    JSONObject jsonObject;
    if (tokenRequest == null) {
        log.debug("Input request is null. Creating a new Request Object.");
        tokenRequest = new AccessTokenRequest();
    }
    try {
        jsonObject = (JSONObject) parser.parse(jsonInput);
        // Getting parameters from input string and setting in TokenRequest.
        if (jsonObject != null && !jsonObject.isEmpty()) {
            Map<String, Object> params = (Map<String, Object>) jsonObject;
            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_ID)) {
                tokenRequest.setClientId((String) params.get(ApplicationConstants.OAUTH_CLIENT_ID));
            }
            if (null != params.get(ApplicationConstants.OAUTH_CLIENT_SECRET)) {
                tokenRequest.setClientSecret((String) params.get(ApplicationConstants.OAUTH_CLIENT_SECRET));
            }
            if (null != params.get(ApplicationConstants.VALIDITY_PERIOD)) {
                tokenRequest.setValidityPeriod(Long.parseLong((String) params.get(ApplicationConstants.VALIDITY_PERIOD)));
            }
            if (APIConstants.OAuthConstants.TOKEN_EXCHANGE.equals(tokenRequest.getGrantType())) {
                tokenRequest.addRequestParam(APIConstants.OAuthConstants.SUBJECT_TOKEN, params.get(APIConstants.OAuthConstants.SUBJECT_TOKEN));
            }
            return tokenRequest;
        }
    } catch (ParseException e) {
        handleException("Error occurred while parsing JSON String", e);
    }
    return null;
}
Also used : JSONObject(org.json.simple.JSONObject) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map)

Example 7 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest in project carbon-apimgt by wso2.

the class ApplicationUtilsTestCase method testPopulateTokenRequestWhenAccessTokenNotNull.

@Test
public void testPopulateTokenRequestWhenAccessTokenNotNull() throws APIManagementException {
    PowerMockito.mockStatic(KeyManagerHolder.class);
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    ApplicationUtils.populateTokenRequest(keyManager, "", accessTokenRequest);
    Mockito.verify(keyManager, Mockito.times(1)).buildAccessTokenRequestFromJSON(Matchers.anyString(), Matchers.any(AccessTokenRequest.class));
}
Also used : AccessTokenRequest(org.wso2.carbon.apimgt.api.model.AccessTokenRequest) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 8 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest 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 9 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest in project carbon-apimgt by wso2.

the class APIStoreImpl method generateApplicationToken.

@Override
public ApplicationToken generateApplicationToken(String clientId, String clientSecret, String scopes, long validityPeriod, String tokenToBeRevoked) throws APIManagementException {
    log.debug("Generating a new application access token");
    AccessTokenRequest accessTokenRequest = new AccessTokenRequest();
    accessTokenRequest.setClientId(clientId);
    accessTokenRequest.setClientSecret(clientSecret);
    accessTokenRequest.setGrantType(KeyManagerConstants.CLIENT_CREDENTIALS_GRANT_TYPE);
    if (StringUtils.isEmpty(scopes)) {
        scopes = KeyManagerConstants.OAUTH2_DEFAULT_SCOPE;
    }
    accessTokenRequest.setScopes(scopes);
    accessTokenRequest.setValidityPeriod(validityPeriod);
    accessTokenRequest.setTokenToRevoke(tokenToBeRevoked);
    AccessTokenInfo newToken = getKeyManager().getNewAccessToken(accessTokenRequest);
    ApplicationToken applicationToken = new ApplicationToken();
    applicationToken.setAccessToken(newToken.getAccessToken());
    applicationToken.setValidityPeriod(newToken.getValidityPeriod());
    applicationToken.setScopes(newToken.getScopes());
    log.debug("Successfully created a new application access token.");
    return applicationToken;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) ApplicationToken(org.wso2.carbon.apimgt.core.models.ApplicationToken)

Example 10 with AccessTokenRequest

use of org.wso2.carbon.apimgt.api.model.AccessTokenRequest in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenErrorCases.

@Test
public void testGetNewAccessTokenErrorCases() 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);
    // error case - tokenRequest is null
    try {
        kmImpl.getNewAccessToken(null);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("No information available to generate Token. " + "AccessTokenRequest is null"));
    }
    // error case - invalid grant type
    final String invalidGrantType = "invalid_grant";
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, invalidGrantType, null, null, null, -2L, null, null, null, null);
    try {
        kmImpl.getNewAccessToken(tokenRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().contains("Invalid access token request. Unsupported grant type: " + invalidGrantType));
    }
    // error case - response is null (mock condition (validity period) is different)
    tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.REFRESH_GRANT_TYPE, null, null, null, -1L, null, null, "xxx-refresh-token-xxx", null);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(null);
    try {
        kmImpl.getNewAccessToken(tokenRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().equals("Error occurred while generating an access token. " + "Response is null"));
    }
    // error case - token response non-200
    // //request to key manager
    tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.REFRESH_GRANT_TYPE, null, null, null, 7200L, null, null, "xxx-refresh-token-xxx", null);
    final int errorCode = 500;
    Response errorResponse = Response.builder().status(errorCode).headers(new HashMap<>()).body("backend error occurred", Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generateRefreshGrantAccessToken(tokenRequest.getRefreshToken(), tokenRequest.getScopes(), tokenRequest.getValidityPeriod(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(errorResponse);
    try {
        kmImpl.getNewAccessToken(tokenRequest);
        Assert.fail("Exception was expected, but wasn't thrown");
    } catch (KeyManagementException ex) {
        Assert.assertTrue(ex.getMessage().startsWith("Token generation request failed. HTTP error code: " + errorCode));
    }
}
Also used : Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) 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) Test(org.testng.annotations.Test)

Aggregations

AccessTokenRequest (org.wso2.carbon.apimgt.api.model.AccessTokenRequest)13 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)9 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)9 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)8 Response (feign.Response)7 Test (org.junit.Test)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)7 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)7 Test (org.testng.annotations.Test)6 OAuthApplicationInfo (org.wso2.carbon.apimgt.api.model.OAuthApplicationInfo)6 DCRMServiceStub (org.wso2.carbon.apimgt.core.auth.DCRMServiceStub)6 OAuth2ServiceStubs (org.wso2.carbon.apimgt.core.auth.OAuth2ServiceStubs)6 ScopeRegistration (org.wso2.carbon.apimgt.core.auth.ScopeRegistration)6 Gson (com.google.gson.Gson)5 KeyManagerConfigurationDTO (org.wso2.carbon.apimgt.api.dto.KeyManagerConfigurationDTO)5 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)4 KeyManager (org.wso2.carbon.apimgt.api.model.KeyManager)4 JSONObject (org.json.simple.JSONObject)3