use of org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean in project carbon-apimgt by wso2.
the class AuthenticatorServiceTestCase method testGetUIServiceRedirectionURI.
@Test
public void testGetUIServiceRedirectionURI() throws URISyntaxException, UnsupportedEncodingException {
// Happy Path
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);
SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
KeyManager keyManager = Mockito.mock(KeyManager.class);
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
// // empty string for first value in allowed list
environmentConfigurations.setAllowedHosts(Collections.singletonList(""));
apimAppConfigurations.setApimBaseUrl("https://localhost:9443/");
URI expectedUri = new URI("https://localhost:9443/publisher");
URI actualUri = authenticatorService.getUIServiceRedirectionURI("publisher", null);
Assert.assertEquals(expectedUri, actualUri);
// // SSO callback
AuthResponseBean authResponseBean = new AuthResponseBean();
authResponseBean.setTokenValid(true);
authResponseBean.setType("bearer");
authResponseBean.setScopes("xxx-scopes-xxx");
authResponseBean.setValidityPeriod(3449);
authResponseBean.setAuthUser("admin");
authResponseBean.setIdToken("xxx-id-token-xxx");
authResponseBean.setPartialToken("xxx-partial-token-xxx");
expectedUri = new URI("https://localhost:9443/publisher/login?user_name=admin&id_token=xxx-id-token-xxx&" + "partial_token=xxx-partial-token-xxx&scopes=xxx-scopes-xxx&validity_period=3449");
actualUri = authenticatorService.getUIServiceRedirectionURI("publisher", authResponseBean);
Assert.assertEquals(expectedUri, actualUri);
// // non empty string for first value in allowed list
environmentConfigurations.setAllowedHosts(Arrays.asList("localhost:9444", "localhost: 9445", "localhost:9446"));
expectedUri = new URI("https://localhost:9444/publisher");
actualUri = authenticatorService.getUIServiceRedirectionURI("publisher", null);
Assert.assertEquals(expectedUri, actualUri);
}
use of org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean 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();
}
}
use of org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean 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();
}
}
use of org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean in project carbon-apimgt by wso2.
the class AuthenticatorServiceTestCase method testSetupAccessTokenParts.
@Test
public void testSetupAccessTokenParts() {
// Happy Path
APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
KeyManager keyManager = Mockito.mock(KeyManager.class);
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
Map<String, NewCookie> cookies = new HashMap<>();
AuthResponseBean authResponseBean = new AuthResponseBean();
Map<String, String> contextPaths = new HashMap<>();
contextPaths.put("APP_CONTEXT", "/publisher");
contextPaths.put("LOGOUT_CONTEXT", "/login/logout/publisher");
contextPaths.put("LOGIN_CONTEXT", "/login/token/publisher");
contextPaths.put("REST_API_CONTEXT", "/api/am/publisher");
String accessToken = "xxx-access_token_part_1-xxx-xxx-access_token_part_2-xxx-";
environmentConfigurations.setEnvironmentLabel("Production");
Map<String, NewCookie> expectedCookies = new HashMap<>();
expectedCookies.put("REST_API_CONTEXT", new NewCookie("WSO2_AM_TOKEN_MSF4J_Production", "xxx-access_token_part_2-xxx-; path=/api/am/publisher; HttpOnly; Secure; "));
expectedCookies.put("LOGOUT_CONTEXT", new NewCookie("WSO2_AM_TOKEN_2_Production", "xxx-access_token_part_2-xxx-; path=/login/logout/publisher; HttpOnly; Secure; "));
AuthResponseBean expectedAuthResponseBean = new AuthResponseBean();
expectedAuthResponseBean.setPartialToken("xxx-access_token_part_1-xxx-");
authenticatorService.setupAccessTokenParts(cookies, authResponseBean, accessToken, contextPaths, false);
Assert.assertEquals(expectedCookies, cookies);
Assert.assertEquals(expectedAuthResponseBean.getPartialToken(), authResponseBean.getPartialToken());
// // sso enabled
cookies = new HashMap<>();
authResponseBean = new AuthResponseBean();
authResponseBean.setAuthUser("John");
expectedCookies.put("LOGGED_IN_USER", new NewCookie("LOGGED_IN_USER_Production", "John; path=/publisher; Secure; "));
authenticatorService.setupAccessTokenParts(cookies, authResponseBean, accessToken, contextPaths, true);
Assert.assertEquals(expectedCookies, cookies);
Assert.assertEquals(expectedAuthResponseBean.getPartialToken(), authResponseBean.getPartialToken());
}
use of org.wso2.carbon.apimgt.rest.api.authenticator.utils.bean.AuthResponseBean in project carbon-apimgt by wso2.
the class AuthenticatorServiceTestCase method testSetAccessTokenData.
@Test
public void testSetAccessTokenData() throws Exception {
// Happy Path
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);
// // AccessTokenInfo object
AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
accessTokenInfo.setIdToken("eyJ4NXQiOiJObUptT0dVeE16WmxZak0yWkRSaE5UWmxZVEExWXpkaFpUUmlPV0UwTldJMk0ySm1PVGMxWkEiLCJraWQiOiJkMGVjNTE0YTMyYjZmODhjMGFiZDEyYTI4NDA2OTliZGQzZGViYTlkIiwiYWxnIjoiUlMyNTYifQ.eyJhdF9oYXNoIjoiWGg3bFZpSDZDS2pZLXRIT09JaWN5QSIsInN1YiI6ImFkbWluIiwiYXVkIjpbInR6NlJGQnhzdV93Z0RCd3FyUThvVmo3d25FTWEiXSwiYXpwIjoidHo2UkZCeHN1X3dnREJ3cXJROG9Wajd3bkVNYSIsImF1dGhfdGltZSI6MTUwMTczMzQ1NiwiaXNzIjoiaHR0cHM6XC9cL2xvY2FsaG9zdDo5NDQzXC9vYXV0aDJcL3Rva2VuIiwiZXhwIjoxNTAxNzM3MDU3LCJpYXQiOjE1MDE3MzM0NTd9.XXX-XXX");
accessTokenInfo.setValidityPeriod(-2L);
accessTokenInfo.setScopes("apim:subscribe openid");
// // Expected AuthResponseBean object
AuthResponseBean expectedAuthResponseBean = new AuthResponseBean();
expectedAuthResponseBean.setTokenValid(true);
expectedAuthResponseBean.setAuthUser("admin");
expectedAuthResponseBean.setScopes(accessTokenInfo.getScopes());
expectedAuthResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
expectedAuthResponseBean.setValidityPeriod(accessTokenInfo.getValidityPeriod());
expectedAuthResponseBean.setIdToken(accessTokenInfo.getIdToken());
KeyManager keyManager = Mockito.mock(KeyManager.class);
SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
// // Actual response
AuthResponseBean authResponseBean = authenticatorService.getResponseBeanFromTokenInfo(accessTokenInfo);
Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedAuthResponseBean, authResponseBean));
// Happy Path - When id token is null
// // AccessTokenInfo object with null id token
AccessTokenInfo invalidTokenInfo = new AccessTokenInfo();
invalidTokenInfo.setValidityPeriod(-2L);
invalidTokenInfo.setScopes("apim:subscribe openid");
// // Expected AuthResponseBean object when id token is null
AuthResponseBean expectedResponseBean = new AuthResponseBean();
expectedResponseBean.setTokenValid(true);
expectedResponseBean.setScopes(invalidTokenInfo.getScopes());
expectedResponseBean.setType(AuthenticatorConstants.BEARER_PREFIX);
expectedResponseBean.setValidityPeriod(invalidTokenInfo.getValidityPeriod());
expectedResponseBean.setIdToken(invalidTokenInfo.getIdToken());
expectedResponseBean.setAuthUser("admin");
// // Actual response when id token is null
AuthResponseBean responseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidTokenInfo);
Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedResponseBean, responseBean));
// Error Path - When parsing JWT fails and throws KeyManagementException
// // AccessTokenInfo object with invalid ID token format
AccessTokenInfo invalidAccessTokenInfo = new AccessTokenInfo();
invalidAccessTokenInfo.setIdToken("xxx-invalid-id-token-xxx");
invalidAccessTokenInfo.setValidityPeriod(-2L);
invalidAccessTokenInfo.setScopes("apim:subscribe openid");
try {
AuthResponseBean errorResponseBean = authenticatorService.getResponseBeanFromTokenInfo(invalidAccessTokenInfo);
} catch (KeyManagementException e) {
Assert.assertEquals(900986, e.getErrorHandler().getErrorCode());
}
}
Aggregations