Package io.undertow.servlet.handlers

Examples of io.undertow.servlet.handlers.ServletRequestContext


    }


    @Override
    public void include(final ServletRequest request, final ServletResponse response) throws ServletException, IOException {
        final ServletRequestContext servletRequestContext = SecurityActions.requireCurrentServletRequestContext();
        final HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
        final HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
        ThreadSetupAction.Handle handle = null;
        ServletContextImpl oldServletContext = null;
        HttpSessionImpl oldSession = null;
        if (servletRequestContext.getCurrentServletContext() != this.servletContext) {
            //cross context request, we need to run the thread setup actions
            oldServletContext = servletRequestContext.getCurrentServletContext();
            oldSession = servletRequestContext.getSession();
            servletRequestContext.setSession(null);
            handle = this.servletContext.getDeployment().getThreadSetupAction().setup(servletRequestContext.getExchange());
            servletRequestContext.setCurrentServletContext(this.servletContext);
        }

        try {
            if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
                if (servletRequestContext.getOriginalRequest() != request) {
                    if (!(request instanceof ServletRequestWrapper)) {
                        throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request);
                    }
                }
                if (servletRequestContext.getOriginalResponse() != response) {
                    if (!(response instanceof ServletResponseWrapper)) {
                        throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response);
                    }
                }
            }

            final ServletRequest oldRequest = servletRequestContext.getServletRequest();
            final ServletResponse oldResponse = servletRequestContext.getServletResponse();

            Object requestUri = null;
            Object contextPath = null;
            Object servletPath = null;
            Object pathInfo = null;
            Object queryString = null;
            Map<String, Deque<String>> queryParameters = requestImpl.getQueryParameters();

            if (!named) {
                requestUri = request.getAttribute(INCLUDE_REQUEST_URI);
                contextPath = request.getAttribute(INCLUDE_CONTEXT_PATH);
                servletPath = request.getAttribute(INCLUDE_SERVLET_PATH);
                pathInfo = request.getAttribute(INCLUDE_PATH_INFO);
                queryString = request.getAttribute(INCLUDE_QUERY_STRING);

                int qsPos = path.indexOf("?");
                String newServletPath = path;
                if (qsPos != -1) {
                    String newQueryString = newServletPath.substring(qsPos + 1);
                    newServletPath = newServletPath.substring(0, qsPos);

                    Map<String, Deque<String>> newQueryParameters = QueryParameterUtils.mergeQueryParametersWithNewQueryString(queryParameters, newQueryString);
                    requestImpl.setQueryParameters(newQueryParameters);
                    requestImpl.setAttribute(INCLUDE_QUERY_STRING, newQueryString);
                } else {
                    requestImpl.setAttribute(INCLUDE_QUERY_STRING, "");
                }
                String newRequestUri = servletContext.getContextPath() + newServletPath;

                requestImpl.setAttribute(INCLUDE_REQUEST_URI, newRequestUri);
                requestImpl.setAttribute(INCLUDE_CONTEXT_PATH, servletContext.getContextPath());
                requestImpl.setAttribute(INCLUDE_SERVLET_PATH, pathMatch.getMatched());
                requestImpl.setAttribute(INCLUDE_PATH_INFO, pathMatch.getRemaining());
            }
            boolean inInclude = responseImpl.isInsideInclude();
            responseImpl.setInsideInclude(true);
            DispatcherType oldDispatcherType = servletRequestContext.getDispatcherType();

            ServletContextImpl oldContext = requestImpl.getServletContext();
            try {
                requestImpl.setServletContext(servletContext);
                responseImpl.setServletContext(servletContext);
                try {
                    servletRequestContext.setServletRequest(request);
                    servletRequestContext.setServletResponse(response);
                    servletContext.getDeployment().getServletDispatcher().dispatchToServlet(requestImpl.getExchange(), chain, DispatcherType.INCLUDE);
                } catch (ServletException e) {
                    throw e;
                } catch (IOException e) {
                    throw e;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            } finally {
                responseImpl.setInsideInclude(inInclude);
                requestImpl.setServletContext(oldContext);
                responseImpl.setServletContext(oldContext);

                servletRequestContext.setServletRequest(oldRequest);
                servletRequestContext.setServletResponse(oldResponse);
                servletRequestContext.setDispatcherType(oldDispatcherType);
                if (!named) {
                    requestImpl.setAttribute(INCLUDE_REQUEST_URI, requestUri);
                    requestImpl.setAttribute(INCLUDE_CONTEXT_PATH, contextPath);
                    requestImpl.setAttribute(INCLUDE_SERVLET_PATH, servletPath);
                    requestImpl.setAttribute(INCLUDE_PATH_INFO, pathInfo);
                    requestImpl.setAttribute(INCLUDE_QUERY_STRING, queryString);
                    requestImpl.setQueryParameters(queryParameters);
                }
            }
        } finally {
            if(handle != null) {
                servletRequestContext.setSession(oldSession);
                servletRequestContext.setCurrentServletContext(oldServletContext);
                handle.tearDown();
            }
        }
    }
View Full Code Here


    public void error(final ServletRequest request, final ServletResponse response, final String servletName, final Throwable exception) throws ServletException, IOException {
        error(request, response, servletName, exception, exception.getMessage());
    }

    private void error(final ServletRequest request, final ServletResponse response, final String servletName, final Throwable exception, final String message) throws ServletException, IOException {
        final ServletRequestContext servletRequestContext = SecurityActions.requireCurrentServletRequestContext();
        final HttpServletRequestImpl requestImpl = servletRequestContext.getOriginalRequest();
        final HttpServletResponseImpl responseImpl = servletRequestContext.getOriginalResponse();
        if (!servletContext.getDeployment().getDeploymentInfo().isAllowNonStandardWrappers()) {
            if (servletRequestContext.getOriginalRequest() != request) {
                if (!(request instanceof ServletRequestWrapper)) {
                    throw UndertowServletMessages.MESSAGES.requestWasNotOriginalOrWrapper(request);
                }
            }
            if (servletRequestContext.getOriginalResponse() != response) {
                if (!(response instanceof ServletResponseWrapper)) {
                    throw UndertowServletMessages.MESSAGES.responseWasNotOriginalOrWrapper(response);
                }
            }
        }

        final ServletRequest oldRequest = servletRequestContext.getServletRequest();
        final ServletResponse oldResponse = servletRequestContext.getServletResponse();
        servletRequestContext.setDispatcherType(DispatcherType.ERROR);

        //only update if this is the first forward
        requestImpl.setAttribute(ERROR_REQUEST_URI, requestImpl.getRequestURI());
        requestImpl.setAttribute(ERROR_SERVLET_NAME, servletName);
        if (exception != null) {
            requestImpl.setAttribute(ERROR_EXCEPTION, exception);
            requestImpl.setAttribute(ERROR_EXCEPTION_TYPE, exception.getClass());
        }
        requestImpl.setAttribute(ERROR_MESSAGE, message);
        requestImpl.setAttribute(ERROR_STATUS_CODE, responseImpl.getStatus());

        String newQueryString = "";
        int qsPos = path.indexOf("?");
        String newServletPath = path;
        if (qsPos != -1) {
            newQueryString = newServletPath.substring(qsPos + 1);
            newServletPath = newServletPath.substring(0, qsPos);
        }
        String newRequestUri = servletContext.getContextPath() + newServletPath;

        //todo: a more efficent impl
        Map<String, Deque<String>> newQueryParameters = new HashMap<String, Deque<String>>();
        for (String part : newQueryString.split("&")) {
            String name = part;
            String value = "";
            int equals = part.indexOf('=');
            if (equals != -1) {
                name = part.substring(0, equals);
                value = part.substring(equals + 1);
            }
            Deque<String> queue = newQueryParameters.get(name);
            if (queue == null) {
                newQueryParameters.put(name, queue = new ArrayDeque<String>(1));
            }
            queue.add(value);
        }
        requestImpl.setQueryParameters(newQueryParameters);

        requestImpl.getExchange().setRelativePath(newServletPath);
        requestImpl.getExchange().setQueryString(newQueryString);
        requestImpl.getExchange().setRequestPath(newRequestUri);
        requestImpl.getExchange().setRequestURI(newRequestUri);
        requestImpl.getExchange().getAttachment(ServletRequestContext.ATTACHMENT_KEY).setServletPathMatch(pathMatch);
        requestImpl.setServletContext(servletContext);
        responseImpl.setServletContext(servletContext);

        try {
            try {
                servletRequestContext.setServletRequest(request);
                servletRequestContext.setServletResponse(response);
                servletContext.getDeployment().getServletDispatcher().dispatchToPath(requestImpl.getExchange(), pathMatch, DispatcherType.ERROR);
            } catch (ServletException e) {
                throw e;
            } catch (IOException e) {
                throw e;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } finally {
            servletRequestContext.setServletRequest(oldRequest);
            servletRequestContext.setServletResponse(oldResponse);
        }
    }
View Full Code Here

        super(formParserFactory, name, loginPage, errorPage);
    }

    @Override
    protected Integer servePage(final HttpServerExchange exchange, final String location) {
        final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        ServletRequest req = servletRequestContext.getServletRequest();
        ServletResponse resp = servletRequestContext.getServletResponse();
        RequestDispatcher disp = req.getRequestDispatcher(location);
        exchange.setRequestMethod(Methods.GET); //TODO: is this correct?
        try {
            disp.forward(req, resp);
        } catch (ServletException e) {
View Full Code Here

        return null;
    }

    @Override
    protected void storeInitialLocation(final HttpServerExchange exchange) {
        final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, true);
        Session session;
        if (System.getSecurityManager() == null) {
            session = httpSession.getSession();
        } else {
            session = AccessController.doPrivileged(new HttpSessionImpl.UnwrapSessionAction(httpSession));
View Full Code Here

        SavedRequest.trySaveRequest(exchange);
    }

    @Override
    protected void handleRedirectBack(final HttpServerExchange exchange) {
        final ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        HttpServletResponse resp = (HttpServletResponse) servletRequestContext.getServletResponse();
        HttpSessionImpl httpSession = servletRequestContext.getCurrentServletContext().getSession(exchange, false);
        if (httpSession != null) {
            Session session;
            if (System.getSecurityManager() == null) {
                session = httpSession.getSession();
            } else {
View Full Code Here

            }
        };
    }

    public static ServletRequest getActiveRequest() {
        ServletRequestContext current;
        if(System.getSecurityManager() == null) {
            current = ServletRequestContext.current();
        } else {
            current = AccessController.doPrivileged(CURRENT_CONTEXT);
        }
        if(current == null) {
            return null;
        }
        return current.getServletRequest();
    }
View Full Code Here

        return roles;
    }

    @Override
    public boolean canAccessResource(List<SingleConstraintMatch> mappedConstraints, Account account, ServletInfo servletInfo, HttpServletRequest request, Deployment deployment) {
        ServletRequestContext src = ServletRequestContext.current();
        boolean baseDecision = delegate.canAccessResource(mappedConstraints, account, servletInfo, request, deployment);
        boolean authzDecision = false;
        // if the RealmBase check has passed, then we can go to authz framework
        if (baseDecision) {
            SecurityContext sc = SecurityActions.getSecurityContext();
            Subject caller = sc.getUtil().getSubject();
            //if (caller == null) {
            //    caller = getSubjectFromRequestPrincipal(request.getPrincipal());
            //}
            Map<String, Object> contextMap = new HashMap<String, Object>();
            contextMap.put(ResourceKeys.RESOURCE_PERM_CHECK, Boolean.TRUE);
            contextMap.put("securityConstraints", mappedConstraints); //TODO? What should this be?

            AbstractWebAuthorizationHelper helper = null;
            try {
                helper = SecurityHelperFactory.getWebAuthorizationHelper(sc);
            } catch (Exception e) {
                UndertowLogger.ROOT_LOGGER.noAuthorizationHelper(e);
                return false;
            }

            ArrayList<String> roles = new ArrayList<String>();
            if(account != null) {
                roles.addAll(account.getRoles());
            }
            authzDecision = helper.checkResourcePermission(contextMap, request, src.getServletResponse(), caller, PolicyContext.getContextID(),
                    requestURI(src.getExchange()), roles);
        }
        boolean finalDecision = baseDecision && authzDecision && hasUserDataPermission(request, src.getOriginalResponse(), account, mappedConstraints);

        UndertowLogger.ROOT_LOGGER.tracef("hasResourcePermission:RealmBase says: %s ::Authz framework says: %s :final= %s", baseDecision, authzDecision, finalDecision);
        //TODO: audit?

        return finalDecision;
View Full Code Here

        this.configuredAuthMethod = configuredAuthMethod;
    }

    @Override
    public AuthenticationMechanismOutcome authenticate(final HttpServerExchange exchange, final SecurityContext sc) {
        final ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        final JASPIServerAuthenticationManager sam = createJASPIAuthenticationManager();
        final GenericMessageInfo messageInfo = createMessageInfo(exchange, sc);
        final String applicationIdentifier = buildApplicationIdentifier(requestContext);
        final JASPICallbackHandler cbh = new JASPICallbackHandler();

        UndertowLogger.ROOT_LOGGER.debugf("validateRequest for layer [%s] and applicationContextIdentifier [%s]", JASPI_HTTP_SERVLET_LAYER, applicationIdentifier);

        Account cachedAccount = null;
        final JASPICSecurityContext jaspicSecurityContext = (JASPICSecurityContext) exchange.getSecurityContext();
        final AuthenticatedSessionManager sessionManager = exchange.getAttachment(AuthenticatedSessionManager.ATTACHMENT_KEY);

        if (sessionManager != null) {
            AuthenticatedSessionManager.AuthenticatedSession authSession = sessionManager.lookupSession(exchange);
            cachedAccount = authSession.getAccount();
            // if there is a cached account we set it in the security context so that the principal is available to
            // SAM modules via request.getUserPrincipal().
            if (cachedAccount !=  null) {
                jaspicSecurityContext.setCachedAuthenticatedAccount(cachedAccount);
            }
        }

        AuthenticationMechanismOutcome outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
        Account authenticatedAccount = null;

        boolean isValid = sam.isValid(messageInfo, new Subject(), JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, cbh);
        jaspicSecurityContext.setCachedAuthenticatedAccount(null);

        if (isValid) {
            // The CBH filled in the JBOSS SecurityContext, we need to create an Undertow account based on that
            org.jboss.security.SecurityContext jbossSct = SecurityActions.getSecurityContext();
            authenticatedAccount = createAccount(cachedAccount, jbossSct);
        }

        // authType resolution (check message info first, then check for the configured auth method, then use mech-specific name).
        String authType = (String) messageInfo.getMap().get(JASPI_AUTH_TYPE);
        if (authType == null)
            authType = this.configuredAuthMethod != null ? this.configuredAuthMethod : MECHANISM_NAME;

        if (isValid && authenticatedAccount != null) {
            outcome = AuthenticationMechanismOutcome.AUTHENTICATED;

            Object registerObj = messageInfo.getMap().get(JASPI_REGISTER_SESSION);
            boolean cache = false;
            if(registerObj != null && (registerObj instanceof String)) {
                cache = Boolean.valueOf((String)registerObj);
            }
            sc.authenticationComplete(authenticatedAccount, authType, cache);
        } else if (isValid && authenticatedAccount == null && !isMandatory(requestContext)) {
            outcome = AuthenticationMechanismOutcome.NOT_ATTEMPTED;
        } else {
            outcome = AuthenticationMechanismOutcome.NOT_AUTHENTICATED;
            sc.authenticationFailed("JASPIC authentication failed.", authType);
        }

        // A SAM can wrap the HTTP request/response objects - update the servlet request context with the values found in the message info.
        ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
        servletRequestContext.setServletRequest((HttpServletRequest) messageInfo.getRequestMessage());
        servletRequestContext.setServletResponse((HttpServletResponse) messageInfo.getResponseMessage());

        secureResponse(exchange, sam, messageInfo, cbh);

        return outcome;
View Full Code Here

        ServletRequest servletRequest = attachment.getServletRequest();
        return servletRequest.getServletContext().getVirtualServerName() + " " + servletRequest.getServletContext().getContextPath();
    }

    private GenericMessageInfo createMessageInfo(final HttpServerExchange exchange, final SecurityContext securityContext) {
        ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);

        GenericMessageInfo messageInfo = new GenericMessageInfo();

        messageInfo.setRequestMessage(servletRequestContext.getServletRequest());
        messageInfo.setResponseMessage(servletRequestContext.getServletResponse());

        messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory", isMandatory(servletRequestContext).toString());

        // additional context data, useful to provide access to Undertow resources during the modules processing
        messageInfo.getMap().put(SECURITY_CONTEXT_ATTACHMENT_KEY, securityContext);
View Full Code Here

        exchange.putAttachment(ALREADY_WRAPPED, true);
        // we add a response wrapper to properly invoke the secureResponse, after processing the destination
        exchange.addResponseWrapper(new ConduitWrapper<StreamSinkConduit>() {
            @Override
            public StreamSinkConduit wrap(final ConduitFactory<StreamSinkConduit> factory, final HttpServerExchange exchange) {
                ServletRequestContext requestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                String applicationIdentifier = buildApplicationIdentifier(requestContext);

                if (!wasAuthExceptionThrown(exchange)) {
                    UndertowLogger.ROOT_LOGGER.debugf("secureResponse for layer [%s] and applicationContextIdentifier [%s].", JASPI_HTTP_SERVLET_LAYER, applicationIdentifier);
                    sam.secureResponse(messageInfo, new Subject(), JASPI_HTTP_SERVLET_LAYER, applicationIdentifier, cbh);

                    // A SAM can unwrap the HTTP request/response objects - update the servlet request context with the values found in the message info.
                    ServletRequestContext servletRequestContext = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                    servletRequestContext.setServletRequest((HttpServletRequest) messageInfo.getRequestMessage());
                    servletRequestContext.setServletResponse((HttpServletResponse) messageInfo.getResponseMessage());
                }
                return factory.create();
            }
        });
    }
View Full Code Here

TOP

Related Classes of io.undertow.servlet.handlers.ServletRequestContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.