Search in sources :

Example 26 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project spring-security by spring-projects.

the class AccessDeniedHandlerImpl method handle.

// ~ Methods
// ========================================================================================================
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (!response.isCommitted()) {
        if (errorPage != null) {
            // Put exception into request scope (perhaps of use to a view)
            request.setAttribute(WebAttributes.ACCESS_DENIED_403, accessDeniedException);
            // Set the 403 status code.
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            // forward to error page.
            RequestDispatcher dispatcher = request.getRequestDispatcher(errorPage);
            dispatcher.forward(request, response);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, accessDeniedException.getMessage());
        }
    }
}
Also used : RequestDispatcher(javax.servlet.RequestDispatcher)

Example 27 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project blade by biezhi.

the class FormAuthenticator method validateRequest.

/* ------------------------------------------------------------ */
@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    Request base_request = Request.getBaseRequest(request);
    Response base_response = base_request.getResponse();
    String uri = request.getRequestURI();
    if (uri == null)
        uri = URIUtil.SLASH;
    mandatory |= isJSecurityCheck(uri);
    if (!mandatory)
        return new DeferredAuthentication(this);
    if (isLoginOrErrorPage(URIUtil.addPaths(request.getServletPath(), request.getPathInfo())) && !DeferredAuthentication.isDeferred(response))
        return new DeferredAuthentication(this);
    HttpSession session = request.getSession(true);
    try {
        // Handle a request for authentication.
        if (isJSecurityCheck(uri)) {
            final String username = request.getParameter(__J_USERNAME);
            final String password = request.getParameter(__J_PASSWORD);
            UserIdentity user = login(username, password, request);
            LOG.debug("jsecuritycheck {} {}", username, user);
            session = request.getSession(true);
            if (user != null) {
                // Redirect to original request
                String nuri;
                FormAuthentication form_auth;
                synchronized (session) {
                    nuri = (String) session.getAttribute(__J_URI);
                    if (nuri == null || nuri.length() == 0) {
                        nuri = request.getContextPath();
                        if (nuri.length() == 0)
                            nuri = URIUtil.SLASH;
                    }
                    form_auth = new FormAuthentication(getAuthMethod(), user);
                }
                LOG.debug("authenticated {}->{}", form_auth, nuri);
                response.setContentLength(0);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(nuri));
                return form_auth;
            }
            // not authenticated
            if (LOG.isDebugEnabled())
                LOG.debug("Form authentication FAILED for " + StringUtil.printable(username));
            if (_formErrorPage == null) {
                LOG.debug("auth failed {}->403", username);
                if (response != null)
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else if (_dispatch) {
                LOG.debug("auth failed {}=={}", username, _formErrorPage);
                RequestDispatcher dispatcher = request.getRequestDispatcher(_formErrorPage);
                response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
                response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
                dispatcher.forward(new FormRequest(request), new FormResponse(response));
            } else {
                LOG.debug("auth failed {}->{}", username, _formErrorPage);
                int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
                base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formErrorPage)));
            }
            return Authentication.SEND_FAILURE;
        }
        // Look for cached authentication
        Authentication authentication = (Authentication) session.getAttribute(SessionAuthentication.__J_AUTHENTICATED);
        if (authentication != null) {
            // Has authentication been revoked?
            if (authentication instanceof User && _loginService != null && !_loginService.validate(((User) authentication).getUserIdentity())) {
                LOG.debug("auth revoked {}", authentication);
                session.removeAttribute(SessionAuthentication.__J_AUTHENTICATED);
            } else {
                synchronized (session) {
                    String j_uri = (String) session.getAttribute(__J_URI);
                    if (j_uri != null) {
                        //check if the request is for the same url as the original and restore
                        //params if it was a post
                        LOG.debug("auth retry {}->{}", authentication, j_uri);
                        StringBuffer buf = request.getRequestURL();
                        if (request.getQueryString() != null)
                            buf.append("?").append(request.getQueryString());
                        if (j_uri.equals(buf.toString())) {
                            MultiMap<String> j_post = (MultiMap<String>) session.getAttribute(__J_POST);
                            if (j_post != null) {
                                LOG.debug("auth rePOST {}->{}", authentication, j_uri);
                                base_request.setContentParameters(j_post);
                            }
                            session.removeAttribute(__J_URI);
                            session.removeAttribute(__J_METHOD);
                            session.removeAttribute(__J_POST);
                        }
                    }
                }
                LOG.debug("auth {}", authentication);
                return authentication;
            }
        }
        // if we can't send challenge
        if (DeferredAuthentication.isDeferred(response)) {
            LOG.debug("auth deferred {}", session.getId());
            return Authentication.UNAUTHENTICATED;
        }
        // remember the current URI
        synchronized (session) {
            // But only if it is not set already, or we save every uri that leads to a login form redirect
            if (session.getAttribute(__J_URI) == null || _alwaysSaveUri) {
                StringBuffer buf = request.getRequestURL();
                if (request.getQueryString() != null)
                    buf.append("?").append(request.getQueryString());
                session.setAttribute(__J_URI, buf.toString());
                session.setAttribute(__J_METHOD, request.getMethod());
                if (MimeTypes.Type.FORM_ENCODED.is(req.getContentType()) && HttpMethod.POST.is(request.getMethod())) {
                    MultiMap<String> formParameters = new MultiMap<>();
                    base_request.extractFormParameters(formParameters);
                    session.setAttribute(__J_POST, formParameters);
                }
            }
        }
        // send the the challenge
        if (_dispatch) {
            LOG.debug("challenge {}=={}", session.getId(), _formLoginPage);
            RequestDispatcher dispatcher = request.getRequestDispatcher(_formLoginPage);
            response.setHeader(HttpHeader.CACHE_CONTROL.asString(), HttpHeaderValue.NO_CACHE.asString());
            response.setDateHeader(HttpHeader.EXPIRES.asString(), 1);
            dispatcher.forward(new FormRequest(request), new FormResponse(response));
        } else {
            LOG.debug("challenge {}->{}", session.getId(), _formLoginPage);
            int redirectCode = (base_request.getHttpVersion().getVersion() < HttpVersion.HTTP_1_1.getVersion() ? HttpServletResponse.SC_MOVED_TEMPORARILY : HttpServletResponse.SC_SEE_OTHER);
            base_response.sendRedirect(redirectCode, response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(), _formLoginPage)));
        }
        return Authentication.SEND_CONTINUE;
    } catch (IOException | ServletException e) {
        throw new ServerAuthException(e);
    }
}
Also used : User(org.eclipse.jetty.server.Authentication.User) HttpSession(javax.servlet.http.HttpSession) UserIdentity(org.eclipse.jetty.server.UserIdentity) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) Constraint(org.eclipse.jetty.util.security.Constraint) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Response(org.eclipse.jetty.server.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ServletResponse(javax.servlet.ServletResponse) ServletException(javax.servlet.ServletException) MultiMap(org.eclipse.jetty.util.MultiMap) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication)

Example 28 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project guice by google.

the class ServletPipelineRequestDispatcherTest method forwardToManagedServletFailureOnCommittedBuffer.

public final void forwardToManagedServletFailureOnCommittedBuffer() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    final Injector injector = createMock(Injector.class);
    final Binding binding = createMock(Binding.class);
    final HttpServletRequest mockRequest = createMock(HttpServletRequest.class);
    final HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
    expect(mockResponse.isCommitted()).andReturn(true);
    final HttpServlet mockServlet = new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            final Object o = request.getAttribute(A_KEY);
            assertEquals("Wrong attrib returned - " + o, A_VALUE, o);
        }
    };
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    expect(injector.getInstance(Key.get(HttpServlet.class))).andReturn(mockServlet);
    final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
    Binding<ServletDefinition> mockBinding = createMock(Binding.class);
    expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral()))).andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
    Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
    expect(mockBinding.getProvider()).andReturn(bindingProvider);
    replay(injector, binding, mockRequest, mockResponse, mockBinding);
    // Have to init the Servlet before we can dispatch to it.
    servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
    final RequestDispatcher dispatcher = new ManagedServletPipeline(injector).getRequestDispatcher(pattern);
    assertNotNull(dispatcher);
    try {
        dispatcher.forward(mockRequest, mockResponse);
    } finally {
        verify(injector, mockRequest, mockResponse, mockBinding);
    }
}
Also used : Binding(com.google.inject.Binding) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Injector(com.google.inject.Injector) EasyMock.anyObject(org.easymock.EasyMock.anyObject)

Example 29 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project guice by google.

the class ServletPipelineRequestDispatcherTest method testIncludeManagedServlet.

public final void testIncludeManagedServlet() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    final Injector injector = createMock(Injector.class);
    final Binding binding = createMock(Binding.class);
    final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
    expect(requestMock.getAttribute(A_KEY)).andReturn(A_VALUE);
    requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
    requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);
    final boolean[] run = new boolean[1];
    final HttpServlet mockServlet = new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            run[0] = true;
            final Object o = request.getAttribute(A_KEY);
            assertEquals("Wrong attrib returned - " + o, A_VALUE, o);
        }
    };
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    expect(injector.getInstance(HTTP_SERLVET_KEY)).andReturn(mockServlet);
    final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
    Binding<ServletDefinition> mockBinding = createMock(Binding.class);
    expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral()))).andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
    Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
    expect(mockBinding.getProvider()).andReturn(bindingProvider);
    replay(injector, binding, requestMock, mockBinding);
    // Have to init the Servlet before we can dispatch to it.
    servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
    final RequestDispatcher dispatcher = new ManagedServletPipeline(injector).getRequestDispatcher(pattern);
    assertNotNull(dispatcher);
    dispatcher.include(requestMock, createMock(HttpServletResponse.class));
    assertTrue("Include did not dispatch to our servlet!", run[0]);
    verify(injector, requestMock, mockBinding);
}
Also used : Binding(com.google.inject.Binding) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Injector(com.google.inject.Injector) EasyMock.anyObject(org.easymock.EasyMock.anyObject)

Example 30 with RequestDispatcher

use of javax.servlet.RequestDispatcher in project guice by google.

the class ServletPipelineRequestDispatcherTest method testForwardToManagedServlet.

public final void testForwardToManagedServlet() throws IOException, ServletException {
    String pattern = "blah.html";
    final ServletDefinition servletDefinition = new ServletDefinition(Key.get(HttpServlet.class), UriPatternType.get(UriPatternType.SERVLET, pattern), new HashMap<String, String>(), null);
    final Injector injector = createMock(Injector.class);
    final Binding binding = createMock(Binding.class);
    final HttpServletRequest requestMock = createMock(HttpServletRequest.class);
    final HttpServletResponse mockResponse = createMock(HttpServletResponse.class);
    expect(requestMock.getAttribute(A_KEY)).andReturn(A_VALUE);
    requestMock.setAttribute(REQUEST_DISPATCHER_REQUEST, true);
    requestMock.removeAttribute(REQUEST_DISPATCHER_REQUEST);
    expect(mockResponse.isCommitted()).andReturn(false);
    mockResponse.resetBuffer();
    expectLastCall().once();
    final List<String> paths = new ArrayList<String>();
    final HttpServlet mockServlet = new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse httpServletResponse) throws ServletException, IOException {
            paths.add(request.getRequestURI());
            final Object o = request.getAttribute(A_KEY);
            assertEquals("Wrong attrib returned - " + o, A_VALUE, o);
        }
    };
    expect(binding.acceptScopingVisitor((BindingScopingVisitor) anyObject())).andReturn(true);
    expect(injector.getBinding(Key.get(HttpServlet.class))).andReturn(binding);
    expect(injector.getInstance(HTTP_SERLVET_KEY)).andReturn(mockServlet);
    final Key<ServletDefinition> servetDefsKey = Key.get(TypeLiteral.get(ServletDefinition.class));
    Binding<ServletDefinition> mockBinding = createMock(Binding.class);
    expect(injector.findBindingsByType(eq(servetDefsKey.getTypeLiteral()))).andReturn(ImmutableList.<Binding<ServletDefinition>>of(mockBinding));
    Provider<ServletDefinition> bindingProvider = Providers.of(servletDefinition);
    expect(mockBinding.getProvider()).andReturn(bindingProvider);
    replay(injector, binding, requestMock, mockResponse, mockBinding);
    // Have to init the Servlet before we can dispatch to it.
    servletDefinition.init(null, injector, Sets.<HttpServlet>newIdentityHashSet());
    final RequestDispatcher dispatcher = new ManagedServletPipeline(injector).getRequestDispatcher(pattern);
    assertNotNull(dispatcher);
    dispatcher.forward(requestMock, mockResponse);
    assertTrue("Include did not dispatch to our servlet!", paths.contains(pattern));
    verify(injector, requestMock, mockResponse, mockBinding);
}
Also used : Binding(com.google.inject.Binding) HttpServlet(javax.servlet.http.HttpServlet) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestDispatcher(javax.servlet.RequestDispatcher) HttpServletRequest(javax.servlet.http.HttpServletRequest) Injector(com.google.inject.Injector) EasyMock.anyObject(org.easymock.EasyMock.anyObject)

Aggregations

RequestDispatcher (javax.servlet.RequestDispatcher)203 ServletException (javax.servlet.ServletException)63 HttpSession (javax.servlet.http.HttpSession)58 IOException (java.io.IOException)41 SQLException (java.sql.SQLException)31 HttpServletRequest (javax.servlet.http.HttpServletRequest)30 HttpServletResponse (javax.servlet.http.HttpServletResponse)26 Properties (java.util.Properties)14 ServletContext (javax.servlet.ServletContext)12 Test (org.junit.Test)10 ArrayList (java.util.ArrayList)9 WebUser (org.compiere.util.WebUser)9 ClienteDAO (br.senac.tads3.pi03b.gruposete.dao.ClienteDAO)8 PrintWriter (java.io.PrintWriter)8 ServletResponse (javax.servlet.ServletResponse)8 Cliente (br.senac.tads3.pi03b.gruposete.models.Cliente)7 ServletRequest (javax.servlet.ServletRequest)7 User (org.opennms.netmgt.config.users.User)7 HotelDAO (br.senac.tads3.pi03b.gruposete.dao.HotelDAO)6 VooDAO (br.senac.tads3.pi03b.gruposete.dao.VooDAO)6