use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class ResponseTypeHandlerUtil method generateAuthorizationCode.
public static AuthzCodeDO generateAuthorizationCode(OAuthAuthzReqMessageContext oauthAuthzMsgCtx, boolean cacheEnabled, OauthTokenIssuer oauthIssuerImpl) throws IdentityOAuth2Exception {
OAuth2AuthorizeReqDTO authorizationReqDTO = oauthAuthzMsgCtx.getAuthorizationReqDTO();
String authorizationCode;
String codeId = UUID.randomUUID().toString();
Timestamp timestamp = new Timestamp(new Date().getTime());
long validityPeriod = OAuthServerConfiguration.getInstance().getAuthorizationCodeValidityPeriodInSeconds();
// if a VALID callback is set through the callback handler, use
// it instead of the default one
long callbackValidityPeriod = oauthAuthzMsgCtx.getValidityPeriod();
if ((callbackValidityPeriod != OAuthConstants.UNASSIGNED_VALIDITY_PERIOD) && callbackValidityPeriod > 0) {
validityPeriod = callbackValidityPeriod;
}
// convert to milliseconds
validityPeriod = validityPeriod * 1000;
// set the validity period. this is needed by downstream handlers.
// if this is set before - then this will override it by the calculated new value.
oauthAuthzMsgCtx.setValidityPeriod(validityPeriod);
oauthAuthzMsgCtx.setAuthorizationCodeValidityPeriod(validityPeriod);
// set code issued time.this is needed by downstream handlers.
oauthAuthzMsgCtx.setCodeIssuedTime(timestamp.getTime());
if (authorizationReqDTO.getUser() != null && authorizationReqDTO.getUser().isFederatedUser()) {
// if a federated user, treat the tenant domain as similar to application domain.
authorizationReqDTO.getUser().setTenantDomain(authorizationReqDTO.getTenantDomain());
}
try {
authorizationCode = oauthIssuerImpl.authorizationCode(oauthAuthzMsgCtx);
} catch (OAuthSystemException e) {
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, null, OAuthConstants.LogConstants.FAILED, "System error occurred.", "issue-authz-code", null);
throw new IdentityOAuth2Exception(e.getMessage(), e);
}
AuthzCodeDO authzCodeDO = new AuthzCodeDO(authorizationReqDTO.getUser(), oauthAuthzMsgCtx.getApprovedScope(), timestamp, validityPeriod, authorizationReqDTO.getCallbackUrl(), authorizationReqDTO.getConsumerKey(), authorizationCode, codeId, authorizationReqDTO.getPkceCodeChallenge(), authorizationReqDTO.getPkceCodeChallengeMethod());
OAuthTokenPersistenceFactory.getInstance().getAuthorizationCodeDAO().insertAuthorizationCode(authorizationCode, authorizationReqDTO.getConsumerKey(), authorizationReqDTO.getCallbackUrl(), authzCodeDO);
if (cacheEnabled) {
// Cache the authz Code, here we prepend the client_key to avoid collisions with
// AccessTokenDO instances. In database level, these are in two databases. But access
// tokens and authorization codes are in a single cache.
String cacheKeyString = OAuth2Util.buildCacheKeyStringForAuthzCode(authorizationReqDTO.getConsumerKey(), authorizationCode);
OAuthCache.getInstance().addToCache(new OAuthCacheKey(cacheKeyString), authzCodeDO);
if (log.isDebugEnabled()) {
log.debug("Authorization Code info was added to the cache for client id : " + authorizationReqDTO.getConsumerKey());
}
}
if (log.isDebugEnabled()) {
log.debug("Issued Authorization Code to user : " + authorizationReqDTO.getUser() + ", Using the redirect url : " + authorizationReqDTO.getCallbackUrl() + ", Scope : " + OAuth2Util.buildScopeString(oauthAuthzMsgCtx.getApprovedScope()) + ", validity period : " + validityPeriod);
}
if (LoggerUtils.isDiagnosticLogsEnabled()) {
Map<String, Object> params = new HashMap<>();
params.put("clientId", authorizationReqDTO.getConsumerKey());
if (authorizationReqDTO.getUser() != null) {
try {
params.put("user", authorizationReqDTO.getUser().getUserId());
} catch (UserIdNotFoundException e) {
if (StringUtils.isNotBlank(authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier())) {
params.put("user", authorizationReqDTO.getUser().getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
}
}
}
params.put("requestedScopes", OAuth2Util.buildScopeString(authorizationReqDTO.getScopes()));
params.put("redirectUri", authorizationReqDTO.getCallbackUrl());
Map<String, Object> configs = new HashMap<>();
configs.put("authzCodeValidityPeriod", String.valueOf(validityPeriod));
LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "Issued Authorization Code to user.", "issue-authz-code", configs);
}
return authzCodeDO;
}
use of org.apache.amber.oauth2.common.exception.OAuthSystemException in project identity-inbound-auth-oauth by wso2-extensions.
the class SHA256Generator method generateValue.
@Override
public String generateValue(String value) throws OAuthSystemException {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
digest.update(value.getBytes(StandardCharsets.UTF_8));
byte[] messageDigest = digest.digest();
// Return the hex representation of the hash.
return Hex.toHexString(messageDigest);
} catch (Exception e) {
throw new OAuthSystemException("Error while generating the token value.", e);
}
}
use of org.apache.amber.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.amber.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.amber.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;
}
Aggregations