Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2010, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.as.web.security.jaspi;
 
 import java.util.List;
 import java.util.Set;
 
 

Tomcat authenticator that does JSR-196 (JASPI) authentication.

Author(s):
Anil Saldhana
Stefan Guilhen
 
 @SuppressWarnings("unused")
 public class WebJASPIAuthenticator extends AuthenticatorBase {
 
     protected final String messageLayer = "HttpServlet";
 
 
     protected boolean secureResponse;
 
     @Override
     protected boolean authenticate(Request requestHttpServletResponse responseLoginConfig configthrows IOException {
         boolean result = false;
 
         String authMethod = config.getAuthMethod();
 
         // have we already authenticated someone?
         Principal principal = request.getUserPrincipal();
         String ssoId = (Stringrequest.getNote(.);
         if (principal != null) {
             ..tracef("Already authenticated '%s'"principal.getName());
             // associate the session with any existing SSO session
             if (ssoId != null)
                 associate(ssoIdrequest.getSessionInternal(true));
             return (true);
         }
 
         if ("BASIC".equalsIgnoreCase(authMethod) || "FORM".equalsIgnoreCase(authMethod)) {
             // is there an SSO session against which we can try to reauthenticate?
             if (ssoId != null) {
                 ..tracef("SSO Id %s set; attempting reauthentication"ssoId);
                 /* Try to reauthenticate using data cached by SSO.  If this fails, either the original SSO logon was of
                    DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password),
                    or the realm denied the user's reauthentication for some reason. In either case we have to prompt the
                    user for a logon */
                 if (reauthenticateFromSSO(ssoIdrequest))
                     return true;
            }
        }
        // TODO: change message info to operate on HttpServletResponse, to align with Servlet 3.0
        GenericMessageInfo messageInfo = new GenericMessageInfo();
        messageInfo.setRequestMessage(request);
        messageInfo.setResponseMessage(request.getResponse());
        // put bits of information needed by tomcat server auth modules
        messageInfo.getMap().put("CACHE", String.valueOf());
        messageInfo.getMap().put("javax.security.auth.message.MessagePolicy.isMandatory""true");
        WebJASPICallbackHandler cbh = new WebJASPICallbackHandler();
        String appContext = request.getLocalName() + " " + request.getContextPath();
        Subject clientSubject = new Subject();
        if (sam != null) {
            result = sam.isValid(messageInfoclientSubjectappContextcbh);
        }
        // the authentication process has been a success. We need to register the principal, username, password and roles
        // with the container
        if (result) {
            PasswordValidationCallback pvc = cbh.getPasswordValidationCallback();
            CallerPrincipalCallback cpc = cbh.getCallerPrincipalCallback();
            GroupPrincipalCallback gpc = cbh.getGroupPrincipalCallback();
            // get the client principal from the callback.
            Principal clientPrincipal = cpc.getPrincipal();
            if (clientPrincipal == null) {
                clientPrincipal = new SimplePrincipal(cpc.getName());
            }
            // if the client principal is not a jboss generic principal, we need to build one before registering.
            if (!(clientPrincipal instanceof JBossGenericPrincipal))
                clientPrincipal = this.buildJBossPrincipal(clientSubjectclientPrincipalgpc);
            String passwordString = (pvc != null && pvc.getPassword() != null) ? new String(pvc.getPassword()) : null;
            String passwordUsername = (pvc != null && pvc.getUsername() != null) ? pvc.getUsername() : null;
            this.register(requestresponseclientPrincipalauthMethodpasswordUsernamepasswordString);
            if (this.)
                sam.secureResponse(messageInfonew Subject(), appContextcbh);
        }
        return result;
    }

    

Obtains the fully-qualified name of the class that implements the ServerAuthenticationManager interface.

Returns:
the name of the ServerAuthenticationManager implementation class.
        return ;
    }

    

Sets the fully-qualified name of the class that implements the ServerAuthenticationManager interface.

Parameters:
serverAuthenticationManagerClass the name ServerAuthenticationManager implementation class.
    public void setServerAuthenticationManagerClass(String serverAuthenticationManagerClass) {
        this. = serverAuthenticationManagerClass;
    }

    

Obtains the value of the flag that indicates whether JASPI should be used to secure the HTTP response or not.

Returns:
true if the authenticator is to secure the response; false otherwise.
    public boolean getSecureResponse() {
        return this.;
    }

    

Sets the flag that indicates whether JASPI should be used to secure the HTTP response or not.

Parameters:
secureResponse true if the authenticator is to secure the response; false otherwise.
    public void setSecureResponse(boolean secureResponse) {
        this. = secureResponse;
    }

    

Instantiates and returns the ServerAuthenticationManager implementation.

Returns:
a reference to the instantiated ServerAuthenticationManager instance.
        ServerAuthenticationManager sam = null;
        // if the default authentication manager is to be used, just instantiate it.
        if (this. ==  null) {
            SecurityContext context = SecurityActions.getSecurityContext();
            if (context != null) {
                ..debugf("Instantiating JASPI authentication manager with security domain %s",
                        context.getSecurityDomain());
                sam = new JASPIServerAuthenticationManager(context.getSecurityDomain(), new JBossCallbackHandler());
            }
            else {
                ..debugf("Security context is null, instantiating JASPI authentication manager with default domain");
                sam = new JASPIServerAuthenticationManager();
            }
        }
        // if not, load the configured authentication manager via reflection.
        else {
            Class<?> clazz;
            try {
                clazz = SecurityActions.loadClass(this.);
                sam = (ServerAuthenticationManagerclazz.newInstance();
            } catch (Exception e) {
            }
        }
        return sam;
    }

    

Registers an authenticated Principal and authentication type in our request, in the current session (if there is one), and with our SingleSignOn valve, if there is one. Set the appropriate cookie to be returned.

Parameters:
request the servlet request we are processing.
response the servlet response we are generating.
principal the authenticated Principal to be registered.
authType the authentication type to be registered.
username username used to authenticate (if any).
password password used to authenticate (if any).
    protected void register(Request requestHttpServletResponse responsePrincipal principalString authType,
                            String usernameString password) {
            // Bugzilla 39255: http://issues.apache.org/bugzilla/show_bug.cgi?id=39255
            String name = (principal == null) ? "none" : principal.getName();
            ..tracef("Authenticated '%s' with type '" + authType + "'"nameauthType);
        }
        // cache the authentication information in our request
        request.setAuthType(authType);
        request.setUserPrincipal(principal);
        Session session = request.getSessionInternal(false);
        // cache the authentication information in our session, if any
        if () {
            if (session != null) {
                session.setAuthType(authType);
                session.setPrincipal(principal);
                if (username != null)
                    session.setNote(.username);
                else
                    session.removeNote(.);
                if (password != null)
                    session.setNote(.password);
                else
                    session.removeNote(.);
            }
        }
        // construct a cookie to be returned to the client
        if ( == null)
            return;
        // only create a new SSO entry if the SSO did not already set a note for an existing entry (as it would do with
        // subsequent requests for DIGEST and SSL authenticated contexts).
        String ssoId = (Stringrequest.getNote(.);
        if (ssoId == null) {
            // construct a cookie to be returned to the client.
            ssoId = generateSessionId(new Random());
            Cookie cookie = new Cookie(.ssoId);
            cookie.setMaxAge(-1);
            cookie.setPath("/");
            // Bugzilla 41217
            cookie.setSecure(request.isSecure());
            // Bugzilla 34724
            String ssoDomain = .getCookieDomain();
            if (ssoDomain != null) {
                cookie.setDomain(ssoDomain);
            }
            response.addCookie(cookie);
            // register this principal with our SSO valve.
            .register(ssoIdprincipalauthTypeusernamepassword);
            request.setNote(.ssoId);
        } else {
            // update the SSO session with the latest authentication data.
            .update(ssoIdprincipalauthTypeusernamepassword);
        }
        // fix for Bug 10040: always associate a session with a new SSO registration. SSO entries are only removed from
        // the SSO registry map when associated sessions are destroyed; if a new SSO entry is created above for this
        // request and the user never revisits the context, the SSO entry will never be cleared if we don't associate
        // the session
        if (session == null)
            session = request.getSessionInternal(true);
        .associate(ssoIdsession);
    }
    protected Principal buildJBossPrincipal(Subject subjectPrincipal principalGroupPrincipalCallback gpc) {
        List<Stringroles = new ArrayList<String>();
        // look for roles in the subject first.
        for (Principal p : subject.getPrincipals()) {
            if (p instanceof Group && p.getName().equals("Roles")) {
                Enumeration<? extends Principalmembers = ((Groupp).members();
                while (members.hasMoreElements())
                    roles.add(members.nextElement().getName());
            }
        }
        // check if the group callback contains any roles.
        if (gpc != null && gpc.getGroups() != null) {
            for (String group : gpc.getGroups())
                roles.add(group);
        }
        // look for the roles declared in the deployment descriptor.
        JBossWebRealm realm = (JBossWebRealmthis.getContainer().getRealm();
        Set<StringdescriptorRoles = realm.getPrincipalVersusRolesMap().get(principal.getName());
        if (descriptorRoles != null)
            roles.addAll(descriptorRoles);
        // build and return the JBossGenericPrincipal.
        return new JBossGenericPrincipal(realmprincipal.getName(), nullrolesprincipalnullnullnullsubject);
    }
New to GrepCode? Check out our FAQ X