Search in sources :

Example 1 with ApplicationTokenGenerateRequestDTO

use of org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImplTestCase method testApplicationsApplicationIdGenerateTokenPostErrorCase.

@Test
public void testApplicationsApplicationIdGenerateTokenPostErrorCase() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String accessToken = UUID.randomUUID().toString();
    String clientID = UUID.randomUUID().toString();
    String clientSecret = UUID.randomUUID().toString();
    ApplicationsApiServiceImpl applicationsApiService = new ApplicationsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    ApplicationTokenGenerateRequestDTO generateRequestDTO = new ApplicationTokenGenerateRequestDTO();
    generateRequestDTO.setConsumerKey(clientID);
    generateRequestDTO.setConsumerSecret(clientSecret);
    generateRequestDTO.setRevokeToken("revokeToken");
    generateRequestDTO.setScopes("SCOPE1");
    generateRequestDTO.setValidityPeriod(10000);
    Mockito.doThrow(new APIManagementException("Error Occurred", ExceptionCodes.APPLICATION_TOKEN_GENERATION_FAILED)).when(apiStore).generateApplicationToken(clientID, clientSecret, "SCOPE1", 10000, "revokeToken");
    Response response = applicationsApiService.applicationsApplicationIdGenerateTokenPost(applicationId, generateRequestDTO, null, null, request);
    Assert.assertEquals(500, response.getStatus());
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Response(javax.ws.rs.core.Response) ApplicationTokenGenerateRequestDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Request(org.wso2.msf4j.Request) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 2 with ApplicationTokenGenerateRequestDTO

use of org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost.

@Override
public Response applicationsApplicationIdOauthKeysKeyMappingIdGenerateTokenPost(String applicationId, String keyMappingId, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) throws APIManagementException {
    String username = RestApiCommonUtil.getLoggedInUsername();
    APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
    Application application = apiConsumer.getApplicationByUUID(applicationId);
    if (application != null) {
        if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
            ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyMapping(applicationId, keyMappingId);
            if (appKey != null) {
                String jsonInput = null;
                String grantType;
                if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
                    grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
                } else {
                    grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
                }
                try {
                    // verify that the provided jsonInput is a valid json
                    if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
                        jsonInput = validateAdditionalParameters(grantType, body);
                    }
                } catch (JsonProcessingException | ParseException | ClassCastException e) {
                    RestApiUtil.handleBadRequest("Error while generating " + appKey.getKeyType() + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
                }
                if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
                    appKey.setConsumerSecret(body.getConsumerSecret());
                }
                String[] scopes = body.getScopes().toArray(new String[0]);
                try {
                    AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, appKey.getKeyManager(), grantType);
                    ApplicationTokenDTO appToken = new ApplicationTokenDTO();
                    appToken.setAccessToken(response.getAccessToken());
                    if (response.getScopes() != null) {
                        appToken.setTokenScopes(Arrays.asList(response.getScopes()));
                    }
                    appToken.setValidityTime(response.getValidityPeriod());
                    return Response.ok().entity(appToken).build();
                } catch (APIManagementException e) {
                    Long errorCode = e.getErrorHandler() != null ? e.getErrorHandler().getErrorCode() : ExceptionCodes.INTERNAL_ERROR.getErrorCode();
                    RestApiUtil.handleBadRequest(e.getMessage(), errorCode, log);
                }
            } else {
                RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyMappingId, log);
            }
        } else {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } else {
        RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
    }
    return null;
}
Also used : ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ParseException(org.json.simple.parser.ParseException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 3 with ApplicationTokenGenerateRequestDTO

use of org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdGenerateTokenPost.

/**
 * Generate an application token
 *
 * @param applicationId   Application ID
 * @param body            Application information which are required to generate tokens
 * @param ifMatch         If-Match header value
 * @param ifUnmodifiedSince If-UnModified-Since header value
 * @param request         msf4j request object
 * @return Generated application key detials
 * @throws NotFoundException When the particular resource does not exist in the system
 */
@Override
public Response applicationsApplicationIdGenerateTokenPost(String applicationId, ApplicationTokenGenerateRequestDTO body, String ifMatch, String ifUnmodifiedSince, Request request) throws NotFoundException {
    try {
        String username = RestApiUtil.getLoggedInUsername(request);
        APIStore apiConsumer = RestApiUtil.getConsumer(username);
        ApplicationToken token = apiConsumer.generateApplicationToken(body.getConsumerKey(), body.getConsumerSecret(), body.getScopes(), body.getValidityPeriod(), body.getRevokeToken());
        ApplicationTokenDTO appToken = ApplicationKeyMappingUtil.fromApplicationTokenToDTO(token);
        return Response.ok().entity(appToken).build();
    } catch (APIManagementException e) {
        String errorMessage = "Error occurred while generating application tokens for application: " + applicationId;
        Map<String, String> paramList = new HashMap<>();
        paramList.put(APIMgtConstants.ExceptionsConstants.APPLICATION_ID, applicationId);
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenDTO) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO) ApplicationToken(org.wso2.carbon.apimgt.core.models.ApplicationToken) HashMap(java.util.HashMap) Map(java.util.Map) APIStore(org.wso2.carbon.apimgt.core.api.APIStore)

Example 4 with ApplicationTokenGenerateRequestDTO

use of org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImplTestCase method testApplicationsApplicationIdGenerateTokenPost.

@Test
public void testApplicationsApplicationIdGenerateTokenPost() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String accessToken = UUID.randomUUID().toString();
    String clientID = UUID.randomUUID().toString();
    String clientSecret = UUID.randomUUID().toString();
    ApplicationsApiServiceImpl applicationsApiService = new ApplicationsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    ApplicationToken applicationToken = new ApplicationToken();
    applicationToken.setAccessToken(accessToken);
    applicationToken.setValidityPeriod(10000);
    applicationToken.setScopes("SCOPE1");
    Mockito.when(apiStore.generateApplicationToken(clientID, clientSecret, "SCOPE1", 1000, "revokeToken")).thenReturn(applicationToken);
    ApplicationTokenGenerateRequestDTO generateRequestDTO = new ApplicationTokenGenerateRequestDTO();
    generateRequestDTO.setConsumerKey(clientID);
    generateRequestDTO.setConsumerSecret(clientSecret);
    generateRequestDTO.setRevokeToken("revokeToken");
    generateRequestDTO.setScopes("SCOPE1");
    generateRequestDTO.setValidityPeriod(10000);
    Response response = applicationsApiService.applicationsApplicationIdGenerateTokenPost(applicationId, generateRequestDTO, null, null, request);
    Assert.assertEquals(200, response.getStatus());
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) ApplicationCreationResponse(org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse) Response(javax.ws.rs.core.Response) ApplicationTokenGenerateRequestDTO(org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO) Request(org.wso2.msf4j.Request) ApplicationToken(org.wso2.carbon.apimgt.core.models.ApplicationToken) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 5 with ApplicationTokenGenerateRequestDTO

use of org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO in project carbon-apimgt by wso2.

the class ApplicationsApiServiceImpl method applicationsApplicationIdKeysKeyTypeGenerateTokenPost.

@Override
public Response applicationsApplicationIdKeysKeyTypeGenerateTokenPost(String applicationId, String keyType, ApplicationTokenGenerateRequestDTO body, String ifMatch, MessageContext messageContext) {
    try {
        String username = RestApiCommonUtil.getLoggedInUsername();
        APIConsumer apiConsumer = RestApiCommonUtil.getConsumer(username);
        Application application = apiConsumer.getApplicationByUUID(applicationId);
        if (application != null) {
            if (RestAPIStoreUtils.isUserAccessAllowedForApplication(application)) {
                ApplicationKeyDTO appKey = getApplicationKeyByAppIDAndKeyType(applicationId, keyType);
                if (appKey != null) {
                    String jsonInput = null;
                    String grantType;
                    if (ApplicationTokenGenerateRequestDTO.GrantTypeEnum.TOKEN_EXCHANGE.equals(body.getGrantType())) {
                        grantType = APIConstants.OAuthConstants.TOKEN_EXCHANGE;
                    } else {
                        grantType = APIConstants.GRANT_TYPE_CLIENT_CREDENTIALS;
                    }
                    try {
                        // verify that the provided jsonInput is a valid json
                        if (body.getAdditionalProperties() != null && !body.getAdditionalProperties().toString().isEmpty()) {
                            jsonInput = validateAdditionalParameters(grantType, body);
                        }
                    } catch (JsonProcessingException | ParseException | ClassCastException e) {
                        RestApiUtil.handleBadRequest("Error while generating " + keyType + " token for " + "application " + applicationId + ". Invalid jsonInput '" + body.getAdditionalProperties() + "' provided.", log);
                    }
                    if (StringUtils.isNotEmpty(body.getConsumerSecret())) {
                        appKey.setConsumerSecret(body.getConsumerSecret());
                    }
                    String[] scopes = body.getScopes().toArray(new String[0]);
                    AccessTokenInfo response = apiConsumer.renewAccessToken(body.getRevokeToken(), appKey.getConsumerKey(), appKey.getConsumerSecret(), body.getValidityPeriod().toString(), scopes, jsonInput, APIConstants.KeyManager.DEFAULT_KEY_MANAGER, grantType);
                    ApplicationTokenDTO appToken = new ApplicationTokenDTO();
                    appToken.setAccessToken(response.getAccessToken());
                    appToken.setTokenScopes(Arrays.asList(response.getScopes()));
                    appToken.setValidityTime(response.getValidityPeriod());
                    return Response.ok().entity(appToken).build();
                } else {
                    RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APP_CONSUMER_KEY, keyType, log);
                }
            } else {
                RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
            }
        } else {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_APPLICATION, applicationId, log);
        }
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Error while generating " + keyType + " token for application " + applicationId, e, log);
    }
    return null;
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.api.model.AccessTokenInfo) ApplicationTokenDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ApplicationKeyDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer) ParseException(org.json.simple.parser.ParseException) ExportedApplication(org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication) Application(org.wso2.carbon.apimgt.api.model.Application) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

APIStore (org.wso2.carbon.apimgt.core.api.APIStore)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 Response (javax.ws.rs.core.Response)2 ParseException (org.json.simple.parser.ParseException)2 Test (org.junit.Test)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)2 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)2 AccessTokenInfo (org.wso2.carbon.apimgt.api.model.AccessTokenInfo)2 Application (org.wso2.carbon.apimgt.api.model.Application)2 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)2 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)2 ApplicationToken (org.wso2.carbon.apimgt.core.models.ApplicationToken)2 ApplicationCreationResponse (org.wso2.carbon.apimgt.core.workflow.ApplicationCreationResponse)2 GeneralWorkflowResponse (org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse)2 ApplicationTokenGenerateRequestDTO (org.wso2.carbon.apimgt.rest.api.store.dto.ApplicationTokenGenerateRequestDTO)2 ApplicationKeyDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO)2 ApplicationTokenDTO (org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO)2 ExportedApplication (org.wso2.carbon.apimgt.rest.api.store.v1.models.ExportedApplication)2 Request (org.wso2.msf4j.Request)2