Search in sources :

Example 1 with PROMPT

use of org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT in project carbon-identity-framework by wso2.

the class GraphBasedSequenceHandler method displayPrompt.

private void displayPrompt(AuthenticationContext context, HttpServletRequest request, HttpServletResponse response, ShowPromptNode promptNode) throws FrameworkException {
    try {
        String promptPage = ConfigurationFacade.getInstance().getAuthenticationEndpointPromptURL();
        String tenantDomainQueryString = null;
        if (!IdentityTenantUtil.isTenantQualifiedUrlsEnabled()) {
            tenantDomainQueryString = "tenantDomain=" + context.getTenantDomain();
            promptPage = FrameworkUtils.appendQueryParamsStringToUrl(promptPage, tenantDomainQueryString);
        }
        String redirectUrl = FrameworkUtils.appendQueryParamsStringToUrl(promptPage, "templateId=" + URLEncoder.encode(promptNode.getTemplateId(), StandardCharsets.UTF_8.name()) + "&promptId=" + context.getContextIdentifier());
        if (promptNode.getData() != null) {
            context.addEndpointParams(promptNode.getData());
        }
        response.sendRedirect(redirectUrl);
        AuthenticationResult authenticationResult = new AuthenticationResult();
        request.setAttribute(FrameworkConstants.RequestAttribute.AUTH_RESULT, authenticationResult);
        request.setAttribute(RESPONSE_HANDLED_BY_FRAMEWORK, Boolean.TRUE);
        request.setAttribute(FrameworkConstants.RequestParams.FLOW_STATUS, AuthenticatorFlowStatus.INCOMPLETE);
    } catch (UnsupportedEncodingException e) {
        throw new FrameworkException("Error while encoding the data to send to prompt page with session data key" + context.getContextIdentifier(), e);
    } catch (IOException e) {
        throw new FrameworkException("Error while redirecting the user for prompt page with session data key" + context.getContextIdentifier(), e);
    }
}
Also used : FrameworkException(org.wso2.carbon.identity.application.authentication.framework.exception.FrameworkException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) AuthenticationResult(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticationResult)

Example 2 with PROMPT

use of org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT in project product-is by wso2.

the class OIDCAuthCodeGrantSSOTestCase method testAuthzRequestWithoutValidSessionForIDENTITY5581.

@Test(groups = "wso2.is", description = "Test authz endpoint before creating a valid session")
public void testAuthzRequestWithoutValidSessionForIDENTITY5581() throws Exception {
    // When accessing the below endpoint from with invalid session it should provide a message with login_required
    OIDCApplication application = applications.get(OIDCUtilTest.playgroundAppOneAppName);
    URI uri = new URIBuilder(OAuth2Constant.APPROVAL_URL).addParameter("client_id", application.getClientId()).addParameter("scope", "openid").addParameter("response_type", "code").addParameter("prompt", "none").addParameter("redirect_uri", application.getCallBackURL()).build();
    HttpResponse httpResponse = sendGetRequest(client, uri.toString());
    String contentData = DataExtractUtil.getContentData(httpResponse);
    Assert.assertTrue(contentData.contains("login_required"));
    EntityUtils.consume(httpResponse.getEntity());
}
Also used : HttpResponse(org.apache.http.HttpResponse) OIDCApplication(org.wso2.identity.integration.test.oidc.bean.OIDCApplication) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) Test(org.testng.annotations.Test)

Example 3 with PROMPT

use of org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method doUserAuthorization.

/**
 * prompt : none
 * The Authorization Server MUST NOT display any authentication
 * or consent user interface pages. An error is returned if the
 * End-User is not already authenticated or the Client does not
 * have pre-configured consent for the requested scopes. This
 * can be used as a method to check for existing authentication
 * and/or consent.
 * <p/>
 * prompt : consent
 * The Authorization Server MUST prompt the End-User for consent before
 * returning information to the Client.
 * <p/>
 * prompt Error : consent_required
 * The Authorization Server requires End-User consent. This
 * error MAY be returned when the prompt parameter in the
 * Authorization Request is set to none to request that the
 * Authorization Server should not display any user
 * interfaces to the End-User, but the Authorization Request
 * cannot be completed without displaying a user interface
 * for End-User consent.
 *
 * @return String URL
 * @throws OAuthSystemException OAuthSystemException
 */
private String doUserAuthorization(OAuthMessage oAuthMessage, String sessionDataKeyFromLogin, OIDCSessionState sessionState) throws OAuthSystemException, ConsentHandlingFailedException, OAuthProblemException {
    OAuth2Parameters oauth2Params = getOauth2Params(oAuthMessage);
    AuthenticatedUser authenticatedUser = getLoggedInUser(oAuthMessage);
    boolean hasUserApproved = isUserAlreadyApproved(oauth2Params, authenticatedUser);
    if (hasPromptContainsConsent(oauth2Params)) {
        // Remove any existing consents.
        String clientId = oauth2Params.getClientId();
        OpenIDConnectUserRPStore.getInstance().removeConsentForUser(authenticatedUser, clientId);
        if (LoggerUtils.isDiagnosticLogsEnabled()) {
            Map<String, Object> params = new HashMap<>();
            params.put("clientId", oauth2Params.getClientId());
            params.put("prompt", oauth2Params.getPrompt());
            if (authenticatedUser != null) {
                try {
                    params.put("user", authenticatedUser.getUserId());
                } catch (UserIdNotFoundException e) {
                    if (StringUtils.isNotBlank(authenticatedUser.getAuthenticatedSubjectIdentifier())) {
                        params.put("user", authenticatedUser.getAuthenticatedSubjectIdentifier().replaceAll(".", "*"));
                    }
                }
            }
            LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, params, OAuthConstants.LogConstants.SUCCESS, "'prompt' contains consent. Hence existing user consent is revoked.", "remove-user-consent", null);
        }
        if (log.isDebugEnabled()) {
            log.debug("Prompt parameter contains 'consent'. Existing consents for user: " + authenticatedUser.toFullQualifiedUsername() + " for oauth app with clientId: " + clientId + " are revoked and user will be prompted to give consent again.");
        }
        // Need to prompt for consent and get user consent for claims as well.
        return promptUserForConsent(sessionDataKeyFromLogin, oauth2Params, authenticatedUser, true, oAuthMessage);
    } else if (isPromptNone(oauth2Params)) {
        return handlePromptNone(oAuthMessage, sessionState, oauth2Params, authenticatedUser, hasUserApproved);
    } else if (isPromptLogin(oauth2Params) || isPromptParamsNotPresent(oauth2Params)) {
        return handleConsent(oAuthMessage, sessionDataKeyFromLogin, sessionState, oauth2Params, authenticatedUser, hasUserApproved);
    } else {
        return StringUtils.EMPTY;
    }
}
Also used : OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject) UserIdNotFoundException(org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)

Example 4 with PROMPT

use of org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT in project identity-inbound-auth-oauth by wso2-extensions.

the class OAuth2AuthzEndpoint method analyzePromptParameter.

private String analyzePromptParameter(OAuthMessage oAuthMessage, OAuth2Parameters params, String prompt) {
    List promptsList = getSupportedPromtsValues();
    boolean containsNone = (OAuthConstants.Prompt.NONE).equals(prompt);
    if (StringUtils.isNotBlank(prompt)) {
        List requestedPrompts = getRequestedPromptList(prompt);
        if (!CollectionUtils.containsAny(requestedPrompts, promptsList)) {
            String message = "Invalid prompt variables passed with the authorization request";
            if (LoggerUtils.isDiagnosticLogsEnabled()) {
                Map<String, Object> logParams = new HashMap<>();
                logParams.put("prompt", prompt);
                logParams.put("clientId", params.getClientId());
                Map<String, Object> configs = new HashMap<>();
                configs.put("serverSupportedPrompts", promptsList);
                LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, logParams, OAuthConstants.LogConstants.FAILED, message, "validate-input-parameters", configs);
            }
            return handleInvalidPromptValues(oAuthMessage, params, prompt, message);
        }
        if (requestedPrompts.size() > 1) {
            if (requestedPrompts.contains(OAuthConstants.Prompt.NONE)) {
                String message = "Invalid prompt variable combination. The value 'none' cannot be used with others " + "prompts. Prompt: ";
                if (LoggerUtils.isDiagnosticLogsEnabled()) {
                    Map<String, Object> logParams = new HashMap<>();
                    logParams.put("prompt", prompt);
                    logParams.put("clientId", params.getClientId());
                    Map<String, Object> configs = new HashMap<>();
                    configs.put("serverSupportedPrompts", promptsList);
                    LoggerUtils.triggerDiagnosticLogEvent(OAuthConstants.LogConstants.OAUTH_INBOUND_SERVICE, logParams, OAuthConstants.LogConstants.FAILED, message, "validate-input-parameters", configs);
                }
                return handleInvalidPromptValues(oAuthMessage, params, prompt, message);
            } else if (requestedPrompts.contains(OAuthConstants.Prompt.LOGIN) && (requestedPrompts.contains(OAuthConstants.Prompt.CONSENT))) {
                oAuthMessage.setForceAuthenticate(true);
                oAuthMessage.setPassiveAuthentication(false);
            }
        } else {
            if ((OAuthConstants.Prompt.LOGIN).equals(prompt)) {
                // prompt for authentication
                oAuthMessage.setForceAuthenticate(true);
                oAuthMessage.setPassiveAuthentication(false);
            } else if (containsNone) {
                oAuthMessage.setForceAuthenticate(false);
                oAuthMessage.setPassiveAuthentication(true);
            } else if ((OAuthConstants.Prompt.CONSENT).equals(prompt)) {
                oAuthMessage.setForceAuthenticate(false);
                oAuthMessage.setPassiveAuthentication(false);
            }
        }
    }
    return null;
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Example 5 with PROMPT

use of org.wso2.carbon.identity.openidconnect.model.Constants.PROMPT 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);
    }
}
Also used : RequestObjectException(org.wso2.carbon.identity.oauth2.RequestObjectException) ClaimMetadataException(org.wso2.carbon.identity.claim.metadata.mgt.exception.ClaimMetadataException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) ConsentClaimsData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ConsentClaimsData) SSOConsentServiceException(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.exception.SSOConsentServiceException) ClaimMetaData(org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) ConsentHandlingFailedException(org.wso2.carbon.identity.oauth.endpoint.exception.ConsentHandlingFailedException) OAuth2Parameters(org.wso2.carbon.identity.oauth2.model.OAuth2Parameters) ServiceProvider(org.wso2.carbon.identity.application.common.model.ServiceProvider) RequestObject(org.wso2.carbon.identity.openidconnect.model.RequestObject) JSONObject(org.json.JSONObject)

Aggregations

HashMap (java.util.HashMap)9 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)9 RequestObject (org.wso2.carbon.identity.openidconnect.model.RequestObject)9 JSONObject (org.json.JSONObject)7 AuthenticatedUser (org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser)4 OAuth2Parameters (org.wso2.carbon.identity.oauth2.model.OAuth2Parameters)4 Test (org.testng.annotations.Test)3 ServiceProvider (org.wso2.carbon.identity.application.common.model.ServiceProvider)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 ArrayList (java.util.ArrayList)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)2 Response (javax.ws.rs.core.Response)2 OAuthResponse (org.apache.oltu.oauth2.common.message.OAuthResponse)2 Matchers.anyString (org.mockito.Matchers.anyString)2 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)2 AfterTest (org.testng.annotations.AfterTest)2 BeforeTest (org.testng.annotations.BeforeTest)2 UserIdNotFoundException (org.wso2.carbon.identity.application.authentication.framework.exception.UserIdNotFoundException)2 ClaimMetaData (org.wso2.carbon.identity.application.authentication.framework.handler.request.impl.consent.ClaimMetaData)2