Search in sources :

Example 6 with AuthenticatorService

use of org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService in project carbon-apimgt by wso2.

the class AuthenticatorAPI method redirect.

/**
 * This method provides the DCR application information to the SSO-IS login.
 *
 * @param request Request to call the /login api
 * @return Response - Response object with OAuth data
 */
@OPTIONS
@GET
@Path("/login/{appName}")
@Produces(MediaType.APPLICATION_JSON)
public Response redirect(@Context Request request, @PathParam("appName") String appName) {
    try {
        AuthenticatorService authenticatorService = AuthenticatorAPIFactory.getInstance().getService();
        JsonObject oAuthData = authenticatorService.getAuthenticationConfigurations(appName);
        if (oAuthData.size() == 0) {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Error while creating the OAuth application!").build();
        } else {
            return Response.status(Response.Status.OK).entity(oAuthData).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 : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) JsonObject(com.google.gson.JsonObject) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) OPTIONS(javax.ws.rs.OPTIONS)

Example 7 with AuthenticatorService

use of org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService 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 8 with AuthenticatorService

use of org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService 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)

Example 9 with AuthenticatorService

use of org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService in project carbon-apimgt by wso2.

the class AuthenticatorAPI method logout.

@OPTIONS
@POST
@Produces(MediaType.APPLICATION_JSON)
@Path("/logout/{appName}")
public Response logout(@Context Request request, @PathParam("appName") String appName) {
    Map<String, String> contextPaths = AuthUtil.getContextPaths(appName);
    String environmentName = APIMConfigurationService.getInstance().getEnvironmentConfigurations().getEnvironmentLabel();
    String accessToken = AuthUtil.extractTokenFromHeaders(request, AuthenticatorConstants.ACCESS_TOKEN_2, environmentName);
    if (accessToken != null) {
        try {
            AuthenticatorService authenticatorService = AuthenticatorAPIFactory.getInstance().getService();
            authenticatorService.revokeAccessToken(appName, accessToken);
            // Lets invalidate all the cookies saved.
            NewCookie logoutContextCookie = AuthUtil.cookieBuilder(AuthenticatorConstants.ACCESS_TOKEN_2, "", contextPaths.get(AuthenticatorConstants.Context.LOGOUT_CONTEXT), true, true, AuthenticatorConstants.COOKIE_EXPIRE_TIME, environmentName);
            NewCookie restContextCookie = AuthUtil.cookieBuilder(APIConstants.AccessTokenConstants.AM_TOKEN_MSF4J, "", contextPaths.get(AuthenticatorConstants.Context.REST_API_CONTEXT), true, true, AuthenticatorConstants.COOKIE_EXPIRE_TIME, environmentName);
            NewCookie refreshTokenCookie = AuthUtil.cookieBuilder(AuthenticatorConstants.REFRESH_TOKEN_1, "", contextPaths.get(AuthenticatorConstants.Context.APP_CONTEXT), true, false, AuthenticatorConstants.COOKIE_EXPIRE_TIME, environmentName);
            NewCookie refreshTokenHttpOnlyCookie = AuthUtil.cookieBuilder(AuthenticatorConstants.REFRESH_TOKEN_2, "", contextPaths.get(AuthenticatorConstants.Context.APP_CONTEXT), true, true, AuthenticatorConstants.COOKIE_EXPIRE_TIME, environmentName);
            return Response.ok().cookie(logoutContextCookie, restContextCookie, refreshTokenCookie, refreshTokenHttpOnlyCookie).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();
        }
    }
    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();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) ErrorDTO(org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO) NewCookie(javax.ws.rs.core.NewCookie) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) OPTIONS(javax.ws.rs.OPTIONS)

Example 10 with AuthenticatorService

use of org.wso2.carbon.apimgt.rest.api.authenticator.AuthenticatorService in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetAuthenticationConfigurationsForPublisher.

@Test
public void testGetAuthenticationConfigurationsForPublisher() throws Exception {
    // Happy Path - 200
    // // Mocked response object from DCR api
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setCallBackURL("https://localhost:9292/login/callback/publisher");
    // // Expected data object to be passed to the front-end
    JsonObject oAuthData = new JsonObject();
    String scopes = "apim:api_view apim:api_create apim:api_update apim:api_delete apim:apidef_update " + "apim:api_publish apim:subscription_view apim:subscription_block openid " + "apim:external_services_discover apim:dedicated_gateway";
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CLIENT_ID, oAuthApplicationInfo.getClientId());
    oAuthData.addProperty(KeyManagerConstants.OAUTH_CALLBACK_URIS, oAuthApplicationInfo.getCallBackURL());
    oAuthData.addProperty(KeyManagerConstants.TOKEN_SCOPES, scopes);
    oAuthData.addProperty(KeyManagerConstants.AUTHORIZATION_ENDPOINT, "https://localhost:9443/oauth2/authorize");
    oAuthData.addProperty(AuthenticatorConstants.SSO_ENABLED, ServiceReferenceHolder.getInstance().getAPIMAppConfiguration().isSsoEnabled());
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    multiEnvironmentOverview.setEnabled(true);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    // // Get data object to be passed to the front-end
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    JsonObject responseOAuthDataObj = authenticatorService.getAuthenticationConfigurations("publisher");
    String[] scopesActual = responseOAuthDataObj.get(KeyManagerConstants.TOKEN_SCOPES).toString().split(" ");
    String[] scopesExpected = oAuthData.get(KeyManagerConstants.TOKEN_SCOPES).toString().split(" ");
    Assert.assertEquals(scopesActual.length, scopesExpected.length);
    // Error Path - 500 - When OAuthApplicationInfo is null
    JsonObject emptyOAuthDataObj = new JsonObject();
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(null);
    JsonObject responseEmptyOAuthDataObj = authenticatorService.getAuthenticationConfigurations("publisher");
    Assert.assertEquals(responseEmptyOAuthDataObj, emptyOAuthDataObj);
    // Error Path - When DCR application creation fails and throws an APIManagementException
    Mockito.when(keyManager.createApplication(Mockito.any())).thenThrow(KeyManagementException.class);
    try {
        authenticatorService.getAuthenticationConfigurations("publisher");
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while creating the keys for OAuth application : publisher");
    }
}
Also used : JsonObject(com.google.gson.JsonObject) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)8 APIMConfigurationService (org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService)8 SystemApplicationDao (org.wso2.carbon.apimgt.core.dao.SystemApplicationDao)8 APIMAppConfigurationService (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService)8 KeyManager (org.wso2.carbon.apimgt.core.api.KeyManager)7 EnvironmentConfigurations (org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations)7 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)7 NewCookie (javax.ws.rs.core.NewCookie)5 APIMAppConfigurations (org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations)5 AuthResponseBean (org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean)5 HashMap (java.util.HashMap)4 OPTIONS (javax.ws.rs.OPTIONS)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 MultiEnvironmentOverview (org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview)4 AccessTokenInfo (org.wso2.carbon.apimgt.core.models.AccessTokenInfo)4 ErrorDTO (org.wso2.carbon.apimgt.rest.api.authenticator.dto.ErrorDTO)4 JsonObject (com.google.gson.JsonObject)3 IdentityProvider (org.wso2.carbon.apimgt.core.api.IdentityProvider)3 OAuthApplicationInfo (org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo)3