Search in sources :

Example 6 with ServerAuthException

use of org.eclipse.jetty.security.ServerAuthException in project jetty.project by eclipse.

the class DeferredAuthentication method authenticate.

/* ------------------------------------------------------------ */
/**
     * @see org.eclipse.jetty.server.Authentication.Deferred#authenticate(ServletRequest)
     */
@Override
public Authentication authenticate(ServletRequest request) {
    try {
        Authentication authentication = _authenticator.validateRequest(request, __deferredResponse, true);
        if (authentication != null && (authentication instanceof Authentication.User) && !(authentication instanceof Authentication.ResponseSent)) {
            LoginService login_service = _authenticator.getLoginService();
            IdentityService identity_service = login_service.getIdentityService();
            if (identity_service != null)
                _previousAssociation = identity_service.associate(((Authentication.User) authentication).getUserIdentity());
            return authentication;
        }
    } catch (ServerAuthException e) {
        LOG.debug(e);
    }
    return this;
}
Also used : IdentityService(org.eclipse.jetty.security.IdentityService) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) LoginService(org.eclipse.jetty.security.LoginService)

Example 7 with ServerAuthException

use of org.eclipse.jetty.security.ServerAuthException in project jetty.project by eclipse.

the class DeferredAuthentication method authenticate.

/* ------------------------------------------------------------ */
/**
     * @see org.eclipse.jetty.server.Authentication.Deferred#authenticate(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
     */
@Override
public Authentication authenticate(ServletRequest request, ServletResponse response) {
    try {
        LoginService login_service = _authenticator.getLoginService();
        IdentityService identity_service = login_service.getIdentityService();
        Authentication authentication = _authenticator.validateRequest(request, response, true);
        if (authentication instanceof Authentication.User && identity_service != null)
            _previousAssociation = identity_service.associate(((Authentication.User) authentication).getUserIdentity());
        return authentication;
    } catch (ServerAuthException e) {
        LOG.debug(e);
    }
    return this;
}
Also used : IdentityService(org.eclipse.jetty.security.IdentityService) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Authentication(org.eclipse.jetty.server.Authentication) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) LoginService(org.eclipse.jetty.security.LoginService)

Example 8 with ServerAuthException

use of org.eclipse.jetty.security.ServerAuthException in project hive by apache.

the class PamAuthenticator method validateRequest.

@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        if (!mandatory)
            return new DeferredAuthentication(this);
        if (credentials != null) {
            int space = credentials.indexOf(' ');
            if (space > 0) {
                String method = credentials.substring(0, space);
                if ("basic".equalsIgnoreCase(method)) {
                    credentials = credentials.substring(space + 1);
                    credentials = B64Code.decode(credentials, StandardCharsets.ISO_8859_1);
                    int i = credentials.indexOf(':');
                    if (i > 0) {
                        String username = credentials.substring(0, i);
                        String password = credentials.substring(i + 1);
                        UserIdentity user = login(username, password);
                        if (user != null) {
                            return new UserAuthentication(getAuthMethod(), user);
                        }
                    }
                }
            }
        }
        if (DeferredAuthentication.isDeferred(response))
            return Authentication.UNAUTHENTICATED;
        response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "basic realm=\"" + _loginService.getName() + '"');
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return Authentication.SEND_CONTINUE;
    } catch (IOException e) {
        throw new ServerAuthException(e);
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) UserIdentity(org.eclipse.jetty.server.UserIdentity) HttpServletResponse(javax.servlet.http.HttpServletResponse) DeferredAuthentication(org.eclipse.jetty.security.authentication.DeferredAuthentication) IOException(java.io.IOException) ServerAuthException(org.eclipse.jetty.security.ServerAuthException) UserAuthentication(org.eclipse.jetty.security.UserAuthentication)

Example 9 with ServerAuthException

use of org.eclipse.jetty.security.ServerAuthException in project jetty.project by eclipse.

the class DigestAuthenticator method validateRequest.

@Override
public Authentication validateRequest(ServletRequest req, ServletResponse res, boolean mandatory) throws ServerAuthException {
    if (!mandatory)
        return new DeferredAuthentication(this);
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String credentials = request.getHeader(HttpHeader.AUTHORIZATION.asString());
    try {
        boolean stale = false;
        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;
                        break;
                    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;
                            name = null;
                        }
                }
            }
            int n = checkNonce(digest, (Request) request);
            if (n > 0) {
                //UserIdentity user = _loginService.login(digest.username,digest);
                UserIdentity user = login(digest.username, digest, req);
                if (user != null) {
                    return new UserAuthentication(getAuthMethod(), user);
                }
            } else if (n == 0)
                stale = true;
        }
        if (!DeferredAuthentication.isDeferred(response)) {
            String domain = request.getContextPath();
            if (domain == null)
                domain = "/";
            response.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), "Digest realm=\"" + _loginService.getName() + "\", domain=\"" + domain + "\", nonce=\"" + newNonce((Request) request) + "\", algorithm=MD5, qop=\"auth\"," + " stale=" + stale);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return Authentication.SEND_CONTINUE;
        }
        return Authentication.UNAUTHENTICATED;
    } catch (IOException e) {
        throw new ServerAuthException(e);
    }
}
Also used : MessageDigest(java.security.MessageDigest) 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) UserAuthentication(org.eclipse.jetty.security.UserAuthentication) Constraint(org.eclipse.jetty.util.security.Constraint) HttpServletRequest(javax.servlet.http.HttpServletRequest) QuotedStringTokenizer(org.eclipse.jetty.util.QuotedStringTokenizer)

Example 10 with ServerAuthException

use of org.eclipse.jetty.security.ServerAuthException in project jetty.project by eclipse.

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 = null;
    try {
        session = request.getSession(true);
    } catch (Exception e) {
        if (LOG.isDebugEnabled())
            LOG.debug(e);
    }
    //unauthenticated
    if (session == null)
        return Authentication.UNAUTHENTICATED;
    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 Authentication.User && _loginService != null && !_loginService.validate(((Authentication.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) ServletException(javax.servlet.ServletException) 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)

Aggregations

ServerAuthException (org.eclipse.jetty.security.ServerAuthException)17 UserAuthentication (org.eclipse.jetty.security.UserAuthentication)16 HttpServletRequest (javax.servlet.http.HttpServletRequest)12 HttpServletResponse (javax.servlet.http.HttpServletResponse)12 UserIdentity (org.eclipse.jetty.server.UserIdentity)12 IOException (java.io.IOException)10 Authentication (org.eclipse.jetty.server.Authentication)7 Constraint (org.eclipse.jetty.util.security.Constraint)6 ServletRequest (javax.servlet.ServletRequest)4 IdentityService (org.eclipse.jetty.security.IdentityService)4 LoginService (org.eclipse.jetty.security.LoginService)4 Request (org.eclipse.jetty.server.Request)4 Principal (java.security.Principal)3 HttpSession (javax.servlet.http.HttpSession)3 KeyStore (java.security.KeyStore)2 MessageDigest (java.security.MessageDigest)2 X509Certificate (java.security.cert.X509Certificate)2 AuthException (javax.security.auth.message.AuthException)2 AuthStatus (javax.security.auth.message.AuthStatus)2 ServerAuthContext (javax.security.auth.message.config.ServerAuthContext)2