Search in sources :

Example 1 with Response

use of org.apache.catalina.connector.Response in project tomcat by apache.

the class FormAuthenticator method doAuthenticate.

// ------------------------------------------------------ Protected Methods
/**
     * Authenticate the user making this request, based on the specified
     * login configuration.  Return <code>true</code> if any specified
     * constraint has been satisfied, or <code>false</code> if we have
     * created a response challenge already.
     *
     * @param request Request we are processing
     * @param response Response we are creating
     *
     * @exception IOException if an input/output error occurs
     */
@Override
protected boolean doAuthenticate(Request request, HttpServletResponse response) throws IOException {
    if (checkForCachedAuthentication(request, response, true)) {
        return true;
    }
    // References to objects we will need later
    Session session = null;
    Principal principal = null;
    // Have we authenticated this user before but have caching disabled?
    if (!cache) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled()) {
            log.debug("Checking for reauthenticate in session " + session);
        }
        String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE);
        String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE);
        if ((username != null) && (password != null)) {
            if (log.isDebugEnabled()) {
                log.debug("Reauthenticating username '" + username + "'");
            }
            principal = context.getRealm().authenticate(username, password);
            if (principal != null) {
                session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
                if (!matchRequest(request)) {
                    register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password);
                    return true;
                }
            }
            if (log.isDebugEnabled()) {
                log.debug("Reauthentication failed, proceed normally");
            }
        }
    }
    // authentication?  If so, forward the *original* request instead.
    if (matchRequest(request)) {
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled()) {
            log.debug("Restore request from session '" + session.getIdInternal() + "'");
        }
        principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE);
        register(request, response, principal, HttpServletRequest.FORM_AUTH, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (String) session.getNote(Constants.SESS_PASSWORD_NOTE));
        // and password in the session, so remove them
        if (cache) {
            session.removeNote(Constants.SESS_USERNAME_NOTE);
            session.removeNote(Constants.SESS_PASSWORD_NOTE);
        }
        if (restoreRequest(request, session)) {
            if (log.isDebugEnabled()) {
                log.debug("Proceed to restored request");
            }
            return true;
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Restore of original request failed");
            }
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return false;
        }
    }
    // Acquire references to objects we will need to evaluate
    String contextPath = request.getContextPath();
    String requestURI = request.getDecodedRequestURI();
    // Is this the action request from the login page?
    boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION);
    LoginConfig config = context.getLoginConfig();
    // No -- Save this request and redirect to the form login page
    if (!loginAction) {
        // may not go to the correct web application
        if (request.getServletPath().length() == 0 && request.getPathInfo() == null) {
            StringBuilder location = new StringBuilder(requestURI);
            location.append('/');
            if (request.getQueryString() != null) {
                location.append('?');
                location.append(request.getQueryString());
            }
            response.sendRedirect(response.encodeRedirectURL(location.toString()));
            return false;
        }
        session = request.getSessionInternal(true);
        if (log.isDebugEnabled()) {
            log.debug("Save request in session '" + session.getIdInternal() + "'");
        }
        try {
            saveRequest(request, session);
        } catch (IOException ioe) {
            log.debug("Request body too big to save during authentication");
            response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig"));
            return false;
        }
        forwardToLoginPage(request, response, config);
        return false;
    }
    // Yes -- Acknowledge the request, validate the specified credentials
    // and redirect to the error page if they are not correct
    request.getResponse().sendAcknowledgement();
    Realm realm = context.getRealm();
    if (characterEncoding != null) {
        request.setCharacterEncoding(characterEncoding);
    }
    String username = request.getParameter(Constants.FORM_USERNAME);
    String password = request.getParameter(Constants.FORM_PASSWORD);
    if (log.isDebugEnabled()) {
        log.debug("Authenticating username '" + username + "'");
    }
    principal = realm.authenticate(username, password);
    if (principal == null) {
        forwardToErrorPage(request, response, config);
        return false;
    }
    if (log.isDebugEnabled()) {
        log.debug("Authentication of '" + username + "' was successful");
    }
    if (session == null) {
        session = request.getSessionInternal(false);
    }
    if (session == null) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug("User took so long to log on the session expired");
        }
        if (landingPage == null) {
            response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired"));
        } else {
            // Make the authenticator think the user originally requested
            // the landing page
            String uri = request.getContextPath() + landingPage;
            SavedRequest saved = new SavedRequest();
            saved.setMethod("GET");
            saved.setRequestURI(uri);
            saved.setDecodedRequestURI(uri);
            request.getSessionInternal(true).setNote(Constants.FORM_REQUEST_NOTE, saved);
            response.sendRedirect(response.encodeRedirectURL(uri));
        }
        return false;
    }
    // Save the authenticated Principal in our session
    session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal);
    // Save the username and password as well
    session.setNote(Constants.SESS_USERNAME_NOTE, username);
    session.setNote(Constants.SESS_PASSWORD_NOTE, password);
    // Redirect the user to the original request URI (which will cause
    // the original request to be restored)
    requestURI = savedRequestURL(session);
    if (log.isDebugEnabled()) {
        log.debug("Redirecting to original '" + requestURI + "'");
    }
    if (requestURI == null) {
        if (landingPage == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin"));
        } else {
            // Make the authenticator think the user originally requested
            // the landing page
            String uri = request.getContextPath() + landingPage;
            SavedRequest saved = new SavedRequest();
            saved.setMethod("GET");
            saved.setRequestURI(uri);
            saved.setDecodedRequestURI(uri);
            session.setNote(Constants.FORM_REQUEST_NOTE, saved);
            response.sendRedirect(response.encodeRedirectURL(uri));
        }
    } else {
        // Until the Servlet API allows specifying the type of redirect to
        // use.
        Response internalResponse = request.getResponse();
        String location = response.encodeRedirectURL(requestURI);
        if ("HTTP/1.1".equals(request.getProtocol())) {
            internalResponse.sendRedirect(location, HttpServletResponse.SC_SEE_OTHER);
        } else {
            internalResponse.sendRedirect(location, HttpServletResponse.SC_FOUND);
        }
    }
    return false;
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) LoginConfig(org.apache.tomcat.util.descriptor.web.LoginConfig) IOException(java.io.IOException) Realm(org.apache.catalina.Realm) Principal(java.security.Principal) Session(org.apache.catalina.Session)

Example 2 with Response

use of org.apache.catalina.connector.Response in project tomcat by apache.

the class AuthenticatorBase method authenticate.

@Override
public boolean authenticate(Request request, HttpServletResponse httpResponse) throws IOException {
    AuthConfigProvider jaspicProvider = getJaspicProvider();
    if (jaspicProvider == null) {
        return doAuthenticate(request, httpResponse);
    } else {
        Response response = request.getResponse();
        JaspicState jaspicState = getJaspicState(jaspicProvider, request, response, true);
        if (jaspicState == null) {
            return false;
        }
        boolean result = authenticateJaspic(request, response, jaspicState, true);
        secureResponseJspic(request, response, jaspicState);
        return result;
    }
}
Also used : HttpServletResponse(javax.servlet.http.HttpServletResponse) Response(org.apache.catalina.connector.Response) AuthConfigProvider(javax.security.auth.message.config.AuthConfigProvider)

Example 3 with Response

use of org.apache.catalina.connector.Response in project tomcat by apache.

the class TestRequestFilterValve method oneTest.

private void oneTest(String allow, String deny, boolean denyStatus, boolean addConnectorPort, boolean auth, String property, String type, boolean allowed) {
    // PREPARE
    RequestFilterValve valve = null;
    Connector connector = new Connector();
    Context context = new StandardContext();
    Request request = new Request(connector);
    Response response = new MockResponse();
    StringBuilder msg = new StringBuilder();
    int expected = allowed ? OK : FORBIDDEN;
    connector.setPort(PORT);
    request.getMappingData().context = context;
    request.setCoyoteRequest(new org.apache.coyote.Request());
    Assert.assertNotNull("Invalid test with null type", type);
    if (property != null) {
        if (type.equals("Addr")) {
            valve = new RemoteAddrValve();
            request.setRemoteAddr(property);
            msg.append(" ip='" + property + "'");
        } else if (type.equals("Host")) {
            valve = new RemoteHostValve();
            request.setRemoteHost(property);
            msg.append(" host='" + property + "'");
        }
    }
    Assert.assertNotNull("Invalid test type" + type, valve);
    valve.setNext(new TerminatingValve());
    if (allow != null) {
        valve.setAllow(allow);
        msg.append(" allow='" + allow + "'");
    }
    if (deny != null) {
        valve.setDeny(deny);
        msg.append(" deny='" + deny + "'");
    }
    if (denyStatus) {
        valve.setDenyStatus(CUSTOM);
        msg.append(" denyStatus='" + CUSTOM + "'");
        if (!allowed) {
            expected = CUSTOM;
        }
    }
    if (addConnectorPort) {
        if (valve instanceof RemoteAddrValve) {
            ((RemoteAddrValve) valve).setAddConnectorPort(true);
        } else if (valve instanceof RemoteHostValve) {
            ((RemoteHostValve) valve).setAddConnectorPort(true);
        } else {
            fail("Can only set 'addConnectorPort' for RemoteAddrValve and RemoteHostValve");
        }
        msg.append(" addConnectorPort='true'");
    }
    if (auth) {
        context.setPreemptiveAuthentication(true);
        valve.setInvalidAuthenticationWhenDeny(true);
        msg.append(" auth='true'");
    }
    // TEST
    try {
        valve.invoke(request, response);
    } catch (IOException ex) {
    //Ignore
    } catch (ServletException ex) {
    //Ignore
    }
    // VERIFY
    if (!allowed && auth) {
        assertEquals(msg.toString(), OK, response.getStatus());
        assertEquals(msg.toString(), "invalid", request.getHeader("authorization"));
    } else {
        assertEquals(msg.toString(), expected, response.getStatus());
    }
}
Also used : Context(org.apache.catalina.Context) StandardContext(org.apache.catalina.core.StandardContext) Connector(org.apache.catalina.connector.Connector) Request(org.apache.catalina.connector.Request) IOException(java.io.IOException) Response(org.apache.catalina.connector.Response) ServletException(javax.servlet.ServletException) StandardContext(org.apache.catalina.core.StandardContext)

Example 4 with Response

use of org.apache.catalina.connector.Response in project tomcat by apache.

the class TestRealmBase method testHttpConstraint.

/*
     * This test case covers the special case in section 13.4.1 of the Servlet
     * 3.1 specification for {@link javax.servlet.annotation.HttpConstraint}.
     */
@Test
public void testHttpConstraint() throws IOException {
    // Get the annotation from the test case
    Class<TesterServletSecurity01> clazz = TesterServletSecurity01.class;
    ServletSecurity servletSecurity = clazz.getAnnotation(ServletSecurity.class);
    // Convert the annotation into constraints
    ServletSecurityElement servletSecurityElement = new ServletSecurityElement(servletSecurity);
    SecurityConstraint[] constraints = SecurityConstraint.createConstraints(servletSecurityElement, "/*");
    // Create a separate constraint that covers DELETE
    SecurityConstraint deleteConstraint = new SecurityConstraint();
    deleteConstraint.addAuthRole(ROLE1);
    SecurityCollection deleteCollection = new SecurityCollection();
    deleteCollection.addMethod("DELETE");
    deleteCollection.addPatternDecoded("/*");
    deleteConstraint.addCollection(deleteCollection);
    TesterMapRealm mapRealm = new TesterMapRealm();
    // Set up the mock request and response
    TesterRequest request = new TesterRequest();
    Response response = new TesterResponse();
    Context context = request.getContext();
    context.addSecurityRole(ROLE1);
    context.addSecurityRole(ROLE2);
    request.getMappingData().context = context;
    // Create the principals
    List<String> userRoles1 = new ArrayList<>();
    userRoles1.add(ROLE1);
    GenericPrincipal gp1 = new GenericPrincipal(USER1, PWD, userRoles1);
    List<String> userRoles2 = new ArrayList<>();
    userRoles2.add(ROLE2);
    GenericPrincipal gp2 = new GenericPrincipal(USER2, PWD, userRoles2);
    List<String> userRoles99 = new ArrayList<>();
    GenericPrincipal gp99 = new GenericPrincipal(USER99, PWD, userRoles99);
    // Add the constraints to the context
    for (SecurityConstraint constraint : constraints) {
        context.addConstraint(constraint);
    }
    context.addConstraint(deleteConstraint);
    // All users should be able to perform a GET
    request.setMethod("GET");
    SecurityConstraint[] constraintsGet = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    request.setUserPrincipal(gp99);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsGet, null));
    // Only user1 should be able to perform a POST as only that user has
    // role1.
    request.setMethod("POST");
    SecurityConstraint[] constraintsPost = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp2);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPost, null));
    // Only users with application roles (role1 or role2 so user1 or user2)
    // should be able to perform a PUT.
    request.setMethod("PUT");
    SecurityConstraint[] constraintsPut = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsPut, null));
    // Any authenticated user should be able to perform a TRACE.
    request.setMethod("TRACE");
    SecurityConstraint[] constraintsTrace = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp2);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    request.setUserPrincipal(gp99);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsTrace, null));
    // Only user1 should be able to perform a DELETE as only that user has
    // role1.
    request.setMethod("DELETE");
    SecurityConstraint[] constraintsDelete = mapRealm.findSecurityConstraints(request, context);
    request.setUserPrincipal(null);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp1);
    Assert.assertTrue(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp2);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
    request.setUserPrincipal(gp99);
    Assert.assertFalse(mapRealm.hasResourcePermission(request, response, constraintsDelete, null));
}
Also used : Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) ServletSecurity(javax.servlet.annotation.ServletSecurity) ArrayList(java.util.ArrayList) TesterResponse(org.apache.tomcat.unittest.TesterResponse) ServletSecurityElement(javax.servlet.ServletSecurityElement) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) TesterResponse(org.apache.tomcat.unittest.TesterResponse) Response(org.apache.catalina.connector.Response) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) TesterRequest(org.apache.tomcat.unittest.TesterRequest) SecurityCollection(org.apache.tomcat.util.descriptor.web.SecurityCollection) Test(org.junit.Test)

Example 5 with Response

use of org.apache.catalina.connector.Response in project tomcat by apache.

the class TestRealmBase method doRoleTest.

private void doRoleTest(List<String> userRoles, List<String> constraintOneRoles, List<String> constraintTwoRoles, List<String> applicationRoles, boolean expected) throws IOException {
    TesterMapRealm mapRealm = new TesterMapRealm();
    // Configure the security constraints for the resource
    SecurityConstraint constraintOne = new SecurityConstraint();
    if (constraintOneRoles != null) {
        constraintOne.setAuthConstraint(true);
        for (String constraintRole : constraintOneRoles) {
            constraintOne.addAuthRole(constraintRole);
            if (applicationRoles.contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS)) {
                constraintOne.treatAllAuthenticatedUsersAsApplicationRole();
            }
        }
    }
    SecurityConstraint constraintTwo = new SecurityConstraint();
    if (constraintTwoRoles != null) {
        constraintTwo.setAuthConstraint(true);
        for (String constraintRole : constraintTwoRoles) {
            constraintTwo.addAuthRole(constraintRole);
            if (applicationRoles.contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS)) {
                constraintTwo.treatAllAuthenticatedUsersAsApplicationRole();
            }
        }
    }
    SecurityConstraint[] constraints = new SecurityConstraint[] { constraintOne, constraintTwo };
    // Set up the mock request and response
    Request request = new Request(null);
    Response response = new TesterResponse();
    Context context = new TesterContext();
    for (String applicationRole : applicationRoles) {
        context.addSecurityRole(applicationRole);
    }
    request.getMappingData().context = context;
    // Configure the users in the Realm
    if (userRoles != null) {
        GenericPrincipal gp = new GenericPrincipal(USER1, PWD, userRoles);
        request.setUserPrincipal(gp);
    }
    // Check if user meets constraints
    boolean result = mapRealm.hasResourcePermission(request, response, constraints, null);
    Assert.assertEquals(Boolean.valueOf(expected), Boolean.valueOf(result));
}
Also used : TesterResponse(org.apache.tomcat.unittest.TesterResponse) Response(org.apache.catalina.connector.Response) Context(org.apache.catalina.Context) TesterContext(org.apache.tomcat.unittest.TesterContext) TesterMapRealm(org.apache.catalina.startup.TesterMapRealm) Request(org.apache.catalina.connector.Request) TesterRequest(org.apache.tomcat.unittest.TesterRequest) TesterResponse(org.apache.tomcat.unittest.TesterResponse) TesterContext(org.apache.tomcat.unittest.TesterContext) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Aggregations

Response (org.apache.catalina.connector.Response)8 HttpServletResponse (javax.servlet.http.HttpServletResponse)5 Context (org.apache.catalina.Context)4 IOException (java.io.IOException)3 ServletResponse (javax.servlet.ServletResponse)3 Request (org.apache.catalina.connector.Request)3 TesterContext (org.apache.tomcat.unittest.TesterContext)3 ServletException (javax.servlet.ServletException)2 ServletResponseWrapper (javax.servlet.ServletResponseWrapper)2 TesterMapRealm (org.apache.catalina.startup.TesterMapRealm)2 TesterRequest (org.apache.tomcat.unittest.TesterRequest)2 TesterResponse (org.apache.tomcat.unittest.TesterResponse)2 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)2 Test (org.junit.Test)2 URISyntaxException (java.net.URISyntaxException)1 Principal (java.security.Principal)1 ArrayList (java.util.ArrayList)1 AuthConfigProvider (javax.security.auth.message.config.AuthConfigProvider)1 AsyncContext (javax.servlet.AsyncContext)1 AsyncEvent (javax.servlet.AsyncEvent)1