Search in sources :

Example 11 with AccessTokenInfo

use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByJWTGrant.

@Test
public void testGetNewAccessTokenByJWTGrant() 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 - JWT grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.JWT_GRANT_TYPE, null, null, null, -2L, null, null, null, "xxx-assertion-xxx");
    // //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().generateJWTGrantAccessToken(tokenRequest.getAssertion(), tokenRequest.getGrantType(), 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 12 with AccessTokenInfo

use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByAuthorizationCodeGrant.

@Test
public void testGetNewAccessTokenByAuthorizationCodeGrant() 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 - authorization code grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE, null, null, null, -2L, "xxx-auth-code-xxx", "http://test.callback/url", 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().generateAuthCodeGrantAccessToken(tokenRequest.getAuthorizationCode(), tokenRequest.getCallbackURI(), 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 13 with AccessTokenInfo

use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.

the class DefaultKeyManagerImplTestCase method testGetNewAccessTokenByPasswordGrant.

@Test
public void testGetNewAccessTokenByPasswordGrant() throws Exception {
    DCRMServiceStub dcrmServiceStub = Mockito.mock(DCRMServiceStub.class);
    OAuth2ServiceStubs oAuth2ServiceStub = Mockito.mock(OAuth2ServiceStubs.class);
    OAuth2ServiceStubs.TokenServiceStub tokenStub = Mockito.mock(OAuth2ServiceStubs.TokenServiceStub.class);
    OAuth2ServiceStubs.RevokeServiceStub revokeStub = Mockito.mock(OAuth2ServiceStubs.RevokeServiceStub.class);
    ScopeRegistration scopeRegistration = Mockito.mock(ScopeRegistration.class);
    DefaultKeyManagerImpl kmImpl = new DefaultKeyManagerImpl(dcrmServiceStub, oAuth2ServiceStub, scopeRegistration);
    // happy path - 200 - password grant type
    // //request to key manager
    AccessTokenRequest tokenRequest = createKeyManagerTokenRequest(consumerKey, consumerSecret, KeyManagerConstants.PASSWORD_GRANT_TYPE, "user1", "pass1", "xxx-old-token-xxx", 7200L, null, null, null, null);
    // //mocked response from /token service
    OAuth2TokenInfo oAuth2TokenInfo = createTokenServiceResponse(tokenRequest);
    // //expected response from key manager
    AccessTokenInfo accessTokenInfo = createExpectedKeyManagerResponse(oAuth2TokenInfo);
    Response revokeTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), feign.Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getRevokeServiceStub()).thenReturn(revokeStub);
    Mockito.when(revokeStub.revokeAccessToken(tokenRequest.getTokenToRevoke(), tokenRequest.getClientId(), tokenRequest.getClientSecret())).thenReturn(revokeTokenResponse);
    Response newTokenResponse = Response.builder().status(200).headers(new HashMap<>()).body(new Gson().toJson(oAuth2TokenInfo), feign.Util.UTF_8).build();
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub()).thenReturn(tokenStub);
    Mockito.when(oAuth2ServiceStub.getTokenServiceStub().generatePasswordGrantAccessToken(tokenRequest.getResourceOwnerUsername(), tokenRequest.getResourceOwnerPassword(), 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 : Gson(com.google.gson.Gson) ScopeRegistration(org.wso2.carbon.apimgt.core.auth.ScopeRegistration) 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) Response(feign.Response) OAuth2IntrospectionResponse(org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) DCRMServiceStub(org.wso2.carbon.apimgt.core.auth.DCRMServiceStub) AccessTokenRequest(org.wso2.carbon.apimgt.core.models.AccessTokenRequest) Test(org.testng.annotations.Test)

Example 14 with AccessTokenInfo

use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.

the class AuthenticatorAPI method callback.

/**
 * This is the API which IDP redirects the user after authentication.
 *
 * @param request           Request to call /callback api
 * @param appName           Name of the application (publisher/store/admin)
 * @param authorizationCode Authorization-Code
 * @return Response - Response with redirect URL
 */
@OPTIONS
@GET
@Path("/callback/{appName}")
@Produces(MediaType.APPLICATION_JSON)
public Response callback(@Context Request request, @PathParam("appName") String appName, @QueryParam("code") String authorizationCode) {
    String grantType = KeyManagerConstants.AUTHORIZATION_CODE_GRANT_TYPE;
    try {
        AuthenticatorService authenticatorService = AuthenticatorAPIFactory.getInstance().getService();
        AuthResponseBean authResponseBean;
        Map<String, NewCookie> cookies = new HashMap<>();
        Map<String, String> contextPaths = AuthUtil.getContextPaths(appName);
        AccessTokenInfo accessTokenInfo = authenticatorService.getTokens(appName, grantType, null, null, null, 0, authorizationCode, null, null);
        authResponseBean = authenticatorService.getResponseBeanFromTokenInfo(accessTokenInfo);
        authenticatorService.setupAccessTokenParts(cookies, authResponseBean, accessTokenInfo.getAccessToken(), contextPaths, true);
        log.debug("Set cookies for {} application.", appName);
        if (AuthenticatorConstants.PUBLISHER_APPLICATION.equals(appName) || AuthenticatorConstants.STORE_APPLICATION.equals(appName)) {
            URI targetURIForRedirection = authenticatorService.getUIServiceRedirectionURI(appName, authResponseBean);
            return Response.status(Response.Status.FOUND).header(HttpHeaders.LOCATION, targetURIForRedirection).cookie(cookies.get(AuthenticatorConstants.Context.REST_API_CONTEXT), cookies.get(AuthenticatorConstants.Context.LOGOUT_CONTEXT)).build();
        } else {
            URI targetURIForRedirection = authenticatorService.getUIServiceRedirectionURI(appName, null);
            return Response.status(Response.Status.FOUND).header(HttpHeaders.LOCATION, targetURIForRedirection).entity(authResponseBean).cookie(cookies.get(AuthenticatorConstants.Context.REST_API_CONTEXT), cookies.get(AuthenticatorConstants.Context.LOGOUT_CONTEXT), cookies.get(AuthenticatorConstants.AUTH_USER)).build();
        }
    } catch (APIManagementException e) {
        ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null);
        log.error(e.getMessage(), e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    } catch (URISyntaxException e) {
        log.error(e.getMessage(), e);
        return Response.status(e.getIndex()).build();
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    }
}
Also used : HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) UnsupportedEncodingException(java.io.UnsupportedEncodingException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) AuthResponseBean(org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) OPTIONS(javax.ws.rs.OPTIONS)

Example 15 with AccessTokenInfo

use of org.wso2.carbon.apimgt.core.models.AccessTokenInfo in project carbon-apimgt by wso2.

the class AuthenticatorAPI method authenticate.

/**
 * This method authenticate the user for store app.
 */
@OPTIONS
@POST
@Path("/token/{appName}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA })
public Response authenticate(@Context Request request, @PathParam("appName") String appName, @FormDataParam("username") String userName, @FormDataParam("password") String password, @FormDataParam("assertion") String assertion, @FormDataParam("grant_type") String grantType, @FormDataParam("validity_period") String validityPeriod, @FormDataParam("remember_me") boolean isRememberMe, @FormDataParam("scopes") String scopesList) {
    try {
        AuthenticatorService authenticatorService = AuthenticatorAPIFactory.getInstance().getService();
        IdentityProvider identityProvider = APIManagerFactory.getInstance().getIdentityProvider();
        AuthResponseBean authResponseBean;
        Map<String, NewCookie> cookies = new HashMap<>();
        String refreshToken = null;
        if (AuthenticatorConstants.REFRESH_GRANT.equals(grantType)) {
            String environmentName = APIMConfigurationService.getInstance().getEnvironmentConfigurations().getEnvironmentLabel();
            refreshToken = AuthUtil.extractTokenFromHeaders(request, AuthenticatorConstants.REFRESH_TOKEN_2, environmentName);
            if (refreshToken == null) {
                ErrorDTO errorDTO = new ErrorDTO();
                errorDTO.setCode(ExceptionCodes.INVALID_AUTHORIZATION_HEADER.getErrorCode());
                errorDTO.setMessage(ExceptionCodes.INVALID_AUTHORIZATION_HEADER.getErrorMessage());
                return Response.status(Response.Status.UNAUTHORIZED).entity(errorDTO).build();
            }
        }
        Map<String, String> contextPaths = AuthUtil.getContextPaths(appName);
        AccessTokenInfo accessTokenInfo = authenticatorService.getTokens(appName, grantType, userName, password, refreshToken, Long.parseLong(validityPeriod), null, assertion, identityProvider);
        authResponseBean = authenticatorService.getResponseBeanFromTokenInfo(accessTokenInfo);
        authenticatorService.setupAccessTokenParts(cookies, authResponseBean, accessTokenInfo.getAccessToken(), contextPaths, false);
        String refreshTokenNew = accessTokenInfo.getRefreshToken();
        // Refresh token is not set to cookie if remember me is not set.
        if (refreshTokenNew != null && (AuthenticatorConstants.REFRESH_GRANT.equals(grantType) || (AuthenticatorConstants.PASSWORD_GRANT.equals(grantType) && isRememberMe))) {
            authenticatorService.setupRefreshTokenParts(cookies, refreshTokenNew, contextPaths);
            return Response.ok(authResponseBean, MediaType.APPLICATION_JSON).cookie(cookies.get(AuthenticatorConstants.Context.REST_API_CONTEXT), cookies.get(AuthenticatorConstants.Context.LOGOUT_CONTEXT), cookies.get(AuthenticatorConstants.Context.APP_CONTEXT), cookies.get(AuthenticatorConstants.Context.LOGIN_CONTEXT)).header(AuthenticatorConstants.REFERER_HEADER, (request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) != null && request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER).equals(request.getHeader(AuthenticatorConstants.REFERER_HEADER))) ? "" : request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) != null ? request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) : "").build();
        } else {
            return Response.ok(authResponseBean, MediaType.APPLICATION_JSON).cookie(cookies.get(AuthenticatorConstants.Context.REST_API_CONTEXT), cookies.get(AuthenticatorConstants.Context.LOGOUT_CONTEXT)).header(AuthenticatorConstants.REFERER_HEADER, (request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) != null && request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER).equals(request.getHeader(AuthenticatorConstants.REFERER_HEADER))) ? "" : request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) != null ? request.getHeader(AuthenticatorConstants.X_ALT_REFERER_HEADER) : "").build();
        }
    } catch (APIManagementException e) {
        ErrorDTO errorDTO = AuthUtil.getErrorDTO(e.getErrorHandler(), null);
        log.error(e.getMessage(), e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
}
Also used : AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) AuthResponseBean(org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) OPTIONS(javax.ws.rs.OPTIONS)

Aggregations

AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)17 KeyManagementException (org.wso2.carbon.apimgt.core.exception.KeyManagementException)11 Response (feign.Response)8 OAuth2IntrospectionResponse (org.wso2.carbon.apimgt.core.auth.dto.OAuth2IntrospectionResponse)8 AccessTokenRequest (org.wso2.carbon.apimgt.core.models.AccessTokenRequest)7 Gson (com.google.gson.Gson)6 Test (org.testng.annotations.Test)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 OAuth2TokenInfo (org.wso2.carbon.apimgt.core.auth.dto.OAuth2TokenInfo)6 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)6 AuthResponseBean (org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean)4 HashMap (java.util.HashMap)3 Test (org.junit.Test)3 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)3 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)3 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)3 GsonDecoder (feign.gson.GsonDecoder)2 IOException (java.io.IOException)2