Search in sources :

Example 1 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class BasicAuthenticator method authenticate.

@Override
public Subject authenticate(HttpServletRequest request, HttpServletResponse response, boolean sendChallenge) throws IOException {
    String credentials = request.getHeader("Authorization");
    String username = null;
    String password = null;
    try {
        if (credentials != null && credentials.startsWith("Basic")) {
            final byte[] c = Base64.decodeBase64(credentials.substring("Basic ".length()));
            final String s = new String(c, UTF_8);
            // LOG.debug("BASIC auth credentials: "+s);
            final int p = s.indexOf(':');
            username = p < 0 ? s : s.substring(0, p);
            password = p < 0 ? null : s.substring(p + 1);
        }
    } catch (final IllegalArgumentException iae) {
        LOG.warn("Invalid BASIC authentication header received: {}", iae.getMessage(), iae);
        credentials = null;
    }
    // get the user from the session if possible
    final HttpSession session = request.getSession(false);
    Subject user = null;
    if (session != null) {
        user = (Subject) session.getAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER);
        if (user != null && (username == null || user.getName().equals(username))) {
            return user;
        }
    }
    if (user != null) {
        session.removeAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER);
    }
    // get the credentials
    if (credentials == null) {
        // LOG.debug("Sending BASIC auth challenge.");
        if (sendChallenge) {
            sendChallenge(request, response);
        }
        return null;
    }
    // authenticate the credentials
    final SecurityManager secman = pool.getSecurityManager();
    try {
        user = secman.authenticate(username, password);
    } catch (final AuthenticationException e) {
        // if authentication failed then send a challenge request again
        if (sendChallenge) {
            sendChallenge(request, response);
        }
        return null;
    }
    // store the user in the session
    if (session != null) {
        session.setAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER, user);
    }
    // return the authenticated user
    return user;
}
Also used : SecurityManager(org.exist.security.SecurityManager) AuthenticationException(org.exist.security.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) Subject(org.exist.security.Subject)

Example 2 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class AbstractExistHttpServlet method authenticate.

protected Subject authenticate(HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (isInternalOnly() && request.getAttribute(XQueryURLRewrite.RQ_ATTR) == null) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return null;
    }
    Principal principal = HttpAccount.getUserFromServletRequest(request);
    if (principal != null) {
        return (Subject) principal;
    }
    // Try to validate the principal if passed from the Servlet engine
    principal = request.getUserPrincipal();
    if (principal != null) {
        if (XmldbPrincipal.class.isAssignableFrom(principal.getClass())) {
            final String username = ((XmldbPrincipal) principal).getName();
            final String password = ((XmldbPrincipal) principal).getPassword();
            getLog().info("Validating Principle: {}", username);
            try {
                return getPool().getSecurityManager().authenticate(username, password);
            } catch (final AuthenticationException e) {
                getLog().info(e.getMessage());
            }
        }
        if (principal instanceof Subject) {
            return (Subject) principal;
        }
    }
    // Secondly try basic authentication
    final String auth = request.getHeader("Authorization");
    if (auth == null && getDefaultUser() != null) {
        return getDefaultUser();
    }
    return getAuthenticator().authenticate(request, response, true);
}
Also used : XmldbPrincipal(org.exist.security.XmldbPrincipal) AuthenticationException(org.exist.security.AuthenticationException) Principal(java.security.Principal) XmldbPrincipal(org.exist.security.XmldbPrincipal) Subject(org.exist.security.Subject)

Example 3 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class ActiveDirectoryRealm method authenticate.

/*
	 * (non-Javadoc)
	 * 
	 * @see org.exist.security.Realm#authenticate(java.lang.String,
	 * java.lang.Object)
	 */
@Override
public Subject authenticate(final String username, Object credentials) throws AuthenticationException {
    String[] returnedAtts = { "sn", "givenName", "mail" };
    String searchFilter = "(&(objectClass=user)(sAMAccountName=" + username + "))";
    // Create the search controls
    SearchControls searchCtls = new SearchControls();
    searchCtls.setReturningAttributes(returnedAtts);
    // Specify the search scope
    searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    LdapContext ctxGC = null;
    boolean ldapUser = false;
    try {
        ctxGC = ensureContextFactory().getLdapContext(username, String.valueOf(credentials));
        // Search objects in GC using filters
        NamingEnumeration<SearchResult> answer = ctxGC.search(((ContextFactory) ensureContextFactory()).getSearchBase(), searchFilter, searchCtls);
        while (answer.hasMoreElements()) {
            SearchResult sr = answer.next();
            Attributes attrs = sr.getAttributes();
            Map<String, Object> amap = null;
            if (attrs != null) {
                amap = new HashMap<>();
                NamingEnumeration<? extends Attribute> ne = attrs.getAll();
                while (ne.hasMore()) {
                    Attribute attr = ne.next();
                    amap.put(attr.getID(), attr.get());
                    ldapUser = true;
                }
                ne.close();
            }
        }
    } catch (NamingException e) {
        e.printStackTrace();
        throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e.getMessage());
    }
    if (ldapUser) {
        AbstractAccount account = (AbstractAccount) getAccount(username);
        if (account == null) {
            try (final DBBroker broker = getDatabase().get(Optional.of(getSecurityManager().getSystemSubject()))) {
                // perform as SYSTEM user
                account = (AbstractAccount) getSecurityManager().addAccount(new UserAider(ID, username));
            } catch (Exception e) {
                throw new AuthenticationException(AuthenticationException.UNNOWN_EXCEPTION, e.getMessage(), e);
            }
        }
        return new SubjectAccreditedImpl(account, ctxGC);
    }
    return null;
}
Also used : Attribute(javax.naming.directory.Attribute) AuthenticationException(org.exist.security.AuthenticationException) AbstractAccount(org.exist.security.AbstractAccount) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) AuthenticationException(org.exist.security.AuthenticationException) NamingException(javax.naming.NamingException) DBBroker(org.exist.storage.DBBroker) SubjectAccreditedImpl(org.exist.security.internal.SubjectAccreditedImpl) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException) UserAider(org.exist.security.internal.aider.UserAider) LdapContext(javax.naming.ldap.LdapContext)

Example 4 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class ActiveDirectoryRealmTest method testAuthenticate.

/**
 * Test method for {@link org.exist.security.realm.activedirectory.ActiveDirectoryRealm#authenticate(java.lang.String, java.lang.Object)}.
 */
@Ignore
@Test
public void testAuthenticate() {
    Subject currentUser = null;
    try {
        currentUser = realm.authenticate("accounter@fake.com", "password");
    } catch (AuthenticationException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
    assertNotNull(currentUser);
}
Also used : AuthenticationException(org.exist.security.AuthenticationException) Subject(org.exist.security.Subject) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with AuthenticationException

use of org.exist.security.AuthenticationException in project exist by eXist-db.

the class IPRangeServlet method doPost.

@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    // Get reverse proxy header when available, otherwise use regular IP address
    String ipAddress = request.getHeader("X-Forwarded-For");
    // there may be a comma-separated chain of proxies
    if (ipAddress != null && !ipAddress.isEmpty()) {
        ipAddress = ipAddress.replaceAll("\\s", "");
        String[] xFFs = ipAddress.split(",");
        if (xFFs.length > 1)
            ipAddress = xFFs[xFFs.length - 1];
    } else {
        ipAddress = request.getRemoteAddr();
    }
    LOG.info("Detected IPaddress {}", ipAddress);
    String jsonResponse = "{\"fail\":\"IP range not authenticated\"}";
    try {
        final SecurityManager securityManager = IPRangeRealm.getInstance().getSecurityManager();
        final Subject user = securityManager.authenticate(ipAddress, ipAddress);
        if (user != null) {
            LOG.info("IPRangeServlet user {} found", user.getUsername());
            // Security check
            if (user.hasDbaRole()) {
                LOG.error("User {} has DBA rights, will not be authorized", user.getUsername());
                return;
            }
            final HttpSession session = request.getSession();
            // store the user in the session
            if (session != null) {
                jsonResponse = "{\"user\":\"" + user.getUsername() + "\",\"isAdmin\":\"" + user.hasDbaRole() + "\"}";
                LOG.info("IPRangeServlet setting session attr " + XQueryContext.HTTP_SESSIONVAR_XMLDB_USER);
                session.setAttribute(XQueryContext.HTTP_SESSIONVAR_XMLDB_USER, user);
            } else {
                LOG.info("IPRangeServlet session is null");
            }
        } else {
            LOG.error("IPRangeServlet user not found");
        }
    } catch (final AuthenticationException e) {
        throw new IOException(e.getMessage());
    } finally {
        response.setContentType("application/json");
        final PrintWriter out = response.getWriter();
        out.print(jsonResponse);
        out.flush();
    }
}
Also used : SecurityManager(org.exist.security.SecurityManager) AuthenticationException(org.exist.security.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) IOException(java.io.IOException) Subject(org.exist.security.Subject) PrintWriter(java.io.PrintWriter)

Aggregations

AuthenticationException (org.exist.security.AuthenticationException)33 NamingException (javax.naming.NamingException)16 Subject (org.exist.security.Subject)13 SearchResult (javax.naming.directory.SearchResult)12 LdapContext (javax.naming.ldap.LdapContext)12 SearchControls (javax.naming.directory.SearchControls)9 ArrayList (java.util.ArrayList)8 EXistException (org.exist.EXistException)8 SecurityManager (org.exist.security.SecurityManager)8 AbstractAccount (org.exist.security.AbstractAccount)6 Account (org.exist.security.Account)6 PermissionDeniedException (org.exist.security.PermissionDeniedException)5 Group (org.exist.security.Group)4 DBBroker (org.exist.storage.DBBroker)4 HttpSession (javax.servlet.http.HttpSession)3 IOException (java.io.IOException)2 PrintWriter (java.io.PrintWriter)2 URISyntaxException (java.net.URISyntaxException)2 Properties (java.util.Properties)2 ServletException (javax.servlet.ServletException)2