use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2ServiceTest method testValidateClientInfoWithInvalidAppState.
@Test(dataProvider = "InvalidAppStatDataProvider")
public void testValidateClientInfoWithInvalidAppState(String appState) throws Exception {
OAuthAppDO oAuthAppDO = getOAuthAppDO(clientId, "dummyGrantType", "dummyCallbackUrl", "dummyTenantDomain");
oAuthAppDO.setState(appState);
AppInfoCache.getInstance().addToCache(clientId, oAuthAppDO);
OAuth2ClientValidationResponseDTO oAuth2ClientValidationResponseDTO = oAuth2Service.validateClientInfo(clientId, "dummyCallbackUrI");
assertNotNull(oAuth2ClientValidationResponseDTO);
assertEquals(oAuth2ClientValidationResponseDTO.getErrorCode(), OAuth2ErrorCodes.INVALID_CLIENT);
assertFalse(oAuth2ClientValidationResponseDTO.isValidClient());
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest.
/**
* Tests the scenario of authorization request from the client
*/
@Test(dataProvider = "provideAuthzRequestData", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest(String clientId, String redirectUri, String pkceChallengeCode, String pkceChallengeMethod, String prompt, boolean clientValid, boolean pkceEnabled, boolean supportPlainPkce, String expectedLocation) throws Exception {
Map<String, String[]> requestParams = new HashMap();
Map<String, Object> requestAttributes = new HashMap();
requestParams.put(CLIENT_ID, new String[] { clientId });
// No consent data is saved in the cache yet and client doesn't send cache key
requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { null });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE, new String[] { pkceChallengeCode });
requestParams.put(OAuthConstants.OAUTH_PKCE_CODE_CHALLENGE_METHOD, new String[] { pkceChallengeMethod });
requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
if (redirectUri != null) {
requestParams.put("acr_values", new String[] { redirectUri });
requestParams.put("claims", new String[] { "essentialClaims" });
requestParams.put(MultitenantConstants.TENANT_DOMAIN, new String[] { MultitenantConstants.SUPER_TENANT_DOMAIN_NAME });
}
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
// No authentication data is saved in the cache yet and client doesn't send cache key
requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, null);
if (prompt != null) {
requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { prompt });
}
boolean checkErrorCode = ERROR_PAGE_URL.equals(expectedLocation);
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
mockOAuthServerConfiguration();
Map<String, Class<? extends OAuthValidator<HttpServletRequest>>> responseTypeValidators = new Hashtable<>();
responseTypeValidators.put(ResponseType.CODE.toString(), CodeValidator.class);
responseTypeValidators.put(ResponseType.TOKEN.toString(), TokenValidator.class);
when(oAuthServerConfiguration.getSupportedResponseTypeValidators()).thenReturn(responseTypeValidators);
spy(FrameworkUtils.class);
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
mockEndpointUtil(false);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
when(oAuth2Service.isPKCESupportEnabled()).thenReturn(pkceEnabled);
if (ERROR_PAGE_URL.equals(expectedLocation) && OAuthConstants.Prompt.NONE.equals(prompt)) {
doThrow(new IdentityOAuth2Exception("error")).when(EndpointUtil.class, "getLoginPageURL", anyString(), anyString(), anyBoolean(), anyBoolean(), anySet(), anyMap(), any());
checkErrorCode = false;
}
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
validationResponseDTO.setValidClient(clientValid);
validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
if (!clientValid) {
validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_REQUEST);
validationResponseDTO.setErrorMsg("client is invalid");
}
validationResponseDTO.setPkceMandatory(supportPlainPkce);
validationResponseDTO.setPkceSupportPlain(supportPlainPkce);
when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
if (StringUtils.equals(expectedLocation, LOGIN_PAGE_URL) || StringUtils.equals(expectedLocation, ERROR_PAGE_URL)) {
CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
doAnswer(invocation -> {
CommonAuthRequestWrapper request = (CommonAuthRequestWrapper) invocation.getArguments()[0];
request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
CommonAuthResponseWrapper wrapper = (CommonAuthResponseWrapper) invocation.getArguments()[1];
wrapper.sendRedirect(expectedLocation);
return null;
}).when(handler).doGet(any(), any());
whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
}
mockServiceURLBuilder();
Response response;
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
assertNotNull(response);
assertEquals(response.getStatus(), HttpServletResponse.SC_FOUND, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata, "Response metadata is null");
assertTrue(CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION)), "Location header not found in the response");
String location = String.valueOf(responseMetadata.get(HTTPConstants.HEADER_LOCATION).get(0));
assertTrue(location.contains(expectedLocation), "Unexpected redirect url in the response");
if (checkErrorCode) {
assertTrue(location.contains(OAuth2ErrorCodes.INVALID_REQUEST), "Expected error code not found in URL");
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testAuthorize.
@Test(dataProvider = "provideParams", groups = "testWithConnection")
public void testAuthorize(Object flowStatusObject, String[] clientId, String sessionDataKayConsent, String toCommonAuth, String scope, String sessionDataKey, Exception e, int expectedStatus, String expectedError, String responseMode) throws Exception {
AuthenticatorFlowStatus flowStatus = (AuthenticatorFlowStatus) flowStatusObject;
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new HashMap<>();
if (clientId != null) {
requestParams.put(CLIENT_ID, clientId);
}
requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { sessionDataKayConsent });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { toCommonAuth });
requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { scope });
if (StringUtils.equals(responseMode, RESPONSE_MODE_FORM_POST)) {
requestParams.put(RESPONSE_MODE, new String[] { RESPONSE_MODE_FORM_POST });
}
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, flowStatus);
requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
if (e instanceof OAuthProblemException) {
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
}
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
spy(FrameworkUtils.class);
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(IdentityTenantUtil.class);
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
when(IdentityTenantUtil.getTenantDomain(anyInt())).thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
IdentityEventService eventServiceMock = mock(IdentityEventService.class);
mockStatic(CentralLogMgtServiceComponentHolder.class);
when(CentralLogMgtServiceComponentHolder.getInstance()).thenReturn(centralLogMgtServiceComponentHolderMock);
when(centralLogMgtServiceComponentHolderMock.getIdentityEventService()).thenReturn(eventServiceMock);
PowerMockito.doNothing().when(eventServiceMock).handleEvent(any());
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
when(loginCacheEntry.getoAuth2Parameters()).thenReturn(setOAuth2Parameters(new HashSet<>(Collections.singletonList(OAuthConstants.Scope.OPENID)), APP_NAME, null, null));
mockOAuthServerConfiguration();
mockEndpointUtil(false);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
if (ArrayUtils.isNotEmpty(clientId) && (clientId[0].equalsIgnoreCase("invalidId") || clientId[0].equalsIgnoreCase(INACTIVE_CLIENT_ID_VALUE) || StringUtils.isEmpty(clientId[0]))) {
when(oAuth2Service.validateClientInfo(clientId[0], APP_REDIRECT_URL)).thenCallRealMethod();
} else {
when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(oAuth2ClientValidationResponseDTO);
when(oAuth2ClientValidationResponseDTO.isValidClient()).thenReturn(true);
}
if (e instanceof IOException) {
CommonAuthenticationHandler handler = mock(CommonAuthenticationHandler.class);
doThrow(e).when(handler).doGet(any(), any());
whenNew(CommonAuthenticationHandler.class).withNoArguments().thenReturn(handler);
}
Response response;
try (Connection connection = getConnection()) {
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
mockServiceURLBuilder();
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
}
if (!StringUtils.equals(responseMode, RESPONSE_MODE_FORM_POST)) {
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata, "HTTP response metadata is null");
if (expectedStatus == HttpServletResponse.SC_FOUND) {
if (expectedError != null) {
List<Object> redirectPath = responseMetadata.get(HTTPConstants.HEADER_LOCATION);
if (CollectionUtils.isNotEmpty(redirectPath)) {
String location = String.valueOf(redirectPath.get(0));
assertTrue(location.contains(expectedError), "Expected error code not found in URL");
} else {
assertNotNull(response.getEntity(), "Response entity is null");
assertTrue(response.getEntity().toString().contains(expectedError), "Expected error code not found response entity");
}
} else {
// This is the case where a redirect outside happens.
List<Object> redirectPath = responseMetadata.get(HTTPConstants.HEADER_LOCATION);
assertTrue(CollectionUtils.isNotEmpty(redirectPath));
String location = String.valueOf(redirectPath.get(0));
assertNotNull(location);
assertFalse(location.contains("error"), "Expected no errors in the redirect url, but found one.");
}
}
} else {
if (expectedError != null) {
// Check if the error response is of form post mode
assertTrue(response.getEntity().toString().contains("<form method=\"post\" action=\"" + APP_REDIRECT_URL + "\">"));
}
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleOAuthAuthorizationRequest.
/**
* http://tools.ietf.org/html/rfc6749#section-4.1.2
* <p/>
* 4.1.2.1. Error Response
* <p/>
* If the request fails due to a missing, invalid, or mismatching
* redirection URI, or if the client identifier is missing or invalid,
* the authorization server SHOULD inform the resource owner of the
* error and MUST NOT automatically redirect the user-agent to the
* invalid redirection URI.
* <p/>
* If the resource owner denies the access request or if the request
* fails for reasons other than a missing or invalid redirection URI,
* the authorization server informs the client by adding the following
* parameters to the query component of the redirection URI using the
* "application/x-www-form-urlencoded" format
*
* @param oAuthMessage oAuthMessage
* @return String redirectURL
* @throws OAuthSystemException OAuthSystemException
* @throws OAuthProblemException OAuthProblemException
*/
private String handleOAuthAuthorizationRequest(OAuthMessage oAuthMessage) throws OAuthSystemException, OAuthProblemException, InvalidRequestException {
OAuth2ClientValidationResponseDTO validationResponse = validateClient(oAuthMessage);
if (!validationResponse.isValidClient()) {
EndpointUtil.triggerOnRequestValidationFailure(oAuthMessage, validationResponse);
return getErrorPageURL(oAuthMessage.getRequest(), validationResponse.getErrorCode(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_CLIENT, validationResponse.getErrorMsg(), null);
} else {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> logParams = new HashMap<>();
logParams.put("clientId", oAuthMessage.getClientId());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, logParams, OAuthConstants.LogConstants.SUCCESS, "OAuth client validation is successful.", "validate-oauth-client", null);
}
String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oAuthMessage.getClientId());
setSPAttributeToRequest(oAuthMessage.getRequest(), validationResponse.getApplicationName(), tenantDomain);
}
OAuthAuthzRequest oauthRequest = new CarbonOAuthAuthzRequest(oAuthMessage.getRequest());
OAuth2Parameters params = new OAuth2Parameters();
String sessionDataKey = UUIDGenerator.generateUUID();
params.setSessionDataKey(sessionDataKey);
String redirectURI = populateOauthParameters(params, oAuthMessage, validationResponse, oauthRequest);
if (redirectURI != null) {
return redirectURI;
}
String prompt = oauthRequest.getParam(OAuthConstants.OAuth20Params.PROMPT);
params.setPrompt(prompt);
redirectURI = analyzePromptParameter(oAuthMessage, params, prompt);
if (redirectURI != null) {
return redirectURI;
}
if (isNonceMandatory(params.getResponseType())) {
validateNonceParameter(params.getNonce());
}
addDataToSessionCache(oAuthMessage, params, sessionDataKey);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "OIDC request input parameter validation is successful.", "validate-input-parameters", null);
try {
oAuthMessage.getRequest().setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.SUCCESS_COMPLETED);
oAuthMessage.getRequest().setAttribute(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
return getLoginPageURL(oAuthMessage.getClientId(), sessionDataKey, oAuthMessage.isForceAuthenticate(), oAuthMessage.isPassiveAuthentication(), oauthRequest.getScopes(), oAuthMessage.getRequest().getParameterMap(), oAuthMessage.getRequest());
} catch (IdentityOAuth2Exception e) {
return handleException(e);
}
}
Aggregations