use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpointTest method testHandleOAuthAuthorizationRequest1.
@Test(dataProvider = "provideHandleOAuthAuthorizationRequest1Data", groups = "testWithConnection")
public void testHandleOAuthAuthorizationRequest1(boolean showDisplayName, Object spObj, String savedDisplayName) throws Exception {
ServiceProvider sp = (ServiceProvider) spObj;
sp.setApplicationName(APP_NAME);
mockApplicationManagementService(sp);
mockOAuthServerConfiguration();
mockEndpointUtil(false);
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);
Map<String, String[]> requestParams = new HashMap();
Map<String, Object> requestAttributes = new HashMap();
requestParams.put(CLIENT_ID, new String[] { CLIENT_ID_VALUE });
requestParams.put(REDIRECT_URI, new String[] { APP_REDIRECT_URL });
requestParams.put(OAuth.OAUTH_RESPONSE_TYPE, new String[] { ResponseType.TOKEN.toString() });
mockHttpRequest(requestParams, requestAttributes, HttpMethod.POST);
OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
validationResponseDTO.setValidClient(true);
validationResponseDTO.setCallbackURL(APP_REDIRECT_URL);
when(oAuth2Service.validateClientInfo(anyString(), anyString())).thenReturn(validationResponseDTO);
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);
when(oAuthServerConfiguration.isShowDisplayNameInConsentPage()).thenReturn(showDisplayName);
Method handleOAuthAuthorizationRequest = authzEndpointObject.getClass().getDeclaredMethod("handleOAuthAuthorizationRequest", OAuthMessage.class);
handleOAuthAuthorizationRequest.setAccessible(true);
SessionDataCache sessionDataCache = mock(SessionDataCache.class);
mockStatic(SessionDataCache.class);
when(SessionDataCache.getInstance()).thenReturn(sessionDataCache);
final SessionDataCacheEntry[] cacheEntry = new SessionDataCacheEntry[1];
doAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) {
cacheEntry[0] = (SessionDataCacheEntry) invocation.getArguments()[1];
return null;
}
}).when(sessionDataCache).addToCache(any(SessionDataCacheKey.class), any(SessionDataCacheEntry.class));
when(oAuthMessage.getRequest()).thenReturn(httpServletRequest);
when(oAuthMessage.getClientId()).thenReturn(CLIENT_ID_VALUE);
handleOAuthAuthorizationRequest.invoke(authzEndpointObject, oAuthMessage);
assertNotNull(cacheEntry[0], "Parameters not saved in cache");
assertEquals(cacheEntry[0].getoAuth2Parameters().getDisplayName(), savedDisplayName);
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2Service method validateClientInfo.
/**
* Check Whether the provided client_id and the callback URL are valid.
*
* @param clientId client_id available in the request, Not null parameter.
* @param callbackURI callback_uri available in the request, can be null.
* @return <code>OAuth2ClientValidationResponseDTO</code> bean with validity information,
* callback, App Name, Error Code and Error Message when appropriate.
*/
public OAuth2ClientValidationResponseDTO validateClientInfo(String clientId, String callbackURI) {
OAuth2ClientValidationResponseDTO validationResponseDTO = new OAuth2ClientValidationResponseDTO();
if (log.isDebugEnabled()) {
log.debug("Validate Client information request for client_id : " + clientId + " and callback_uri " + callbackURI);
}
try {
String appTenantDomain = OAuth2Util.getTenantDomainOfOauthApp(clientId);
validateRequestTenantDomain(appTenantDomain);
if (StringUtils.isBlank(clientId)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "client_id cannot be empty.", "validate-input-parameters", null);
}
throw new InvalidOAuthClientException("Invalid client_id. No OAuth application has been registered " + "with the given client_id");
}
OAuthAppDO appDO = OAuth2Util.getAppInformationByClientId(clientId);
String appState = appDO.getState();
if (StringUtils.isEmpty(appState)) {
if (log.isDebugEnabled()) {
log.debug("A valid OAuth client could not be found for client_id: " + clientId);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "A valid OAuth application could not be found for given client_id.", "validate-input-parameters", null);
}
throw new InvalidOAuthClientException("A valid OAuth client could not be found for client_id: " + Encode.forHtml(clientId));
}
if (!appState.equalsIgnoreCase(APP_STATE_ACTIVE)) {
if (log.isDebugEnabled()) {
log.debug("App is not in active state in client ID: " + clientId + ". App state is: " + appState);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "OAuth application is not in active state.", "validate-input-parameters", null);
}
throw new InvalidOAuthClientException("Oauth application is not in active state");
}
if (StringUtils.isEmpty(appDO.getGrantTypes()) || StringUtils.isEmpty(appDO.getCallbackUrl())) {
if (log.isDebugEnabled()) {
log.debug("Registered App found for the given Client Id : " + clientId + " ,App Name : " + appDO.getApplicationName() + ", does not support the requested grant type.");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
Map<String, Object> configurations = new HashMap<>();
configurations.put("callbackUrl", appDO.getCallbackUrl());
configurations.put("supportedGrantTypes", appDO.getGrantTypes());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "The OAuth client is not authorized to use the requested grant type.", "validate-input-parameters", configurations);
}
validationResponseDTO.setValidClient(false);
validationResponseDTO.setErrorCode(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
validationResponseDTO.setErrorMsg("The authenticated client is not authorized to use this authorization grant type");
return validationResponseDTO;
}
OAuth2Util.setClientTenatId(IdentityTenantUtil.getTenantId(appDO.getUser().getTenantDomain()));
// Valid Client, No callback has provided. Use the callback provided during the registration.
if (callbackURI == null) {
validationResponseDTO.setValidClient(true);
validationResponseDTO.setCallbackURL(appDO.getCallbackUrl());
validationResponseDTO.setApplicationName(appDO.getApplicationName());
validationResponseDTO.setPkceMandatory(appDO.isPkceMandatory());
validationResponseDTO.setPkceSupportPlain(appDO.isPkceSupportPlain());
return validationResponseDTO;
}
if (log.isDebugEnabled()) {
log.debug("Registered App found for the given Client Id : " + clientId + " ,App Name : " + appDO.getApplicationName() + ", Callback URL : " + appDO.getCallbackUrl());
}
if (validateCallbackURI(callbackURI, appDO)) {
validationResponseDTO.setValidClient(true);
validationResponseDTO.setApplicationName(appDO.getApplicationName());
validationResponseDTO.setCallbackURL(callbackURI);
validationResponseDTO.setPkceMandatory(appDO.isPkceMandatory());
validationResponseDTO.setPkceSupportPlain(appDO.isPkceSupportPlain());
return validationResponseDTO;
} else {
// Provided callback URL does not match the registered callback url.
log.warn("Provided Callback URL does not match with the provided one.");
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
params.put("redirectUri", callbackURI);
Map<String, Object> configurations = new HashMap<>();
configurations.put("redirectUri", appDO.getApplicationName());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "redirect_uri in request does not match with the registered one.", "validate-input-parameters", configurations);
}
validationResponseDTO.setValidClient(false);
validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_CALLBACK);
validationResponseDTO.setErrorMsg("callback.not.match");
return validationResponseDTO;
}
} catch (InvalidOAuthClientException e) {
// There is no such Client ID being registered. So it is a request from an invalid client.
if (log.isDebugEnabled()) {
log.debug("Error while retrieving the Application Information", e);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Cannot find an application associated with the given client_id", "validate-oauth-client", null);
}
validationResponseDTO.setValidClient(false);
validationResponseDTO.setErrorCode(OAuth2ErrorCodes.INVALID_CLIENT);
validationResponseDTO.setErrorMsg(e.getMessage());
return validationResponseDTO;
} catch (IdentityOAuth2Exception e) {
log.error("Error when reading the Application Information.", e);
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "validate-input-parameters", null);
validationResponseDTO.setValidClient(false);
validationResponseDTO.setErrorCode(OAuth2ErrorCodes.SERVER_ERROR);
validationResponseDTO.setErrorMsg("Error when processing the authorization request.");
return validationResponseDTO;
}
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method populateOauthParameters.
private String populateOauthParameters(OAuth2Parameters params, OAuthMessage oAuthMessage, OAuth2ClientValidationResponseDTO validationResponse, OAuthAuthzRequest oauthRequest) throws OAuthSystemException, InvalidRequestException {
String clientId = oAuthMessage.getClientId();
params.setClientId(clientId);
params.setRedirectURI(validationResponse.getCallbackURL());
params.setResponseType(oauthRequest.getResponseType());
params.setResponseMode(oauthRequest.getParam(RESPONSE_MODE));
params.setScopes(oauthRequest.getScopes());
if (params.getScopes() == null) {
// to avoid null pointers
Set<String> scopeSet = new HashSet<String>();
scopeSet.add("");
params.setScopes(scopeSet);
}
params.setState(oauthRequest.getState());
params.setApplicationName(validationResponse.getApplicationName());
String spDisplayName = getSpDisplayName(clientId);
if (StringUtils.isNotBlank(spDisplayName)) {
params.setDisplayName(spDisplayName);
}
// OpenID Connect specific request parameters
params.setNonce(oauthRequest.getParam(OAuthConstants.OAuth20Params.NONCE));
params.setDisplay(oauthRequest.getParam(OAuthConstants.OAuth20Params.DISPLAY));
params.setIDTokenHint(oauthRequest.getParam(OAuthConstants.OAuth20Params.ID_TOKEN_HINT));
params.setLoginHint(oauthRequest.getParam(OAuthConstants.OAuth20Params.LOGIN_HINT));
// Set the service provider tenant domain.
params.setTenantDomain(getSpTenantDomain(clientId));
// Set the login tenant domain.
String loginTenantDomain = getLoginTenantDomain(oAuthMessage, clientId);
params.setLoginTenantDomain(loginTenantDomain);
if (StringUtils.isNotBlank(oauthRequest.getParam(ACR_VALUES)) && !"null".equals(oauthRequest.getParam(ACR_VALUES))) {
List acrValuesList = Arrays.asList(oauthRequest.getParam(ACR_VALUES).split(" "));
LinkedHashSet acrValuesHashSet = new LinkedHashSet<>(acrValuesList);
params.setACRValues(acrValuesHashSet);
oAuthMessage.getRequest().setAttribute(ACR_VALUES, acrValuesList);
}
if (StringUtils.isNotBlank(oauthRequest.getParam(CLAIMS))) {
params.setEssentialClaims(oauthRequest.getParam(CLAIMS));
}
handleMaxAgeParameter(oauthRequest, params);
/*
OIDC Request object will supersede parameters sent in the OAuth Authorization request. So handling the
OIDC Request object needs to done after processing all request parameters.
*/
if (OAuth2Util.isOIDCAuthzRequest(oauthRequest.getScopes())) {
try {
handleOIDCRequestObject(oAuthMessage, oauthRequest, params);
} catch (RequestObjectException e) {
if (log.isDebugEnabled()) {
log.debug("Request Object Handling failed due to : " + e.getErrorCode() + " for client_id: " + clientId + " of tenantDomain: " + params.getTenantDomain(), e);
}
if (StringUtils.isNotBlank(oAuthMessage.getRequest().getParameter(REQUEST_URI))) {
return EndpointUtil.getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_REQUEST_URI, e.getErrorCode(), e.getErrorMessage(), null, params);
} else {
return EndpointUtil.getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_REQUEST_OBJECT, e.getErrorCode(), e.getErrorMessage(), null, params);
}
}
}
if (isPkceSupportEnabled()) {
String pkceChallengeCode = getPkceCodeChallenge(oAuthMessage, params);
String pkceChallengeMethod = getPkceCodeChallengeMethod(oAuthMessage, params);
String redirectURI = validatePKCEParameters(oAuthMessage, validationResponse, pkceChallengeCode, pkceChallengeMethod);
if (redirectURI != null) {
return redirectURI;
}
params.setPkceCodeChallenge(pkceChallengeCode);
params.setPkceCodeChallengeMethod(pkceChallengeMethod);
}
return null;
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method validatePKCEParameters.
private String validatePKCEParameters(OAuthMessage oAuthMessage, OAuth2ClientValidationResponseDTO validationResponse, String pkceChallengeCode, String pkceChallengeMethod) {
OAuth2Parameters oAuth2Parameters = getOAuth2ParamsFromOAuthMessage(oAuthMessage);
// Check if PKCE is mandatory for the application
if (validationResponse.isPkceMandatory()) {
if (pkceChallengeCode == null || !OAuth2Util.validatePKCECodeChallenge(pkceChallengeCode, pkceChallengeMethod)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuth2Parameters.getClientId());
params.put("pkceChallenge", pkceChallengeCode);
params.put("pkceMethod", pkceChallengeMethod);
Map<String, Object> configs = new HashMap<>();
configs.put("isPkceMandatory", "true");
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "PKCE Challenge is not provided or is not upto RFC 7636 specification.", "validate-pkce", configs);
}
return getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_PKCE_CHALLENGE_CODE, "PKCE is mandatory for this application. " + "PKCE Challenge is not provided or is not upto RFC 7636 " + "specification.", null, oAuth2Parameters);
}
}
// Check if the code challenge method value is neither "plain" or "s256", if so return error
if (pkceChallengeCode != null && pkceChallengeMethod != null) {
if (!OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(pkceChallengeMethod) && !OAuthConstants.OAUTH_PKCE_S256_CHALLENGE.equals(pkceChallengeMethod)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuth2Parameters.getClientId());
params.put("pkceChallenge", pkceChallengeCode);
params.put("pkceMethod", pkceChallengeMethod);
Map<String, Object> configs = new HashMap<>();
configs.put("isPkceMandatory", Boolean.toString(validationResponse.isPkceMandatory()));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Unsupported PKCE Challenge Method.", "validate-pkce", configs);
}
return getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_PKCE_CHALLENGE_CODE, "Unsupported PKCE Challenge Method", null, oAuth2Parameters);
}
}
// Check if "plain" transformation algorithm is disabled for the application
if (pkceChallengeCode != null && !validationResponse.isPkceSupportPlain()) {
if (pkceChallengeMethod == null || OAuthConstants.OAUTH_PKCE_PLAIN_CHALLENGE.equals(pkceChallengeMethod)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuth2Parameters.getClientId());
params.put("pkceChallenge", pkceChallengeCode);
params.put("pkceMethod", pkceChallengeMethod);
Map<String, Object> configs = new HashMap<>();
configs.put("isPkceMandatory", Boolean.toString(validationResponse.isPkceMandatory()));
configs.put("isPkceSupportPlain", "false");
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "OAuth client does not support 'plain' transformation algorithm.", "validate-pkce", configs);
}
return getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_PKCE_CHALLENGE_CODE, "This application does not support " + "\"plain\" transformation algorithm.", null, oAuth2Parameters);
}
}
// If PKCE challenge code was sent, check if the code challenge is upto specifications
if (pkceChallengeCode != null && !OAuth2Util.validatePKCECodeChallenge(pkceChallengeCode, pkceChallengeMethod)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuth2Parameters.getClientId());
params.put("pkceChallenge", pkceChallengeCode);
params.put("pkceMethod", pkceChallengeMethod);
Map<String, Object> configs = new HashMap<>();
configs.put("isPkceMandatory", Boolean.toString(validationResponse.isPkceMandatory()));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Code challenge used is not up to RFC 7636 specifications.", "validate-pkce", configs);
}
return getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_PKCE_CHALLENGE_CODE, "Code challenge used is not up to RFC 7636 " + "specifications.", null, oAuth2Parameters);
}
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.SUCCESS, "PKCE validation is successful.", "validate-pkce", null);
return null;
}
use of org.wso2.carbon.identity.oauth2.dto.OAuth2ClientValidationResponseDTO in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2ServiceTest method testValidateClientInfoWithEmptyGrantTypes.
@Test
public void testValidateClientInfoWithEmptyGrantTypes() throws Exception {
getOAuthAppDO(clientId, null, "dummyCallbackUrl", "dummyTenantDomain");
OAuth2ClientValidationResponseDTO oAuth2ClientValidationResponseDTO = oAuth2Service.validateClientInfo(clientId, "dummyCallBackUrl");
assertEquals(oAuth2ClientValidationResponseDTO.getErrorCode(), OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
}
Aggregations