use of org.apache.oltu.oauth2.common.OAuth 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.OAuth 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.OAuth in project identity-inbound-auth-oauth by wso2-extensions.
the class OAuth2AuthzEndpoint method handlePostConsent.
private void handlePostConsent(OAuthMessage oAuthMessage) throws ConsentHandlingFailedException {
OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
String tenantDomain = EndpointUtil.getSPTenantDomainFromClientId(oauth2Params.getClientId());
setSPAttributeToRequest(oAuthMessage.getRequest(), oauth2Params.getApplicationName(), tenantDomain);
String spTenantDomain = oauth2Params.getTenantDomain();
AuthenticatedUser loggedInUser = getLoggedInUser(oAuthMessage);
String clientId = oauth2Params.getClientId();
ServiceProvider serviceProvider;
if (log.isDebugEnabled()) {
log.debug("Initiating post user consent handling for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
}
try {
if (isConsentHandlingFromFrameworkSkipped(oauth2Params)) {
if (log.isDebugEnabled()) {
log.debug("Consent handling from framework skipped for client_id: " + clientId + " of tenantDomain: " + spTenantDomain + " for user: " + loggedInUser.toFullQualifiedUsername() + ". " + "Therefore handling post consent is not applicable.");
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", clientId);
Map<String, Object> configs = new HashMap<>();
configs.put("skipConsent", "true");
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Consent is disabled for the OAuth client.", "handle-consent", configs);
}
return;
}
List<Integer> approvedClaimIds = getUserConsentClaimIds(oAuthMessage);
serviceProvider = getServiceProvider(clientId);
/*
With the current implementation of the SSOConsentService we need to send back the original
ConsentClaimsData object we got during pre consent stage. Currently we are repeating the API call
during post consent handling to get the original ConsentClaimsData object (Assuming there is no
change in SP during pre-consent and post-consent).
The API on the SSO Consent Service will be improved to avoid having to send the original
ConsentClaimsData object.
*/
ConsentClaimsData value = getConsentRequiredClaims(loggedInUser, serviceProvider, oauth2Params);
/*
It is needed to pitch the consent required claims with the OIDC claims. otherwise the consent of the
the claims which are not in the OIDC claims will be saved as consent denied.
*/
if (value != null) {
// Remove the claims which dont have values given by the user.
value.setRequestedClaims(removeConsentRequestedNullUserAttributes(value.getRequestedClaims(), loggedInUser.getUserAttributes(), spTenantDomain));
List<ClaimMetaData> requestedOidcClaimsList = getRequestedOidcClaimsList(value, oauth2Params, spTenantDomain);
value.setRequestedClaims(requestedOidcClaimsList);
}
// Call framework and create the consent receipt.
if (log.isDebugEnabled()) {
log.debug("Creating user consent receipt for user: " + loggedInUser.toFullQualifiedUsername() + " for client_id: " + clientId + " of tenantDomain: " + spTenantDomain);
}
Map<String, Object> params;
if (hasPromptContainsConsent(oauth2Params)) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
params = new HashMap<>();
params.put("clientId", clientId);
params.put("prompt", oauth2Params.getPrompt());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
}
getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, true);
} else {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
params = new HashMap<>();
params.put("clientId", clientId);
params.put("prompt", oauth2Params.getPrompt());
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, null, "hand-over-to-consent-service", null);
}
getSSOConsentService().processConsent(approvedClaimIds, serviceProvider, loggedInUser, value, false);
}
} catch (OAuthSystemException | SSOConsentServiceException e) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "process-consent", null);
}
String msg = "Error while processing consent of user: " + loggedInUser.toFullQualifiedUsername() + " for " + "client_id: " + clientId + " of tenantDomain: " + spTenantDomain;
throw new ConsentHandlingFailedException(msg, e);
} catch (ClaimMetadataException e) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting " + "claim mappings for %s.", OIDC_DIALECT), "process-consent", null);
}
throw new ConsentHandlingFailedException("Error while getting claim mappings for " + OIDC_DIALECT, e);
} catch (RequestObjectException e) {
if (LoggerUtils.isDiagnosticLogsEnabled()) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, String.format("Error occurred while getting essential claims for the session data key : %s.", oauth2Params.getSessionDataKey()), "process-consent", null);
}
throw new ConsentHandlingFailedException("Error while getting essential claims for the session data key " + ": " + oauth2Params.getSessionDataKey(), e);
}
}
use of org.apache.oltu.oauth2.common.OAuth in project identity-inbound-auth-oauth by wso2-extensions.
the class RefreshGrantHandler method createTokens.
private void createTokens(AccessTokenDO accessTokenDO, OAuthTokenReqMessageContext tokReqMsgCtx) throws IdentityOAuth2Exception {
try {
OauthTokenIssuer oauthTokenIssuer = OAuth2Util.getOAuthTokenIssuerForOAuthApp(accessTokenDO.getConsumerKey());
String accessToken = oauthTokenIssuer.accessToken(tokReqMsgCtx);
String refreshToken = oauthTokenIssuer.refreshToken(tokReqMsgCtx);
if (log.isDebugEnabled()) {
if (IdentityUtil.isTokenLoggable(IdentityConstants.IdentityTokens.ACCESS_TOKEN)) {
log.debug("New access token (hashed): " + DigestUtils.sha256Hex(accessToken) + " & new refresh token (hashed): " + DigestUtils.sha256Hex(refreshToken));
} else {
log.debug("Access token and refresh token generated.");
}
}
accessTokenDO.setAccessToken(accessToken);
accessTokenDO.setRefreshToken(refreshToken);
} catch (OAuthSystemException e) {
throw new IdentityOAuth2Exception("Error when generating the tokens.", e);
} catch (InvalidOAuthClientException e) {
throw new IdentityOAuth2Exception("Error while retrieving oauth issuer for the app with clientId: " + accessTokenDO.getConsumerKey(), e);
}
}
use of org.apache.oltu.oauth2.common.OAuth in project BIMserver by opensourceBIM.
the class SendUrl method main.
public static void main(String[] args) {
try {
OAuthClientRequest request = OAuthClientRegistrationRequest.location("https://thisisanexperimentalserver.com/oauth/register/", OAuthRegistration.Type.PUSH).setName("Zapier").setUrl("https://zapier.com/dashboard/auth/oauth/return/App56192API").setDescription("App Description").setRedirectURL("https://zapier.com/dashboard/auth/oauth/return/App56192API").buildJSONMessage();
OAuthRegistrationClient oauthclient = new OAuthRegistrationClient(new org.bimserver.webservices.impl.URLConnectionClient());
OAuthClientRegistrationResponse response = oauthclient.clientInfo(request);
System.out.println(response.getClientId());
System.out.println(response.getClientSecret());
} catch (OAuthSystemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (OAuthProblemException e) {
e.printStackTrace();
}
}
Aggregations