Search in sources :

Example 51 with ExternalContext

use of javax.faces.context.ExternalContext in project ART-TIME by Artezio.

the class WebCachedInterceptorTest method testGetContextProperties_forApplicationScope.

@Test
public void testGetContextProperties_forApplicationScope() {
    Map<String, Object> contextProperties = new HashMap<String, Object>();
    ExternalContext externalContext = createMock(ExternalContext.class);
    expect(facesContextMock.getExternalContext()).andReturn(externalContext);
    expect(externalContext.getApplicationMap()).andReturn(contextProperties);
    replay(facesContextMock, externalContext);
    Map<String, Object> actual = interceptor.getContextProperties(Scope.APPLICATION_SCOPED);
    verify(facesContextMock, externalContext);
    assertEquals(contextProperties, actual);
}
Also used : HashMap(java.util.HashMap) ExternalContext(javax.faces.context.ExternalContext) Test(org.junit.Test)

Example 52 with ExternalContext

use of javax.faces.context.ExternalContext in project ART-TIME by Artezio.

the class WebCachedInterceptorTest method testProcess_addToCache_ifClassAnnotated.

@SuppressWarnings("unchecked")
@Test
public void testProcess_addToCache_ifClassAnnotated() throws Exception {
    InvocationContext context = createMock(InvocationContext.class);
    Method method = AnnotatedClass.class.getMethod("getTestValue");
    Map<String, Object> contextProperties = new HashMap<String, Object>();
    Object[] parameters = new Object[2];
    AnnotatedClass targetInstance = new AnnotatedClass();
    ExternalContext externalContext = createMock(ExternalContext.class);
    expect(context.getMethod()).andReturn(method);
    expect(context.getTarget()).andReturn(targetInstance);
    expect(facesContextMock.getExternalContext()).andReturn(externalContext);
    expect(externalContext.getRequestMap()).andReturn(contextProperties);
    expect(context.getParameters()).andReturn(parameters);
    expect(context.proceed()).andReturn(getTestValue());
    replay(context, facesContextMock, externalContext);
    Object actual = interceptor.process(context);
    verify(context, facesContextMock, externalContext);
    String cacheId = "_webCache:" + targetInstance.getClass().getName();
    Map<String, Object> cache = (Map<String, Object>) contextProperties.get(cacheId);
    WebCachedInterceptor.CacheKey cacheKey = interceptor.new CacheKey(targetInstance.getClass(), method, parameters);
    assertEquals(cache.get(cacheKey.toString()), actual);
}
Also used : HashMap(java.util.HashMap) Method(java.lang.reflect.Method) ExternalContext(javax.faces.context.ExternalContext) InvocationContext(javax.interceptor.InvocationContext) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 53 with ExternalContext

use of javax.faces.context.ExternalContext in project ART-TIME by Artezio.

the class WebCachedInterceptorTest method testProcess_addToCache.

@SuppressWarnings("unchecked")
@Test
public void testProcess_addToCache() throws Exception {
    InvocationContext context = createMock(InvocationContext.class);
    Method method = this.getClass().getMethod("getTestValue");
    Map<String, Object> contextProperties = new HashMap<String, Object>();
    Object[] parameters = new Object[2];
    String targetInstance = "targetInstance";
    ExternalContext externalContext = createMock(ExternalContext.class);
    expect(context.getMethod()).andReturn(method);
    expect(context.getTarget()).andReturn(targetInstance);
    expect(facesContextMock.getExternalContext()).andReturn(externalContext);
    expect(externalContext.getRequestMap()).andReturn(contextProperties);
    expect(context.getParameters()).andReturn(parameters);
    expect(context.proceed()).andReturn(getTestValue());
    replay(context, facesContextMock, externalContext);
    Object actual = interceptor.process(context);
    verify(context, facesContextMock, externalContext);
    String cacheId = "_webCache:" + targetInstance.getClass().getName();
    Map<String, Object> cache = (Map<String, Object>) contextProperties.get(cacheId);
    WebCachedInterceptor.CacheKey cacheKey = interceptor.new CacheKey(targetInstance.getClass(), method, parameters);
    assertEquals(cache.get(cacheKey.toString()), actual);
}
Also used : HashMap(java.util.HashMap) ExternalContext(javax.faces.context.ExternalContext) Method(java.lang.reflect.Method) InvocationContext(javax.interceptor.InvocationContext) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test)

Example 54 with ExternalContext

use of javax.faces.context.ExternalContext in project fit3d by fkaiserbio.

the class ConfirmView method init.

@PostConstruct
public void init() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    Flash flash = externalContext.getFlash();
    job = (Fit3DJob) flash.get("job");
    logger.info("received job {}", job);
}
Also used : FacesContext(javax.faces.context.FacesContext) ExternalContext(javax.faces.context.ExternalContext) Flash(javax.faces.context.Flash) PostConstruct(javax.annotation.PostConstruct)

Example 55 with ExternalContext

use of javax.faces.context.ExternalContext in project oxAuth by GluuFederation.

the class AuthorizeAction method checkPermissionGranted.

public void checkPermissionGranted() throws IOException {
    if ((clientId == null) || clientId.isEmpty()) {
        log.debug("Permission denied. client_id should be not empty.");
        permissionDenied();
        return;
    }
    Client client = null;
    try {
        client = clientService.getClient(clientId);
    } catch (EntryPersistenceException ex) {
        log.debug("Permission denied. Failed to find client by inum '{}' in LDAP.", clientId, ex);
        permissionDenied();
        return;
    }
    if (client == null) {
        log.debug("Permission denied. Failed to find client_id '{}' in LDAP.", clientId);
        permissionDenied();
        return;
    }
    // Fix the list of scopes in the authorization page. oxAuth #739
    Set<String> grantedScopes = scopeChecker.checkScopesPolicy(client, scope);
    allowedScope = org.gluu.oxauth.model.util.StringUtils.implode(grantedScopes, " ");
    SessionId session = getSession();
    List<Prompt> prompts = Prompt.fromString(prompt, " ");
    try {
        redirectUri = authorizeRestWebServiceValidator.validateRedirectUri(client, redirectUri, state, session != null ? session.getSessionAttributes().get(SESSION_USER_CODE) : null, (HttpServletRequest) externalContext.getRequest());
    } catch (WebApplicationException e) {
        log.error(e.getMessage(), e);
        permissionDenied();
        return;
    }
    try {
        session = sessionIdService.assertAuthenticatedSessionCorrespondsToNewRequest(session, acrValues);
    } catch (AcrChangedException e) {
        log.debug("There is already existing session which has another acr then {}, session: {}", acrValues, session.getId());
        if (e.isForceReAuthentication()) {
            session = handleAcrChange(session, prompts);
        } else {
            log.error("ACR is changed, please provide a supported and enabled acr value");
            permissionDenied();
            return;
        }
    }
    if (session == null || StringUtils.isBlank(session.getUserDn()) || SessionIdState.AUTHENTICATED != session.getState()) {
        Map<String, String> parameterMap = externalContext.getRequestParameterMap();
        Map<String, String> requestParameterMap = requestParameterService.getAllowedParameters(parameterMap);
        String redirectTo = "/login.xhtml";
        boolean useExternalAuthenticator = externalAuthenticationService.isEnabled(AuthenticationScriptUsageType.INTERACTIVE);
        if (useExternalAuthenticator) {
            List<String> acrValuesList = sessionIdService.acrValuesList(this.acrValues);
            if (acrValuesList.isEmpty()) {
                acrValuesList = Arrays.asList(defaultAuthenticationMode.getName());
            }
            CustomScriptConfiguration customScriptConfiguration = externalAuthenticationService.determineCustomScriptConfiguration(AuthenticationScriptUsageType.INTERACTIVE, acrValuesList);
            if (customScriptConfiguration == null) {
                log.error("Failed to get CustomScriptConfiguration. auth_step: {}, acr_values: {}", 1, this.acrValues);
                permissionDenied();
                return;
            }
            String acr = customScriptConfiguration.getName();
            requestParameterMap.put(JwtClaimName.AUTHENTICATION_CONTEXT_CLASS_REFERENCE, acr);
            requestParameterMap.put("auth_step", Integer.toString(1));
            String tmpRedirectTo = externalAuthenticationService.executeExternalGetPageForStep(customScriptConfiguration, 1);
            if (StringHelper.isNotEmpty(tmpRedirectTo)) {
                log.trace("Redirect to person authentication login page: {}", tmpRedirectTo);
                redirectTo = tmpRedirectTo;
            }
        }
        // Store Remote IP
        requestParameterMap.put(Constants.REMOTE_IP, getRemoteIp());
        // User Code used in Device Authz flow
        if (session != null && session.getSessionAttributes().containsKey(SESSION_USER_CODE)) {
            String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
            requestParameterMap.put(SESSION_USER_CODE, userCode);
        }
        // Create unauthenticated session
        SessionId unauthenticatedSession = sessionIdService.generateUnauthenticatedSessionId(null, new Date(), SessionIdState.UNAUTHENTICATED, requestParameterMap, false);
        unauthenticatedSession.setSessionAttributes(requestParameterMap);
        unauthenticatedSession.addPermission(clientId, false);
        // Copy ACR script parameters
        if (appConfiguration.getKeepAuthenticatorAttributesOnAcrChange()) {
            authenticationService.copyAuthenticatorExternalAttributes(session, unauthenticatedSession);
        }
        // #1030, fix for flow 4 - transfer previous session permissions to new session
        if (session != null && session.getPermissionGrantedMap() != null && session.getPermissionGrantedMap().getPermissionGranted() != null) {
            for (Map.Entry<String, Boolean> entity : session.getPermissionGrantedMap().getPermissionGranted().entrySet()) {
                unauthenticatedSession.addPermission(entity.getKey(), entity.getValue());
            }
            // #1030, remove previous session
            sessionIdService.remove(session);
        }
        // always persist is prompt is not none
        boolean persisted = sessionIdService.persistSessionId(unauthenticatedSession, !prompts.contains(Prompt.NONE));
        if (persisted && log.isTraceEnabled()) {
            log.trace("Session '{}' persisted to LDAP", unauthenticatedSession.getId());
        }
        this.sessionId = unauthenticatedSession.getId();
        cookieService.createSessionIdCookie(unauthenticatedSession, false);
        cookieService.creatRpOriginIdCookie(redirectUri);
        identity.setSessionId(unauthenticatedSession);
        Map<String, Object> loginParameters = new HashMap<String, Object>();
        if (requestParameterMap.containsKey(AuthorizeRequestParam.LOGIN_HINT)) {
            loginParameters.put(AuthorizeRequestParam.LOGIN_HINT, requestParameterMap.get(AuthorizeRequestParam.LOGIN_HINT));
        }
        boolean enableRedirect = StringHelper.toBoolean(System.getProperty("gluu.enable-redirect", "false"), false);
        if (!enableRedirect && redirectTo.toLowerCase().endsWith("xhtml")) {
            if (redirectTo.toLowerCase().endsWith("postlogin.xhtml")) {
                authenticator.authenticateWithOutcome();
            } else {
                authenticator.prepareAuthenticationForStep(unauthenticatedSession);
                facesService.renderView(redirectTo);
            }
        } else {
            facesService.redirectWithExternal(redirectTo, loginParameters);
        }
        return;
    }
    String userCode = session.getSessionAttributes().get(SESSION_USER_CODE);
    if (StringUtils.isBlank(userCode) && StringUtils.isBlank(redirectionUriService.validateRedirectionUri(clientId, redirectUri))) {
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseStatus(HttpServletResponse.SC_BAD_REQUEST);
        externalContext.setResponseContentType(MediaType.APPLICATION_JSON);
        externalContext.getResponseOutputWriter().write(errorResponseFactory.getErrorAsJson(AuthorizeErrorResponseType.INVALID_REQUEST_REDIRECT_URI, state, ""));
        facesContext.responseComplete();
    }
    if (log.isTraceEnabled()) {
        log.trace("checkPermissionGranted, userDn = " + session.getUserDn());
    }
    if (prompts.contains(Prompt.SELECT_ACCOUNT)) {
        Map requestParameterMap = requestParameterService.getAllowedParameters(externalContext.getRequestParameterMap());
        facesService.redirect("/selectAccount.xhtml", requestParameterMap);
        return;
    }
    if (prompts.contains(Prompt.NONE) && prompts.size() > 1) {
        invalidRequest();
        return;
    }
    ExternalPostAuthnContext postAuthnContext = new ExternalPostAuthnContext(client, session, (HttpServletRequest) externalContext.getRequest(), (HttpServletResponse) externalContext.getResponse());
    final boolean forceAuthorization = externalPostAuthnService.externalForceAuthorization(client, postAuthnContext);
    final boolean hasConsentPrompt = prompts.contains(Prompt.CONSENT);
    if (!hasConsentPrompt && !forceAuthorization) {
        if (appConfiguration.getTrustedClientEnabled() && client.getTrustedClient()) {
            // if trusted client = true, then skip authorization page and grant access directly
            permissionGranted(session);
            return;
        } else if (ServerUtil.isTrue(appConfiguration.getSkipAuthorizationForOpenIdScopeAndPairwiseId()) && SubjectType.PAIRWISE.toString().equals(client.getSubjectType()) && hasOnlyOpenidScope()) {
            // If a client has only openid scope and pairwise id, person should not have to authorize. oxAuth-743
            permissionGranted(session);
            return;
        }
        final User user = sessionIdService.getUser(session);
        ClientAuthorization clientAuthorization = clientAuthorizationsService.find(user.getAttribute("inum"), client.getClientId());
        if (clientAuthorization != null && clientAuthorization.getScopes() != null && Arrays.asList(clientAuthorization.getScopes()).containsAll(org.gluu.oxauth.model.util.StringUtils.spaceSeparatedToList(scope))) {
            permissionGranted(session);
            return;
        }
    }
    if (externalConsentGatheringService.isEnabled()) {
        if (consentGatherer.isConsentGathered()) {
            log.trace("Consent-gathered flow passed successfully");
            permissionGranted(session);
            return;
        }
        log.trace("Starting external consent-gathering flow");
        boolean result = consentGatherer.configure(session.getUserDn(), clientId, state);
        if (!result) {
            log.error("Failed to initialize external consent-gathering flow.");
            permissionDenied();
            return;
        }
    }
}
Also used : User(org.gluu.oxauth.model.common.User) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) EntryPersistenceException(org.gluu.persist.exception.EntryPersistenceException) HttpServletRequest(javax.servlet.http.HttpServletRequest) AcrChangedException(org.gluu.oxauth.model.exception.AcrChangedException) ExternalContext(javax.faces.context.ExternalContext) Client(org.gluu.oxauth.model.registration.Client) SessionId(org.gluu.oxauth.model.common.SessionId) ClientAuthorization(org.gluu.oxauth.model.ldap.ClientAuthorization) ExternalPostAuthnContext(org.gluu.oxauth.service.external.context.ExternalPostAuthnContext) Date(java.util.Date) Prompt(org.gluu.oxauth.model.common.Prompt) CustomScriptConfiguration(org.gluu.model.custom.script.conf.CustomScriptConfiguration) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

ExternalContext (javax.faces.context.ExternalContext)58 FacesContext (javax.faces.context.FacesContext)28 Test (org.junit.Test)17 HttpServletRequest (javax.servlet.http.HttpServletRequest)13 HashMap (java.util.HashMap)11 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 Map (java.util.Map)7 IOException (java.io.IOException)6 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 File (java.io.File)4 Method (java.lang.reflect.Method)4 Locale (java.util.Locale)4 FacesException (javax.faces.FacesException)4 Flash (javax.faces.context.Flash)4 InvocationContext (javax.interceptor.InvocationContext)4 ExceptionQueuedEvent (javax.faces.event.ExceptionQueuedEvent)3 ExceptionQueuedEventContext (javax.faces.event.ExceptionQueuedEventContext)3 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 Date (java.util.Date)2