use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method getAllowedOAuthScopes.
private static List<String> getAllowedOAuthScopes(OAuth2Parameters params) throws OAuthSystemException {
Set<String> allowedScopes = params.getScopes();
List<String> allowedOAuthScopes = new ArrayList<>();
if (CollectionUtils.isNotEmpty(allowedScopes)) {
try {
startTenantFlow(params.getTenantDomain());
/* If DropUnregisteredScopes scopes config is enabled
then any unregistered scopes(excluding internal scopes
and allowed scopes) is be dropped. Therefore they will
not be shown in the user consent screen.*/
if (oauthServerConfiguration.isDropUnregisteredScopes()) {
if (log.isDebugEnabled()) {
log.debug("DropUnregisteredScopes config is enabled. Attempting to drop unregistered scopes.");
}
allowedScopes = dropUnregisteredScopes(params);
}
// Get registered OIDC scopes.
String[] oidcScopes = oAuthAdminService.getScopeNames();
List<String> oidcScopeList = new ArrayList<>(Arrays.asList(oidcScopes));
for (String scope : allowedScopes) {
if (!oidcScopeList.contains(scope)) {
allowedOAuthScopes.add(scope);
}
}
} catch (IdentityOAuthAdminException e) {
throw new OAuthSystemException("Error while retrieving OIDC scopes.", e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
if (log.isDebugEnabled()) {
log.debug("Allowed OAuth scopes : " + allowedOAuthScopes.stream().collect(Collectors.joining(" ")) + " for client : " + params.getClientId());
}
return allowedOAuthScopes;
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method getRegisteredScopes.
private static Set<String> getRegisteredScopes(Set<String> requestedScopes) throws OAuthSystemException {
try {
String requestedScopesStr = StringUtils.join(requestedScopes, " ");
Set<String> registeredScopes = new HashSet<>();
Set<Scope> registeredScopeSet = oAuth2ScopeService.getScopes(null, null, true, requestedScopesStr);
registeredScopeSet.forEach(scope -> registeredScopes.add(scope.getName()));
return registeredScopes;
} catch (IdentityOAuth2ScopeServerException e) {
throw new OAuthSystemException("Error occurred while retrieving registered scopes.", e);
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException 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.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class EndpointUtil method storeOAuthScopeConsent.
/**
* Store consent given for OAuth scopes by the user for the application.
*
* @param user Authenticated user.
* @param params OAuth2 parameters.
* @param overrideExistingConsent True to override existing consent, otherwise merge the new consent with
* existing consent.
* @throws OAuthSystemException
*/
public static void storeOAuthScopeConsent(AuthenticatedUser user, OAuth2Parameters params, boolean overrideExistingConsent) throws OAuthSystemException {
try {
Set<String> userApprovedScopesSet = params.getConsentRequiredScopes();
if (CollectionUtils.isNotEmpty(userApprovedScopesSet)) {
if (log.isDebugEnabled()) {
log.debug("Storing user consent for approved scopes : " + userApprovedScopesSet.stream().collect(Collectors.joining(" ")) + " of client : " + params.getClientId());
}
List<String> userApprovedScopes = new ArrayList<>(userApprovedScopesSet);
// Remove OIDC scopes.
userApprovedScopes.removeAll(getOIDCScopeNames());
String userId = getUserIdOfAuthenticatedUser(user);
String appId = getAppIdFromClientId(params.getClientId());
if (overrideExistingConsent) {
if (log.isDebugEnabled()) {
log.debug("Overriding existing consents of the user : " + userId + " for application : " + appId);
}
oAuth2ScopeService.addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
} else {
boolean isUserConsentExist = oAuth2ScopeService.isUserHasAnExistingConsentForApp(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()));
if (isUserConsentExist) {
if (log.isDebugEnabled()) {
log.debug("Updating existing consents of the user : " + userId + " for application : " + appId);
}
oAuth2ScopeService.updateUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
} else {
if (log.isDebugEnabled()) {
log.debug("Adding new consent to the user : " + userId + " for application : " + appId);
}
oAuth2ScopeService.addUserConsentForApplication(userId, appId, IdentityTenantUtil.getTenantId(user.getTenantDomain()), userApprovedScopes, null);
}
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> consentParams = new HashMap<>();
consentParams.put("clientId", params.getClientId());
consentParams.put("approvedScopes", userApprovedScopes);
consentParams.put("user", userId);
Map<String, Object> configs = new HashMap<>();
configs.put("overrideExistingConsent", String.valueOf(overrideExistingConsent));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, consentParams, OAuthConstants.LogConstants.SUCCESS, "Successfully persisted oauth scopes.", "persist-oauth-scope-consent", configs);
}
}
} catch (IdentityOAuthAdminException e) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "persist-oauth-scope-consent", null);
throw new OAuthSystemException("Error occurred while removing OIDC scopes from approved OAuth scopes.", e);
} catch (IdentityOAuth2ScopeException e) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "persist-oauth-scope-consent", null);
throw new OAuthSystemException("Error occurred while storing OAuth scope consent.", e);
}
}
use of org.apache.oltu.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handleUserConsent.
private String handleUserConsent(OAuthMessage oAuthMessage, String consent, OIDCSessionState sessionState) throws OAuthSystemException {
OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
storeUserConsent(oAuthMessage, consent);
OAuthResponse oauthResponse;
String responseType = oauth2Params.getResponseType();
HttpRequestHeaderHandler httpRequestHeaderHandler = new HttpRequestHeaderHandler(oAuthMessage.getRequest());
// authorizing the request
OAuth2AuthorizeRespDTO authzRespDTO = authorize(oauth2Params, oAuthMessage.getSessionDataCacheEntry(), httpRequestHeaderHandler);
if (isSuccessfulAuthorization(authzRespDTO)) {
oauthResponse = handleSuccessAuthorization(oAuthMessage, sessionState, oauth2Params, responseType, authzRespDTO);
} else if (isFailureAuthorizationWithErorrCode(authzRespDTO)) {
// Authorization failure due to various reasons
return handleFailureAuthorization(oAuthMessage, sessionState, oauth2Params, authzRespDTO);
} else {
// Authorization failure due to various reasons
return handleServerErrorAuthorization(oAuthMessage, sessionState, oauth2Params);
}
// When response_mode equals to form_post, body parameter is passed back.
if (isFormPostModeAndResponseBodyExists(oauth2Params, oauthResponse)) {
return oauthResponse.getBody();
} else {
// as per the specification: http://openid.net/specs/openid-connect-core-1_0.html#HybridCallback
if (hasIDTokenInResponseType(responseType)) {
return buildOIDCResponseWithURIFragment(oauthResponse, authzRespDTO);
} else {
return appendAuthenticatedIDPs(oAuthMessage.getSessionDataCacheEntry(), oauthResponse.getLocationUri());
}
}
}
Aggregations