Search in sources :

Example 46 with Constraint

use of org.eclipse.jetty.util.security.Constraint in project jetty.project by eclipse.

the class DigestAuthModule method validateRequest.

@Override
public AuthStatus validateRequest(MessageInfo messageInfo, Subject clientSubject, Subject serviceSubject) throws AuthException {
    HttpServletRequest request = (HttpServletRequest) messageInfo.getRequestMessage();
    HttpServletResponse response = (HttpServletResponse) messageInfo.getResponseMessage();
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        boolean stale = false;
        // TODO extract from request
        long timestamp = System.currentTimeMillis();
        if (credentials != null) {
            if (LOG.isDebugEnabled())
                LOG.debug("Credentials: " + credentials);
            QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(credentials, "=, ", true, false);
            final Digest digest = new Digest(request.getMethod());
            String last = null;
            String name = null;
            while (tokenizer.hasMoreTokens()) {
                String tok = tokenizer.nextToken();
                char c = (tok.length() == 1) ? tok.charAt(0) : '\0';
                switch(c) {
                    case '=':
                        name = last;
                        last = tok;
                        break;
                    case ',':
                        name = null;
                    case ' ':
                        break;
                    default:
                        last = tok;
                        if (name != null) {
                            if ("username".equalsIgnoreCase(name))
                                digest.username = tok;
                            else if ("realm".equalsIgnoreCase(name))
                                digest.realm = tok;
                            else if ("nonce".equalsIgnoreCase(name))
                                digest.nonce = tok;
                            else if ("nc".equalsIgnoreCase(name))
                                digest.nc = tok;
                            else if ("cnonce".equalsIgnoreCase(name))
                                digest.cnonce = tok;
                            else if ("qop".equalsIgnoreCase(name))
                                digest.qop = tok;
                            else if ("uri".equalsIgnoreCase(name))
                                digest.uri = tok;
                            else if ("response".equalsIgnoreCase(name))
                                digest.response = tok;
                            break;
                        }
                }
            }
            int n = checkNonce(digest.nonce, timestamp);
            if (n > 0) {
                if (login(clientSubject, digest.username, digest, Constraint.__DIGEST_AUTH, messageInfo)) {
                    return AuthStatus.SUCCESS;
                }
            } else if (n == 0)
                stale = true;
        }
        if (!isMandatory(messageInfo)) {
            return AuthStatus.SUCCESS;
        }
        String domain = request.getContextPath();
        if (domain == null)
            domain = "/";
        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + realmName + "\", domain=\"" + domain + "\", nonce=\"" + newNonce(timestamp) + "\", algorithm=MD5, qop=\"auth\"" + (useStale ? (" stale=" + stale) : ""));
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return AuthStatus.SEND_CONTINUE;
    } catch (IOException e) {
        throw new AuthException(e.getMessage());
    } catch (UnsupportedCallbackException e) {
        throw new AuthException(e.getMessage());
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer) MessageDigest(java.security.MessageDigest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(javax.security.auth.message.AuthException) IOException(java.io.IOException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) Constraint(org.eclipse.jetty.util.security.Constraint)

Example 47 with Constraint

use of org.eclipse.jetty.util.security.Constraint in project jetty.project by eclipse.

the class JaspiTest method before.

@Before
public void before() throws Exception {
    System.setProperty("org.apache.geronimo.jaspic.configurationFile", "src/test/resources/jaspi.xml");
    _server = new Server();
    _connector = new LocalConnector(_server);
    _server.addConnector(_connector);
    ContextHandlerCollection contexts = new ContextHandlerCollection();
    _server.setHandler(contexts);
    TestLoginService loginService = new TestLoginService("TestRealm");
    loginService.putUser("user", new Password("password"), new String[] { "users" });
    loginService.putUser("admin", new Password("secret"), new String[] { "users", "admins" });
    _server.addBean(loginService);
    ContextHandler context = new ContextHandler();
    contexts.addHandler(context);
    context.setContextPath("/ctx");
    JaspiAuthenticatorFactory jaspiAuthFactory = new JaspiAuthenticatorFactory();
    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    context.setHandler(security);
    security.setAuthenticatorFactory(jaspiAuthFactory);
    // security.setAuthenticator(new BasicAuthenticator());
    Constraint constraint = new Constraint("All", "users");
    constraint.setAuthenticate(true);
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/jaspi/*");
    mapping.setConstraint(constraint);
    security.addConstraintMapping(mapping);
    TestHandler handler = new TestHandler();
    security.setHandler(handler);
    ContextHandler other = new ContextHandler();
    contexts.addHandler(other);
    other.setContextPath("/other");
    ConstraintSecurityHandler securityOther = new ConstraintSecurityHandler();
    other.setHandler(securityOther);
    securityOther.setAuthenticatorFactory(jaspiAuthFactory);
    securityOther.addConstraintMapping(mapping);
    securityOther.setHandler(new TestHandler());
    _server.start();
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Server(org.eclipse.jetty.server.Server) Constraint(org.eclipse.jetty.util.security.Constraint) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) LocalConnector(org.eclipse.jetty.server.LocalConnector) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) Password(org.eclipse.jetty.util.security.Password) Before(org.junit.Before)

Example 48 with Constraint

use of org.eclipse.jetty.util.security.Constraint in project jetty.project by eclipse.

the class StandardDescriptorProcessor method visitSecurityConstraint.

public void visitSecurityConstraint(WebAppContext context, Descriptor descriptor, XmlParser.Node node) {
    Constraint scBase = new Constraint();
    //TODO: need to remember origin of the constraints
    try {
        XmlParser.Node auths = node.get("auth-constraint");
        if (auths != null) {
            scBase.setAuthenticate(true);
            // auth-constraint
            Iterator<XmlParser.Node> iter = auths.iterator("role-name");
            List<String> roles = new ArrayList<String>();
            while (iter.hasNext()) {
                String role = iter.next().toString(false, true);
                roles.add(role);
            }
            scBase.setRoles(roles.toArray(new String[roles.size()]));
        }
        XmlParser.Node data = node.get("user-data-constraint");
        if (data != null) {
            data = data.get("transport-guarantee");
            String guarantee = data.toString(false, true).toUpperCase(Locale.ENGLISH);
            if (guarantee == null || guarantee.length() == 0 || "NONE".equals(guarantee))
                scBase.setDataConstraint(Constraint.DC_NONE);
            else if ("INTEGRAL".equals(guarantee))
                scBase.setDataConstraint(Constraint.DC_INTEGRAL);
            else if ("CONFIDENTIAL".equals(guarantee))
                scBase.setDataConstraint(Constraint.DC_CONFIDENTIAL);
            else {
                LOG.warn("Unknown user-data-constraint:" + guarantee);
                scBase.setDataConstraint(Constraint.DC_CONFIDENTIAL);
            }
        }
        Iterator<XmlParser.Node> iter = node.iterator("web-resource-collection");
        while (iter.hasNext()) {
            XmlParser.Node collection = iter.next();
            String name = collection.getString("web-resource-name", false, true);
            Constraint sc = (Constraint) scBase.clone();
            sc.setName(name);
            Iterator<XmlParser.Node> iter2 = collection.iterator("url-pattern");
            while (iter2.hasNext()) {
                String url = iter2.next().toString(false, true);
                url = ServletPathSpec.normalize(url);
                //remember origin so we can process ServletRegistration.Dynamic.setServletSecurityElement() correctly
                context.getMetaData().setOrigin("constraint.url." + url, descriptor);
                Iterator<XmlParser.Node> methods = collection.iterator("http-method");
                Iterator<XmlParser.Node> ommissions = collection.iterator("http-method-omission");
                if (methods.hasNext()) {
                    if (ommissions.hasNext())
                        throw new IllegalStateException("web-resource-collection cannot contain both http-method and http-method-omission");
                    //configure all the http-method elements for each url
                    while (methods.hasNext()) {
                        String method = ((XmlParser.Node) methods.next()).toString(false, true);
                        ConstraintMapping mapping = new ConstraintMapping();
                        mapping.setMethod(method);
                        mapping.setPathSpec(url);
                        mapping.setConstraint(sc);
                        ((ConstraintAware) context.getSecurityHandler()).addConstraintMapping(mapping);
                    }
                } else if (ommissions.hasNext()) {
                    // TODO use the array
                    while (ommissions.hasNext()) {
                        String method = ((XmlParser.Node) ommissions.next()).toString(false, true);
                        ConstraintMapping mapping = new ConstraintMapping();
                        mapping.setMethodOmissions(new String[] { method });
                        mapping.setPathSpec(url);
                        mapping.setConstraint(sc);
                        ((ConstraintAware) context.getSecurityHandler()).addConstraintMapping(mapping);
                    }
                } else {
                    //No http-methods or http-method-omissions specified, the constraint applies to all
                    ConstraintMapping mapping = new ConstraintMapping();
                    mapping.setPathSpec(url);
                    mapping.setConstraint(sc);
                    ((ConstraintAware) context.getSecurityHandler()).addConstraintMapping(mapping);
                }
            }
        }
    } catch (CloneNotSupportedException e) {
        LOG.warn(e);
    }
}
Also used : XmlParser(org.eclipse.jetty.xml.XmlParser) ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) Constraint(org.eclipse.jetty.util.security.Constraint) Node(org.eclipse.jetty.xml.XmlParser.Node) ArrayList(java.util.ArrayList) Node(org.eclipse.jetty.xml.XmlParser.Node) ConstraintAware(org.eclipse.jetty.security.ConstraintAware)

Example 49 with Constraint

use of org.eclipse.jetty.util.security.Constraint in project jetty.project by eclipse.

the class DatabaseLoginServiceTestServer method configureServer.

protected void configureServer() throws Exception {
    _protocol = "http";
    _server.addBean(_loginService);
    ConstraintSecurityHandler security = new ConstraintSecurityHandler();
    _server.setHandler(security);
    Constraint constraint = new Constraint();
    constraint.setName("auth");
    constraint.setAuthenticate(true);
    constraint.setRoles(new String[] { "user", "admin" });
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.setPathSpec("/*");
    mapping.setConstraint(constraint);
    Set<String> knownRoles = new HashSet<>();
    knownRoles.add("user");
    knownRoles.add("admin");
    security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
    security.setAuthenticator(new BasicAuthenticator());
    security.setLoginService(_loginService);
    ServletContextHandler root = new ServletContextHandler();
    root.setContextPath("/");
    root.setResourceBase(_resourceBase);
    ServletHolder servletHolder = new ServletHolder(new DefaultServlet());
    servletHolder.setInitParameter("gzip", "true");
    root.addServlet(servletHolder, "/*");
    _handler = new TestHandler(_resourceBase);
    HandlerCollection handlers = new HandlerCollection();
    handlers.setHandlers(new Handler[] { _handler, root });
    security.setHandler(handlers);
}
Also used : ConstraintMapping(org.eclipse.jetty.security.ConstraintMapping) BasicAuthenticator(org.eclipse.jetty.security.authentication.BasicAuthenticator) Constraint(org.eclipse.jetty.util.security.Constraint) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) ConstraintSecurityHandler(org.eclipse.jetty.security.ConstraintSecurityHandler) HandlerCollection(org.eclipse.jetty.server.handler.HandlerCollection) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) HashSet(java.util.HashSet)

Example 50 with Constraint

use of org.eclipse.jetty.util.security.Constraint in project jetty.project by eclipse.

the class AliasedConstraintTest method startServer.

@BeforeClass
public static void startServer() throws Exception {
    server = new Server();
    connector = new LocalConnector(server);
    server.setConnectors(new Connector[] { connector });
    ContextHandler context = new ContextHandler();
    SessionHandler session = new SessionHandler();
    TestLoginService loginService = new TestLoginService(TEST_REALM);
    loginService.putUser("user0", new Password("password"), new String[] {});
    loginService.putUser("user", new Password("password"), new String[] { "user" });
    loginService.putUser("user2", new Password("password"), new String[] { "user" });
    loginService.putUser("admin", new Password("password"), new String[] { "user", "administrator" });
    loginService.putUser("user3", new Password("password"), new String[] { "foo" });
    context.setContextPath("/ctx");
    context.setResourceBase(MavenTestingUtils.getTestResourceDir("docroot").getAbsolutePath());
    HandlerList handlers = new HandlerList();
    handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
    server.setHandler(handlers);
    context.setHandler(session);
    // context.addAliasCheck(new AllowSymLinkAliasChecker());
    server.addBean(loginService);
    security = new ConstraintSecurityHandler();
    session.setHandler(security);
    ResourceHandler handler = new ResourceHandler();
    security.setHandler(handler);
    List<ConstraintMapping> constraints = new ArrayList<>();
    Constraint constraint0 = new Constraint();
    constraint0.setAuthenticate(true);
    constraint0.setName("forbid");
    ConstraintMapping mapping0 = new ConstraintMapping();
    mapping0.setPathSpec("/forbid/*");
    mapping0.setConstraint(constraint0);
    constraints.add(mapping0);
    Set<String> knownRoles = new HashSet<>();
    knownRoles.add("user");
    knownRoles.add("administrator");
    security.setConstraintMappings(constraints, knownRoles);
    server.start();
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HandlerList(org.eclipse.jetty.server.handler.HandlerList) Server(org.eclipse.jetty.server.Server) Constraint(org.eclipse.jetty.util.security.Constraint) LocalConnector(org.eclipse.jetty.server.LocalConnector) ArrayList(java.util.ArrayList) ResourceHandler(org.eclipse.jetty.server.handler.ResourceHandler) Matchers.containsString(org.hamcrest.Matchers.containsString) DefaultHandler(org.eclipse.jetty.server.handler.DefaultHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) Password(org.eclipse.jetty.util.security.Password) HashSet(java.util.HashSet) BeforeClass(org.junit.BeforeClass)

Aggregations

Constraint (org.eclipse.jetty.util.security.Constraint)78 ConstraintMapping (org.eclipse.jetty.security.ConstraintMapping)46 ConstraintSecurityHandler (org.eclipse.jetty.security.ConstraintSecurityHandler)34 BasicAuthenticator (org.eclipse.jetty.security.authentication.BasicAuthenticator)27 HashLoginService (org.eclipse.jetty.security.HashLoginService)20 Test (org.junit.Test)15 Server (org.eclipse.jetty.server.Server)13 ArrayList (java.util.ArrayList)9 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)8 Password (org.eclipse.jetty.util.security.Password)7 HashSet (java.util.HashSet)6 File (java.io.File)5 IOException (java.io.IOException)5 ResourceHandler (org.eclipse.jetty.server.handler.ResourceHandler)5 LoginService (org.eclipse.jetty.security.LoginService)4 ServerConnector (org.eclipse.jetty.server.ServerConnector)4 ContextHandler (org.eclipse.jetty.server.handler.ContextHandler)4 HandlerList (org.eclipse.jetty.server.handler.HandlerList)4 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)4 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)4