use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage 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.endpoint.message.OAuthMessage 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.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleAuthFlowThroughFramework.
/**
* This method use to call authentication framework directly via API other than using HTTP redirects.
* Sending wrapper request object to doGet method since other original request doesn't exist required parameters
* Doesn't check SUCCESS_COMPLETED since taking decision with INCOMPLETE status
*
* @param type authenticator type
* @throws URISyntaxException
* @throws InvalidRequestParentException
* @Param type OAuthMessage
*/
private Response handleAuthFlowThroughFramework(OAuthMessage oAuthMessage, String type) throws URISyntaxException, InvalidRequestParentException {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuthMessage.getClientId());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Forward authorization request to framework for user authentication.", "hand-over-to-framework", null);
}
try {
String sessionDataKey = (String) oAuthMessage.getRequest().getAttribute(FrameworkConstants.SESSION_DATA_KEY);
CommonAuthenticationHandler commonAuthenticationHandler = new CommonAuthenticationHandler();
CommonAuthRequestWrapper requestWrapper = new CommonAuthRequestWrapper(oAuthMessage.getRequest());
requestWrapper.setParameter(FrameworkConstants.SESSION_DATA_KEY, sessionDataKey);
requestWrapper.setParameter(FrameworkConstants.RequestParams.TYPE, type);
CommonAuthResponseWrapper responseWrapper = new CommonAuthResponseWrapper(oAuthMessage.getResponse());
commonAuthenticationHandler.doGet(requestWrapper, responseWrapper);
Object attribute = oAuthMessage.getRequest().getAttribute(FrameworkConstants.RequestParams.FLOW_STATUS);
if (attribute != null) {
if (attribute == AuthenticatorFlowStatus.INCOMPLETE) {
if (responseWrapper.isRedirect()) {
return Response.status(HttpServletResponse.SC_FOUND).location(buildURI(responseWrapper.getRedirectURL())).build();
} else {
return Response.status(HttpServletResponse.SC_OK).entity(responseWrapper.getContent()).build();
}
} else {
return authorize(requestWrapper, responseWrapper);
}
} else {
requestWrapper.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.UNKNOWN);
return authorize(requestWrapper, responseWrapper);
}
} catch (ServletException | IOException | URLBuilderException e) {
log.error("Error occurred while sending request to authentication framework.");
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", oAuthMessage.getClientId());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.FAILED, "Server error occurred.", "hand-over-to-framework", null);
}
return Response.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR).build();
}
}
use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleEmptyConsent.
private Response handleEmptyConsent(OAuthMessage oAuthMessage) throws URISyntaxException {
String appName = getOauth2Params(oAuthMessage).getApplicationName();
if (log.isDebugEnabled()) {
log.debug("Invalid authorization request. \'sessionDataKey\' parameter found but \'consent\' " + "parameter could not be found in request");
}
OAuth2Parameters oAuth2Parameters = getOAuth2ParamsFromOAuthMessage(oAuthMessage);
return Response.status(HttpServletResponse.SC_FOUND).location(new URI(getErrorPageURL(oAuthMessage.getRequest(), OAuth2ErrorCodes.INVALID_REQUEST, OAuth2ErrorCodes.OAuth2SubErrorCodes.INVALID_AUTHORIZATION_REQUEST, "Invalid authorization request", appName, oAuth2Parameters))).build();
}
use of org.wso2.carbon.identity.oauth.endpoint.message.OAuthMessage in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method addToBCLogoutSessionToOAuthMessage.
/**
* Store Authorization Code and SessionID for back-channel logout in the cache.
*
* @param oAuthMessage
* @param sessionId
*/
private void addToBCLogoutSessionToOAuthMessage(OAuthMessage oAuthMessage, String sessionId) {
AuthorizationGrantCacheEntry entry = oAuthMessage.getAuthorizationGrantCacheEntry();
if (entry == null) {
log.debug("Authorization code is not found in the redirect URL");
return;
}
entry.setOidcSessionId(sessionId);
}
Aggregations