Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 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;
 
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
Abstract SecurityHandler. Select and apply an Authenticator to a request.

The Authenticator may either be directly set on the handler or will be create during org.eclipse.jetty.util.component.AbstractLifeCycle.start() with a call to either the default or set AuthenticatorFactory.

SecurityHandler has a set of initparameters that are used by the Authentication.Configuration. At startup, any context init parameters that start with "org.eclipse.jetty.security." that do not have values in the SecurityHandler init parameters, are copied.

 
 public abstract class SecurityHandler extends HandlerWrapper implements Authenticator.AuthConfiguration
 {
     private static final Logger LOG = Log.getLogger(SecurityHandler.class);
 
     /* ------------------------------------------------------------ */
     private boolean _checkWelcomeFiles = false;
     private Authenticator _authenticator;
     private String _realmName;
     private String _authMethod;
     private final Map<String,String_initParameters=new HashMap<String,String>();
     private LoginService _loginService;
     private boolean _loginServiceShared;
     private IdentityService _identityService;
     private boolean _renewSession=true;
 
     /* ------------------------------------------------------------ */
     protected SecurityHandler()
     {
     }
     
     /* ------------------------------------------------------------ */
    
Get the identityService.

Returns:
the identityService
 
     {
         return ;
     }
 
     /* ------------------------------------------------------------ */
    
Set the identityService.

Parameters:
identityService the identityService to set
 
     public void setIdentityService(IdentityService identityService)
     {
        if (isStarted())
            throw new IllegalStateException("Started");
         = identityService;
    }
    /* ------------------------------------------------------------ */
    
Get the loginService.

Returns:
the loginService
    public LoginService getLoginService()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the loginService.

Parameters:
loginService the loginService to set
    public void setLoginService(LoginService loginService)
    {
        if (isStarted())
            throw new IllegalStateException("Started");
         = loginService;
        =false;
    }
    /* ------------------------------------------------------------ */
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    
Set the authenticator.

Parameters:
authenticator
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public void setAuthenticator(Authenticator authenticator)
    {
        if (isStarted())
            throw new IllegalStateException("Started");
         = authenticator;
    }
    /* ------------------------------------------------------------ */
    

Returns:
the authenticatorFactory
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    

Parameters:
authenticatorFactory the authenticatorFactory to set
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public void setAuthenticatorFactory(Authenticator.Factory authenticatorFactory)
    {
        if (isRunning())
            throw new IllegalStateException("running");
         = authenticatorFactory;
    }
    /* ------------------------------------------------------------ */
    

Returns:
the realmName
    public String getRealmName()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    

Parameters:
realmName the realmName to set
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public void setRealmName(String realmName)
    {
        if (isRunning())
            throw new IllegalStateException("running");
         = realmName;
    }
    /* ------------------------------------------------------------ */
    

Returns:
the authMethod
    public String getAuthMethod()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    

Parameters:
authMethod the authMethod to set
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public void setAuthMethod(String authMethod)
    {
        if (isRunning())
            throw new IllegalStateException("running");
         = authMethod;
    }
    
    /* ------------------------------------------------------------ */
    

Returns:
True if forwards to welcome files are authenticated
    public boolean isCheckWelcomeFiles()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    

Parameters:
authenticateWelcomeFiles True if forwards to welcome files are authenticated
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public void setCheckWelcomeFiles(boolean authenticateWelcomeFiles)
    {
        if (isRunning())
            throw new IllegalStateException("running");
         = authenticateWelcomeFiles;
    }
    /* ------------------------------------------------------------ */
    public String getInitParameter(String key)
    {
        return .get(key);
    }
    
    /* ------------------------------------------------------------ */
    public Set<StringgetInitParameterNames()
    {
        return .keySet();
    }
    
    /* ------------------------------------------------------------ */
    
Set an initialization parameter.

Parameters:
key
value
Returns:
previous value
Throws:
java.lang.IllegalStateException if the SecurityHandler is running
    public String setInitParameter(String keyString value)
    {
        if (isRunning())
            throw new IllegalStateException("running");
        return .put(key,value);
    }
    
    /* ------------------------------------------------------------ */
    protected LoginService findLoginService()
    {
        List<LoginServicelist = getServer().getBeans(LoginService.class);
        
        String realm=getRealmName();
        if (realm!=null)
        {
            for (LoginService service : list)
                if (service.getName()!=null && service.getName().equals(realm))
                    return service;
        }
        else if (list.size()==1)
            return list.get(0);
        return null;
    }
    
    /* ------------------------------------------------------------ */
    {
        return getServer().getBean(IdentityService.class);
    }
    
    /* ------------------------------------------------------------ */
    
    @Override
    protected void doStart()
        throws Exception
    {
        // copy security init parameters
        ContextHandler.Context context =ContextHandler.getCurrentContext();
        if (context!=null)
        {
            Enumeration<Stringnames=context.getInitParameterNames();
            while (names!=null && names.hasMoreElements())
            {
                String name =names.nextElement();
                if (name.startsWith("org.eclipse.jetty.security.") &&
                        getInitParameter(name)==null)
                    setInitParameter(name,context.getInitParameter(name));
            }
            
            //register a session listener to handle securing sessions when authentication is performed
            context.getContextHandler().addEventListener(new HttpSessionListener()
            {
                
                public void sessionDestroyed(HttpSessionEvent se)
                {
                   
                }
                
                public void sessionCreated(HttpSessionEvent se)
                {
                    //if current request is authenticated, then as we have just created the session, mark it as secure, as it has not yet been returned to a user
                    AbstractHttpConnection connection = AbstractHttpConnection.getCurrentConnection();
                    if (connection == null)
                        return;
                    Request request = connection.getRequest();
                    if (request == null)
                        return;
                    
                    if (request.isSecure())
                    {
                        se.getSession().setAttribute(..);
                    }
                }
            });
        }
        
        // complicated resolution of login and identity service to handle
        // many different ways these can be constructed and injected.
        
        if (==null)
        {
            =findLoginService();
            if (!=null)
                =true;
        }
        
        if (==null)
        {
           
            if (!=null)
                =.getIdentityService();
            if (==null)
                =findIdentityService();
            
            if (==null && !=null)
                =new DefaultIdentityService();
        }
        
        if (!=null)
        {
            if (.getIdentityService()==null)
                .setIdentityService();
            else if (.getIdentityService()!=)
                throw new IllegalStateException("LoginService has different IdentityService to "+this);
        }
        if (! &&  instanceof LifeCycle)
            ((LifeCycle)).start();        
        
        if (==null && !=null && !=null)
        {
            if (!=null)
                =.getAuthMethod();
        }
        if (==null)
        {
            if (!=null)
            {
                .warn("No ServerAuthentication for "+this);
                throw new IllegalStateException("No ServerAuthentication");
            }
        }
        else
        {
            .setConfiguration(this);
            if ( instanceof LifeCycle)
                ((LifeCycle)).start();
        }
        super.doStart();
    }
    /* ------------------------------------------------------------ */
    
    @Override
    protected void doStop() throws Exception
    {
        super.doStop();
        
        if (! &&  instanceof LifeCycle)
            ((LifeCycle)).stop();
        
    }
    /* ------------------------------------------------------------ */
    protected boolean checkSecurity(Request request)
    {
        switch(request.getDispatcherType())
        {
            case :
            case :
                return true;
            case :
                if ( && request.getAttribute("org.eclipse.jetty.server.welcome") != null)
                {
                    request.removeAttribute("org.eclipse.jetty.server.welcome");
                    return true;
                }
                return false;
            default:
                return false;
        }
    }
    
    /* ------------------------------------------------------------ */
    
    public boolean isSessionRenewedOnAuthentication()
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    
Set renew the session on Authentication.

If set to true, then on authentication, the session associated with a reqeuest is invalidated and replaced with a new session.

    public void setSessionRenewedOnAuthentication(boolean renew)
    {
        =renew;
    }
    
    /* ------------------------------------------------------------ */
    /*
     * @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
     *      javax.servlet.http.HttpServletRequest,
     *      javax.servlet.http.HttpServletResponse, int)
     */
    @Override
    public void handle(String pathInContextRequest baseRequestHttpServletRequest requestHttpServletResponse responsethrows IOExceptionServletException
    {
        final Response base_response = baseRequest.getResponse();
        final Handler handler=getHandler();
        
        if (handler==null)
            return;
        final Authenticator authenticator = ;
        
        if (checkSecurity(baseRequest))
        {
            Object constraintInfo = prepareConstraintInfo(pathInContextbaseRequest);
            
            // Check data constraints
            if (!checkUserDataPermissions(pathInContextbaseRequestbase_responseconstraintInfo))
            {
                if (!baseRequest.isHandled())
                {
                    response.sendError(.);
                    baseRequest.setHandled(true);
                }
                return;
            }
            // is Auth mandatory?
            boolean isAuthMandatory = 
                isAuthMandatory(baseRequestbase_responseconstraintInfo);
            if (isAuthMandatory && authenticator==null)
            {
                .warn("No authenticator for: "+constraintInfo);
                if (!baseRequest.isHandled())
                {
                    response.sendError(.);
                    baseRequest.setHandled(true);
                }
                return;
            }
            
            // check authentication
            Object previousIdentity = null;
            try
            {
                Authentication authentication = baseRequest.getAuthentication();
                if (authentication==null || authentication==.)
                    authentication=authenticator==null?.:authenticator.validateRequest(requestresponseisAuthMandatory);
                if (authentication instanceof Authentication.Wrapped)
                {
                    request=((Authentication.Wrapped)authentication).getHttpServletRequest();
                    response=((Authentication.Wrapped)authentication).getHttpServletResponse();
                }
                if (authentication instanceof Authentication.ResponseSent)
                {
                    baseRequest.setHandled(true);
                }
                else if (authentication instanceof Authentication.User)
                {
                    Authentication.User userAuth = (Authentication.User)authentication;
                    baseRequest.setAuthentication(authentication);
                    if (!=null)
                        previousIdentity = .associate(userAuth.getUserIdentity());
                    if (isAuthMandatory)
                    {
                        boolean authorized=checkWebResourcePermissions(pathInContextbaseRequestbase_responseconstraintInfouserAuth.getUserIdentity());
                        if (!authorized)
                        {
                            response.sendError(."!role");
                            baseRequest.setHandled(true);
                            return;
                        }
                    }
                         
                    handler.handle(pathInContextbaseRequestrequestresponse);
                    if (authenticator!=null)
                        authenticator.secureResponse(requestresponseisAuthMandatoryuserAuth);
                }
                else if (authentication instanceof Authentication.Deferred)
                {
                    DeferredAuthentication deferred= (DeferredAuthentication)authentication;
                    baseRequest.setAuthentication(authentication);
                    try
                    {
                        handler.handle(pathInContextbaseRequestrequestresponse);
                    }
                    finally
                    {
                        previousIdentity = deferred.getPreviousAssociation();
                    }
                    if (authenticator!=null)
                    {
                        Authentication auth=baseRequest.getAuthentication();
                        if (auth instanceof Authentication.User)
                        {
                            Authentication.User userAuth = (Authentication.User)auth;
                            authenticator.secureResponse(requestresponseisAuthMandatoryuserAuth);
                        }
                        else
                            authenticator.secureResponse(requestresponseisAuthMandatorynull);
                    }
                }
                else
                {
                    baseRequest.setAuthentication(authentication);
                    if (!=null)
                        previousIdentity = .associate(null);
                    handler.handle(pathInContextbaseRequestrequestresponse);
                    if (authenticator!=null)
                        authenticator.secureResponse(requestresponseisAuthMandatorynull);
                }
            }
            catch (ServerAuthException e)
            {
                // jaspi 3.8.3 send HTTP 500 internal server error, with message
                // from AuthException
                response.sendError(.e.getMessage());
            }
            finally
            {
                if (!=null)
                    .disassociate(previousIdentity);
            }
        }
        else
            handler.handle(pathInContextbaseRequestrequestresponse);
    }
    /* ------------------------------------------------------------ */
    {
        Context context = ContextHandler.getCurrentContext();
        if (context==null)
            return null;
        
        SecurityHandler security = context.getContextHandler().getChildHandlerByClass(SecurityHandler.class);
        return security;
    }
    /* ------------------------------------------------------------ */
    public void logout(Authentication.User user)
    {
        .debug("logout {}",user);
        LoginService login_service=getLoginService();
        if (login_service!=null)
        {
            login_service.logout(user.getUserIdentity());
        }
        
        IdentityService identity_service=getIdentityService();
        if (identity_service!=null)
        {
            // TODO recover previous from threadlocal (or similar)
            Object previous=null;
            identity_service.disassociate(previous);
        }
    }
    
    /* ------------------------------------------------------------ */
    protected abstract Object prepareConstraintInfo(String pathInContextRequest request);
    /* ------------------------------------------------------------ */
    protected abstract boolean checkUserDataPermissions(String pathInContextRequest requestResponse responseObject constraintInfothrows IOException;
    /* ------------------------------------------------------------ */
    protected abstract boolean isAuthMandatory(Request baseRequestResponse base_responseObject constraintInfo);
    /* ------------------------------------------------------------ */
    protected abstract boolean checkWebResourcePermissions(String pathInContextRequest requestResponse responseObject constraintInfo,
                                                           UserIdentity userIdentitythrows IOException;
    
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    public class NotChecked implements Principal
    {
        public String getName()
        {
            return null;
        }
        @Override
        public String toString()
        {
            return "NOT CHECKED";
        }
        public SecurityHandler getSecurityHandler()
        {
            return SecurityHandler.this;
        }
    }
    
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    public static Principal __NO_USER = new Principal()
    {
        public String getName()
        {
            return null;
        }
        @Override
        public String toString()
        {
            return "No User";
        }
    };
    
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    
Nobody user. The Nobody UserPrincipal is used to indicate a partial state of authentication. A request with a Nobody UserPrincipal will be allowed past all authentication constraints - but will not be considered an authenticated request. It can be used by Authenticators such as FormAuthenticator to allow access to logon and error pages within an authenticated URI tree.
    public static Principal __NOBODY = new Principal()
    {
        public String getName()
        {
            return "Nobody";
        }
        @Override
        public String toString()
        {
            return getName();
        }
    };
New to GrepCode? Check out our FAQ X