use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testUserConsentResponse.
@Test(dataProvider = "provideConsentData", groups = "testWithConnection")
public void testUserConsentResponse(String consent, String redirectUrl, Set<String> scopes, int expectedStatus, String oAuthErrorDTODescription, String expectedError) throws Exception {
initMocks(this);
spy(FrameworkUtils.class);
when(authCookie.getValue()).thenReturn("dummyValue");
doReturn(authCookie).when(FrameworkUtils.class, "getAuthCookie", any());
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
mockStatic(LoggerUtils.class);
when(LoggerUtils.isDiagnosticLogsEnabled()).thenReturn(true);
mockStatic(IdentityTenantUtil.class);
when(IdentityTenantUtil.getTenantId(anyString())).thenReturn(MultitenantConstants.SUPER_TENANT_ID);
SessionContext sessionContext = new SessionContext();
sessionContext.addProperty(FrameworkConstants.CREATED_TIMESTAMP, 1479249799770L);
doReturn(sessionContext).when(FrameworkUtils.class, "getSessionContextFromCache", anyString(), anyString());
when(openIDConnectClaimFilter.getClaimsFilteredByOIDCScopes(any(), anyString())).thenReturn(Arrays.asList("country"));
OAuth2AuthzEndpoint.setOpenIDConnectClaimFilter(openIDConnectClaimFilter);
Set<ExternalClaim> mappings = new HashSet<>();
ExternalClaim claim = new ExternalClaim(OIDC_DIALECT, "country", "http://wso2.org/country");
mappings.add(claim);
when(claimMetadataHandler.getMappingsFromOtherDialectToCarbon(anyString(), any(), anyString())).thenReturn(mappings);
mockStatic(ClaimMetadataHandler.class);
when(ClaimMetadataHandler.getInstance()).thenReturn(claimMetadataHandler);
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey consentDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_CONSENT_VALUE);
when(sessionDataCache.getValueFromCache(consentDataCacheKey)).thenReturn(consentCacheEntry);
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new ConcurrentHashMap<>();
requestParams.put(OAuthConstants.SESSION_DATA_KEY_CONSENT, new String[] { SESSION_DATA_KEY_CONSENT_VALUE });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
requestParams.put(OAuthConstants.Prompt.CONSENT, new String[] { consent });
requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
OAuth2Parameters oAuth2Params = setOAuth2Parameters(scopes, APP_NAME, RESPONSE_MODE_FORM_POST, redirectUrl);
oAuth2Params.setClientId(CLIENT_ID_VALUE);
when(consentCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
when(consentCacheEntry.getLoggedInUser()).thenReturn(new AuthenticatedUser());
mockStatic(OpenIDConnectUserRPStore.class);
when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
doNothing().when(openIDConnectUserRPStore).putUserRPToStore(any(AuthenticatedUser.class), anyString(), anyBoolean(), anyString());
mockOAuthServerConfiguration();
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
spy(OAuth2Util.class);
doReturn(new ServiceProvider()).when(OAuth2Util.class, "getServiceProvider", CLIENT_ID_VALUE);
mockEndpointUtil(true);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
mockApplicationManagementService();
when(oAuth2Service.handleUserConsentDenial(oAuth2Params)).thenReturn(oAuthErrorDTO);
when(oAuthErrorDTO.getErrorDescription()).thenReturn(oAuthErrorDTODescription);
Response response;
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
if (response != null) {
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata);
if (expectedError != null) {
if (response.getEntity() != null) {
String htmlPost = response.getEntity().toString();
assertTrue(htmlPost.contains(expectedError));
} else {
CollectionUtils.isNotEmpty(responseMetadata.get(HTTPConstants.HEADER_LOCATION));
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(expectedError), "Expected error code not found in URL");
}
}
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuthRequestStateValidator method validateRequest.
private void validateRequest(OAuthMessage oAuthMessage) throws InvalidRequestParentException {
validateRepeatedParameters(oAuthMessage);
if (oAuthMessage.getResultFromLogin() != null && oAuthMessage.getResultFromConsent() != null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' found in request as parameter and " + "attribute, and both have non NULL objects in cache");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'SessionDataKey' parameter in authorization request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_AUTHORIZATION_REQUEST);
} else if (oAuthMessage.getClientId() == null && oAuthMessage.getResultFromLogin() == null && oAuthMessage.getResultFromConsent() == null) {
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request.\'SessionDataKey\' not found in request as parameter or " + "attribute, and client_id parameter cannot be found in request");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "invalid 'client_id' and 'SessionDataKey' parameters cannot be found in request", "validate-input-parameters", null);
}
throw new InvalidRequestException("Invalid authorization request", OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_CLIENT);
} else if (oAuthMessage.getSessionDataKeyFromLogin() != null && oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromLogin());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else if (oAuthMessage.getSessionDataKeyFromConsent() != null && oAuthMessage.getResultFromConsent() == null) {
if (oAuthMessage.getResultFromLogin() == null) {
if (log.isDebugEnabled()) {
log.debug("Session data not found in SessionDataCache for " + oAuthMessage.getSessionDataKeyFromConsent());
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
oAuthMessage.getRequest().getParameterMap().forEach(params::put);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Access denied since user session has timed-out.", "validate-input-parameters", null);
}
throw new AccessDeniedException("Session Timed Out", OAuth2ErrorCodes.ACCESS_DENIED, OAuth2ErrorCodes.OAuth2SubErrorCodes.SESSION_TIME_OUT);
} else {
// if the sessionDataKeyFromConsent parameter present in the login request, skip it and allow login
// since result from login is there.
oAuthMessage.setSessionDataKeyFromConsent(null);
}
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2TokenEndpoint method issueAccessToken.
protected Response issueAccessToken(HttpServletRequest request, Map<String, List<String>> paramMap) throws OAuthSystemException, InvalidRequestParentException {
try {
startSuperTenantFlow();
validateRepeatedParams(request, paramMap);
HttpServletRequestWrapper httpRequest = new OAuthRequestWrapper(request, paramMap);
CarbonOAuthTokenRequest oauthRequest = buildCarbonOAuthTokenRequest(httpRequest);
validateOAuthApplication(oauthRequest.getoAuthClientAuthnContext());
OAuth2AccessTokenRespDTO oauth2AccessTokenResp = issueAccessToken(oauthRequest, httpRequest);
if (oauth2AccessTokenResp.getErrorMsg() != null) {
return handleErrorResponse(oauth2AccessTokenResp);
} else {
return buildTokenResponse(oauth2AccessTokenResp);
}
} catch (TokenEndpointBadRequestException | OAuthSystemException | InvalidApplicationClientException e) {
triggerOnTokenExceptionListeners(e, request, paramMap);
throw e;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.
the class UserAuthenticationEndpoint method deviceAuthorize.
@POST
@Path("/")
@Consumes("application/x-www-form-urlencoded")
@Produces("text/html")
public Response deviceAuthorize(@Context HttpServletRequest request, @Context HttpServletResponse response) throws InvalidRequestParentException, OAuthSystemException {
try {
String userCode = request.getParameter(Constants.USER_CODE);
// True when input(user_code) is not REQUIRED.
if (StringUtils.isBlank(userCode)) {
if (log.isDebugEnabled()) {
log.debug("user_code is missing in the request.");
}
response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
return null;
}
String clientId = deviceAuthService.getClientId(userCode);
DeviceFlowDO deviceFlowDODetails = DeviceFlowPersistenceFactory.getInstance().getDeviceFlowDAO().getDetailsForUserCode(userCode);
if (StringUtils.isNotBlank(clientId) && deviceFlowDODetails != null && !isExpiredUserCode(deviceFlowDODetails)) {
setCallbackURI(clientId);
deviceAuthService.setAuthenticationStatus(userCode);
CommonAuthRequestWrapper commonAuthRequestWrapper = new CommonAuthRequestWrapper(request);
commonAuthRequestWrapper.setParameter(Constants.CLIENT_ID, clientId);
commonAuthRequestWrapper.setParameter(Constants.RESPONSE_TYPE, Constants.RESPONSE_TYPE_DEVICE);
commonAuthRequestWrapper.setParameter(Constants.REDIRECTION_URI, deviceFlowDO.getCallbackUri());
if (getScope(userCode) != null) {
String scope = String.join(Constants.SEPARATED_WITH_SPACE, getScope(userCode));
commonAuthRequestWrapper.setParameter(Constants.SCOPE, scope);
}
commonAuthRequestWrapper.setParameter(Constants.NONCE, userCode);
return oAuth2AuthzEndpoint.authorize(commonAuthRequestWrapper, response);
} else {
if (log.isDebugEnabled()) {
log.debug("Incorrect user_code.");
}
response.sendRedirect(ServiceURLBuilder.create().addPath(Constants.DEVICE_ENDPOINT_PATH).addParameter("error", OAuth2ErrorCodes.INVALID_REQUEST).build().getAbsolutePublicURL());
return null;
}
} catch (IdentityOAuth2Exception e) {
return handleIdentityOAuth2Exception(e);
} catch (IOException e) {
return handleIOException(e);
} catch (URLBuilderException e) {
return handleURLBuilderException(e);
} catch (URISyntaxException e) {
return handleURISyntaxException(e);
}
}
use of org.wso2.carbon.identity.oauth.endpoint.exception.InvalidRequestParentException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testManageOIDCSessionState.
@Test(dataProvider = "provideOidcSessionData", groups = "testWithConnection")
public void testManageOIDCSessionState(Object cookieObject, Object sessionStateObject, String callbackUrl, String responseMode, int expectedStatus, String expectedResult) throws Exception {
Cookie opBrowserStateCookie = (Cookie) cookieObject;
Cookie newOpBrowserStateCookie = new Cookie("opbs", "f6454r678776gffdgdsfafa");
OIDCSessionState previousSessionState = (OIDCSessionState) sessionStateObject;
AuthenticationResult result = setAuthenticationResult(true, null, null, null, null);
Map<String, String[]> requestParams = new HashMap<>();
Map<String, Object> requestAttributes = new HashMap<>();
requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestParams.put(FrameworkConstants.RequestParams.TO_COMMONAUTH, new String[] { "false" });
requestParams.put(OAuthConstants.OAuth20Params.SCOPE, new String[] { OAuthConstants.Scope.OPENID });
requestParams.put(OAuthConstants.OAuth20Params.PROMPT, new String[] { OAuthConstants.Prompt.LOGIN });
requestAttributes.put(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
requestAttributes.put(FrameworkConstants.SESSION_DATA_KEY, SESSION_DATA_KEY_VALUE);
requestAttributes.put(FrameworkConstants.RequestAttribute.AUTH_RESULT, result);
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
OAuth2Parameters oAuth2Params = setOAuth2Parameters(new HashSet<>(Arrays.asList(OAuthConstants.Scope.OPENID)), APP_NAME, responseMode, APP_REDIRECT_URL);
oAuth2Params.setClientId(CLIENT_ID_VALUE);
oAuth2Params.setPrompt(OAuthConstants.Prompt.LOGIN);
mockOAuthServerConfiguration();
mockEndpointUtil(false);
when(oAuthServerConfiguration.getOpenIDConnectSkipeUserConsentConfig()).thenReturn(true);
OAuth2AuthorizeRespDTO authzRespDTO = new OAuth2AuthorizeRespDTO();
authzRespDTO.setCallbackURI(callbackUrl);
when(oAuth2Service.authorize(any(OAuth2AuthorizeReqDTO.class))).thenReturn(authzRespDTO);
mockStatic(OAuth2Util.OAuthURL.class);
when(OAuth2Util.OAuthURL.getOAuth2ErrorPageUrl()).thenReturn(ERROR_PAGE_URL);
mockStatic(OIDCSessionManagementUtil.class);
when(OIDCSessionManagementUtil.getOPBrowserStateCookie(any(HttpServletRequest.class))).thenReturn(opBrowserStateCookie);
when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class))).thenReturn(newOpBrowserStateCookie);
when(OIDCSessionManagementUtil.addOPBrowserStateCookie(any(HttpServletResponse.class), any(HttpServletRequest.class), any(String.class), any(String.class))).thenReturn(newOpBrowserStateCookie);
when(OIDCSessionManagementUtil.getSessionManager()).thenReturn(oidcSessionManager);
when(oidcSessionManager.getOIDCSessionState(anyString(), anyString())).thenReturn(previousSessionState);
when(OIDCSessionManagementUtil.getSessionStateParam(anyString(), anyString(), anyString())).thenReturn("sessionStateValue");
when(OIDCSessionManagementUtil.addSessionStateToURL(anyString(), anyString(), anyString())).thenCallRealMethod();
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
SessionDataCacheKey loginDataCacheKey = new SessionDataCacheKey(SESSION_DATA_KEY_VALUE);
when(sessionDataCache.getValueFromCache(loginDataCacheKey)).thenReturn(loginCacheEntry);
when(loginCacheEntry.getoAuth2Parameters()).thenReturn(oAuth2Params);
when(loginCacheEntry.getLoggedInUser()).thenReturn(result.getSubject());
mockStatic(IdentityDatabaseUtil.class);
when(IdentityDatabaseUtil.getDBConnection()).thenReturn(connection);
mockStatic(OpenIDConnectUserRPStore.class);
when(OpenIDConnectUserRPStore.getInstance()).thenReturn(openIDConnectUserRPStore);
when(openIDConnectUserRPStore.hasUserApproved(any(AuthenticatedUser.class), anyString(), anyString())).thenReturn(true);
when(oAuth2Service.getOauthApplicationState(CLIENT_ID_VALUE)).thenReturn("ACTIVE");
mockApplicationManagementService();
spy(FrameworkUtils.class);
doReturn("sample").when(FrameworkUtils.class, "resolveUserIdFromUsername", anyInt(), anyString(), anyString());
doNothing().when(FrameworkUtils.class, "startTenantFlow", anyString());
doNothing().when(FrameworkUtils.class, "endTenantFlow");
spy(IdentityTenantUtil.class);
doReturn(MultitenantConstants.SUPER_TENANT_ID).when(IdentityTenantUtil.class, "getTenantId", anyString());
doReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME).when(IdentityTenantUtil.class, "getTenantDomain", anyInt());
Response response;
try {
response = oAuth2AuthzEndpoint.authorize(httpServletRequest, httpServletResponse);
} catch (InvalidRequestParentException ire) {
InvalidRequestExceptionMapper invalidRequestExceptionMapper = new InvalidRequestExceptionMapper();
response = invalidRequestExceptionMapper.toResponse(ire);
}
assertNotNull(response, "Authorization response is null");
assertEquals(response.getStatus(), expectedStatus, "Unexpected HTTP response status");
MultivaluedMap<String, Object> responseMetadata = response.getMetadata();
assertNotNull(responseMetadata, "Response metadata is null");
if (response.getStatus() != HttpServletResponse.SC_OK) {
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(expectedResult), "Expected redirect URL is not returned");
} else {
assertTrue(response.getEntity().toString().contains(expectedResult), "Expected redirect URL is not returned");
}
}
Aggregations