use of org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI 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.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI 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.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method getUserConsentURL.
/**
* Returns the consent page URL.
*
* @param params OAuth2 Parameters.
* @param loggedInUser The logged in user
* @param isOIDC Whether the flow is an OIDC or not.
* @param oAuthMessage oAuth Message.
* @return The consent url.
*/
public static String getUserConsentURL(OAuth2Parameters params, String loggedInUser, String sessionDataKey, boolean isOIDC, OAuthMessage oAuthMessage) throws OAuthSystemException {
String queryString = "";
if (log.isDebugEnabled()) {
log.debug("Received Session Data Key is : " + sessionDataKey);
if (params == null) {
log.debug("Received OAuth2 params are Null for UserConsentURL");
}
}
SessionDataCache sessionDataCache = SessionDataCache.getInstance();
SessionDataCacheEntry entry;
if (oAuthMessage != null) {
entry = oAuthMessage.getResultFromLogin();
} else {
entry = sessionDataCache.getValueFromCache(new SessionDataCacheKey(sessionDataKey));
}
AuthenticatedUser user = null;
String consentPage = null;
String sessionDataKeyConsent = UUID.randomUUID().toString();
try {
if (entry != null && entry.getQueryString() != null) {
if (entry.getQueryString().contains(REQUEST_URI) && params != null) {
// When request_uri requests come without redirect_uri, we need to append it to the SPQueryParams
// to be used in storing consent data
entry.setQueryString(entry.getQueryString() + "&" + PROP_REDIRECT_URI + "=" + params.getRedirectURI());
}
queryString = URLEncoder.encode(entry.getQueryString(), UTF_8);
}
if (isOIDC) {
consentPage = OAuth2Util.OAuthURL.getOIDCConsentPageUrl();
} else {
consentPage = OAuth2Util.OAuthURL.getOAuth2ConsentPageUrl();
}
if (params != null) {
consentPage += "?" + OAuthConstants.OIDC_LOGGED_IN_USER + "=" + URLEncoder.encode(loggedInUser, UTF_8) + "&application=";
if (StringUtils.isNotEmpty(params.getDisplayName())) {
consentPage += URLEncoder.encode(params.getDisplayName(), UTF_8);
} else {
consentPage += URLEncoder.encode(params.getApplicationName(), UTF_8);
}
consentPage += "&tenantDomain=" + getSPTenantDomainFromClientId(params.getClientId());
if (entry != null) {
user = entry.getLoggedInUser();
}
setConsentRequiredScopesToOAuthParams(user, params);
Set<String> consentRequiredScopesSet = params.getConsentRequiredScopes();
String consentRequiredScopes = StringUtils.EMPTY;
if (CollectionUtils.isNotEmpty(consentRequiredScopesSet)) {
consentRequiredScopes = String.join(" ", consentRequiredScopesSet).trim();
}
consentPage = consentPage + "&" + OAuthConstants.OAuth20Params.SCOPE + "=" + URLEncoder.encode(consentRequiredScopes, UTF_8) + "&" + OAuthConstants.SESSION_DATA_KEY_CONSENT + "=" + URLEncoder.encode(sessionDataKeyConsent, UTF_8) + "&" + "&spQueryParams=" + queryString;
if (entry != null) {
consentPage = FrameworkUtils.getRedirectURLWithFilteredParams(consentPage, entry.getEndpointParams());
entry.setValidityPeriod(TimeUnit.MINUTES.toNanos(IdentityUtil.getTempDataCleanUpTimeout()));
sessionDataCache.addToCache(new SessionDataCacheKey(sessionDataKeyConsent), entry);
} else {
if (log.isDebugEnabled()) {
log.debug("Cache Entry is Null from SessionDataCache.");
}
}
} else {
throw new OAuthSystemException("Error while retrieving the application name");
}
} catch (UnsupportedEncodingException e) {
throw new OAuthSystemException("Error while encoding the url", e);
}
return consentPage;
}
use of org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI in project identity-inbound-auth-oauth by wso2-extensions.
the class OIDCSessionIFrameServlet method getCallbackURL.
private String getCallbackURL(HttpServletRequest request, String clientId) throws InvalidOAuthClientException, IdentityOAuth2Exception, OIDCSessionManagerException {
OAuthAppDO oAuthAppDO = OAuth2Util.getAppInformationByClientId(clientId);
String configuredCallbackURL = oAuthAppDO.getCallbackUrl();
if (log.isDebugEnabled()) {
log.debug("Requested client_id : " + clientId + " Configured callbackUrl : " + configuredCallbackURL);
}
if (StringUtils.isBlank(configuredCallbackURL)) {
throw new OIDCSessionManagerException("CallbackURL is empty in service provider configuration, clientId : " + clientId);
}
if (configuredCallbackURL.startsWith(OAuthConstants.CALLBACK_URL_REGEXP_PREFIX)) {
if (log.isDebugEnabled()) {
log.debug("Regex value found for callback url in service provider.");
}
String rpIFrameReqCallbackURL = request.getParameter(OIDCSessionConstants.OIDC_REDIRECT_URI_PARAM);
if (StringUtils.isBlank(rpIFrameReqCallbackURL)) {
throw new OIDCSessionManagerException("Invalid request. redirect_uri not found in request as parameter. It is " + "mandatory because of there is regex pattern for " + "callback url in service provider configuration. client_id : " + clientId);
} else {
if (log.isDebugEnabled()) {
log.debug("Requested redirect_uri from rp IFrame : " + rpIFrameReqCallbackURL);
}
String regexp = configuredCallbackURL.substring(OAuthConstants.CALLBACK_URL_REGEXP_PREFIX.length());
if (rpIFrameReqCallbackURL.matches(regexp)) {
if (log.isDebugEnabled()) {
log.debug("Requested redirect_uri is matched with the regex in service provider.");
}
configuredCallbackURL = rpIFrameReqCallbackURL;
} else {
throw new OIDCSessionManagerException("Invalid request. redirect_uri is not matched with the regex that is " + "configured in the service provider, client_id : " + clientId);
}
}
}
return configuredCallbackURL;
}
use of org.wso2.carbon.identity.oauth.common.OAuthConstants.OAuth20Params.REDIRECT_URI in project identity-inbound-auth-oauth by wso2-extensions.
the class AuthorizationCodeGrantHandler method validateGrant.
@Override
public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
super.validateGrant(tokReqMsgCtx);
OAuth2AccessTokenReqDTO tokenReq = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
AuthzCodeDO authzCodeBean = getPersistedAuthzCode(tokenReq);
validateAuthzCodeFromRequest(authzCodeBean, tokenReq.getClientId(), tokenReq.getAuthorizationCode());
try {
// If redirect_uri was given in the authorization request,
// token request should send matching redirect_uri value.
validateCallbackUrlFromRequest(tokenReq.getCallbackURI(), authzCodeBean.getCallbackUrl());
validatePKCECode(authzCodeBean, tokenReq.getPkceCodeVerifier());
setPropertiesForTokenGeneration(tokReqMsgCtx, tokenReq, authzCodeBean);
} finally {
// After validating grant, authorization code is revoked. This is done to stop repetitive usage of
// same authorization code in erroneous token requests.
tokReqMsgCtx.addProperty(CODE_ID, authzCodeBean.getAuthzCodeId());
revokeAuthorizationCode(authzCodeBean);
}
if (log.isDebugEnabled()) {
log.debug("Found Authorization Code for Client : " + tokenReq.getClientId() + ", authorized user : " + authzCodeBean.getAuthorizedUser() + ", scope : " + OAuth2Util.buildScopeString(authzCodeBean.getScope()));
}
return true;
}
Aggregations