Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.security.authentication;
 
 
 
FORM Authenticator.

This authenticator implements form authentication will use dispatchers to the login page if the __FORM_DISPATCH init parameter is set to true. Otherwise it will redirect.

The form authenticator redirects unauthenticated requests to a log page which should use a form to gather username/password from the user and send them to the /j_security_check URI within the context. FormAuthentication uses SessionAuthentication to wrap Authentication results so that they are associated with the session.

 
 public class FormAuthenticator extends LoginAuthenticator
 {
     private static final Logger LOG = Log.getLogger(FormAuthenticator.class);
 
     public final static String __FORM_LOGIN_PAGE="org.eclipse.jetty.security.form_login_page";
     public final static String __FORM_ERROR_PAGE="org.eclipse.jetty.security.form_error_page";
     public final static String __FORM_DISPATCH="org.eclipse.jetty.security.dispatch";
     public final static String __J_URI = "org.eclipse.jetty.security.form_URI";
     public final static String __J_POST = "org.eclipse.jetty.security.form_POST";
     public final static String __J_SECURITY_CHECK = "/j_security_check";
     public final static String __J_USERNAME = "j_username";
     public final static String __J_PASSWORD = "j_password";
 
     private String _formErrorPage;
     private String _formErrorPath;
     private String _formLoginPage;
     private String _formLoginPath;
     private boolean _dispatch;
     private boolean _alwaysSaveUri;
 
     public FormAuthenticator()
     {
     }
 
     /* ------------------------------------------------------------ */
     public FormAuthenticator(String login,String error,boolean dispatch)
     {
         this();
         if (login!=null)
             setLoginPage(login);
         if (error!=null)
             setErrorPage(error);
        =dispatch;
    }
    
    /* ------------------------------------------------------------ */
    
If true, uris that cause a redirect to a login page will always be remembered. If false, only the first uri that leads to a login page redirect is remembered. See https://bugs.eclipse.org/bugs/show_bug.cgi?id=379909

Parameters:
alwaysSave
    public void setAlwaysSaveUri (boolean alwaysSave)
    {
         = alwaysSave;
    }
    
    
    /* ------------------------------------------------------------ */
    public boolean getAlwaysSaveUri ()
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    
    @Override
    public void setConfiguration(AuthConfiguration configuration)
    {
        super.setConfiguration(configuration);
        String login=configuration.getInitParameter(.);
        if (login!=null)
            setLoginPage(login);
        String error=configuration.getInitParameter(.);
        if (error!=null)
            setErrorPage(error);
        String dispatch=configuration.getInitParameter(.);
         = dispatch==null?:Boolean.valueOf(dispatch);
    }
    /* ------------------------------------------------------------ */
    public String getAuthMethod()
    {
        return .;
    }
    /* ------------------------------------------------------------ */
    private void setLoginPage(String path)
    {
        if (!path.startsWith("/"))
        {
            .warn("form-login-page must start with /");
            path = "/" + path;
        }
         = path;
         = path;
        if (.indexOf('?') > 0) 
             = .substring(0, .indexOf('?'));
    }
    /* ------------------------------------------------------------ */
    private void setErrorPage(String path)
    {
        if (path == null || path.trim().length() == 0)
        {
             = null;
             = null;
        }
        else
        {
            if (!path.startsWith("/"))
            {
                .warn("form-error-page must start with /");
                path = "/" + path;
            }
             = path;
             = path;
            if (.indexOf('?') > 0) 
                 = .substring(0, .indexOf('?'));
        }
    }
    
    
    /* ------------------------------------------------------------ */
    @Override
    public UserIdentity login(String usernameObject passwordServletRequest request)
    {
        
        UserIdentity user = super.login(username,password,request);
        if (user!=null)
        {
            HttpSession session = ((HttpServletRequest)request).getSession(true);
            Authentication cached=new SessionAuthentication(getAuthMethod(),user,password);
            session.setAttribute(.cached);
        }
        return user;
    }
    /* ------------------------------------------------------------ */
    public Authentication validateRequest(ServletRequest reqServletResponse resboolean mandatorythrows ServerAuthException
    {   
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        String uri = request.getRequestURI();
        if (uri==null)
            uri=.;
        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();
                final String password = request.getParameter();
                
                UserIdentity user = login(usernamepasswordrequest);
                session = request.getSession(true);
                if (user!=null)
                {                    
                    // Redirect to original request
                    String nuri;
                    synchronized(session)
                    {
                        nuri = (Stringsession.getAttribute();
                        if (nuri == null || nuri.length() == 0)
                        {
                            nuri = request.getContextPath();
                            if (nuri.length() == 0) 
                                nuri = .;
                        }
                    }
                    response.setContentLength(0);   
                    response.sendRedirect(response.encodeRedirectURL(nuri));
                    
                    return new FormAuthentication(getAuthMethod(),user);
                }
                
                // not authenticated
                if (.isDebugEnabled()) 
                    .debug("Form authentication FAILED for " + StringUtil.printable(username));
                if ( == null)
                {
                    if (response != null
                        response.sendError(.);
                }
                else if ()
                {
                    RequestDispatcher dispatcher = request.getRequestDispatcher();
                    response.setHeader(.,"No-cache");
                    response.setDateHeader(.,1);
                    dispatcher.forward(new FormRequest(request), new FormResponse(response));
                }
                else
                {
                    response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(),)));
                }
                
                return .;
            }
            
            // Look for cached authentication
            Authentication authentication = (Authenticationsession.getAttribute(.);
            if (authentication != null
            {
                // Has authentication been revoked?
                if (authentication instanceof Authentication.User && 
                    !=null &&
                    !.validate(((Authentication.User)authentication).getUserIdentity()))
                {
                
                    session.removeAttribute(.);
                }
                else
                {
                    String j_uri=(String)session.getAttribute();
                    if (j_uri!=null)
                    {
                        MultiMap<Stringj_post = (MultiMap<String>)session.getAttribute();
                        if (j_post!=null)
                        {
                            StringBuffer buf = request.getRequestURL();
                            if (request.getQueryString() != null)
                                buf.append("?").append(request.getQueryString());
                            if (j_uri.equals(buf.toString()))
                            {
                                // This is a retry of an original POST request
                                // so restore method and parameters
                                session.removeAttribute();                        
                                Request base_request = (req instanceof Request)?(Request)req:AbstractHttpConnection.getCurrentConnection().getRequest();
                                base_request.setMethod(.);
                                base_request.setParameters(j_post);
                            }
                        }
                        else
                            session.removeAttribute();
                            
                    }
                    return authentication;
                }
            }
            // if we can't send challenge
            if (DeferredAuthentication.isDeferred(response))
            {
                .debug("auth deferred {}",session.getId());
                return .;
            }
            // 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()==null || )
                {  
                    StringBuffer buf = request.getRequestURL();
                    if (request.getQueryString() != null)
                        buf.append("?").append(request.getQueryString());
                    session.setAttribute(buf.toString());
                    
                    if (..equalsIgnoreCase(req.getContentType()) && ..equals(request.getMethod()))
                    {
                        Request base_request = (req instanceof Request)?(Request)req:AbstractHttpConnection.getCurrentConnection().getRequest();
                        base_request.extractParameters();                        
                        session.setAttribute(new MultiMap<String>(base_request.getParameters()));
                    }
                }
            }
            
            // send the the challenge
            if ()
            {
                RequestDispatcher dispatcher = request.getRequestDispatcher();
                response.setHeader(.,"No-cache");
                response.setDateHeader(.,1);
                dispatcher.forward(new FormRequest(request), new FormResponse(response));
            }
            else
            {
                response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getContextPath(),)));
            }
            return .;
            
         
        }
        catch (IOException e)
        {
            throw new ServerAuthException(e);
        }
        catch (ServletException e)
        {
            throw new ServerAuthException(e);
        }
    }
    
    /* ------------------------------------------------------------ */
    public boolean isJSecurityCheck(String uri)
    {
        int jsc = uri.indexOf();
        
        if (jsc<0)
            return false;
        int e=jsc+.length();
        if (e==uri.length())
            return true;
        char c = uri.charAt(e);
        return c==';'||c=='#'||c=='/'||c=='?';
    }
    
    /* ------------------------------------------------------------ */
    public boolean isLoginOrErrorPage(String pathInContext)
    {
        return pathInContext != null && (pathInContext.equals() || pathInContext.equals());
    }
    
    /* ------------------------------------------------------------ */
    public boolean secureResponse(ServletRequest reqServletResponse resboolean mandatoryUser validatedUserthrows ServerAuthException
    {
        return true;
    }
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    protected static class FormRequest extends HttpServletRequestWrapper
    {
        public FormRequest(HttpServletRequest request)
        {
            super(request);
        }
        @Override
        public long getDateHeader(String name)
        {
            if (name.toLowerCase(.).startsWith("if-"))
                return -1;
            return super.getDateHeader(name);
        }
        
        @Override
        public String getHeader(String name)
        {
            if (name.toLowerCase(.).startsWith("if-"))
                return null;
            return super.getHeader(name);
        }
        @Override
        public Enumeration getHeaderNames()
        {
            return Collections.enumeration(Collections.list(super.getHeaderNames()));
        }
        @Override
        public Enumeration getHeaders(String name)
        {
            if (name.toLowerCase(.).startsWith("if-"))
                return Collections.enumeration(.);
            return super.getHeaders(name);
        }
    }
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    protected static class FormResponse extends HttpServletResponseWrapper
    {
        public FormResponse(HttpServletResponse response)
        {
            super(response);
        }
        @Override
        public void addDateHeader(String namelong date)
        {
            if (notIgnored(name))
                super.addDateHeader(name,date);
        }
        @Override
        public void addHeader(String nameString value)
        {
            if (notIgnored(name))
                super.addHeader(name,value);
        }
        @Override
        public void setDateHeader(String namelong date)
        {
            if (notIgnored(name))
                super.setDateHeader(name,date);
        }
        
        @Override
        public void setHeader(String nameString value)
        {
            if (notIgnored(name))
                super.setHeader(name,value);
        }
        
        private boolean notIgnored(String name)
        {
            if (..equalsIgnoreCase(name) ||
                ..equalsIgnoreCase(name) ||
                ..equalsIgnoreCase(name) ||
                ..equalsIgnoreCase(name) ||
                ..equalsIgnoreCase(name) ||
                ..equalsIgnoreCase(name))
                return false;
            return true;
        }
    }
    
    /* ------------------------------------------------------------ */
    
This Authentication represents a just completed Form authentication. Subsequent requests from the same user are authenticated by the presents of a SessionAuthentication instance in their session.
    public static class FormAuthentication extends UserAuthentication implements Authentication.ResponseSent
    {
        public FormAuthentication(String methodUserIdentity userIdentity)
        {
            super(method,userIdentity);
        }
        
        @Override
        public String toString()
        {
            return "Form"+super.toString();
        }
    }
New to GrepCode? Check out our FAQ X