Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   *
   * Copyright 2013 Red Hat, Inc. and/or its affiliates.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.picketlink.social.openid;
 
 import  org.apache.catalina.Session;
 import  org.apache.catalina.authenticator.Constants;
 import  org.apache.catalina.authenticator.FormAuthenticator;
 import  org.apache.catalina.connector.Request;
 import  org.apache.catalina.connector.Response;
 import  org.apache.catalina.deploy.LoginConfig;
 
 import  javax.servlet.http.HttpServletRequest;
 import  javax.servlet.http.HttpServletResponse;
 import  javax.servlet.http.HttpSession;
 import java.util.List;

Tomcat Authenticator that provides OpenID based authentication

Author(s):
Anil Saldhana
Since:
Sep 17, 2011
 
 public class OpenIDConsumerAuthenticator extends FormAuthenticator {
     protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
     protected boolean trace = .isTraceEnabled();
 
     private enum STATES {
         AUTH, AUTHZ, FINISH
     };
 
     public static ThreadLocal<PrincipalcachedPrincipal = new ThreadLocal<Principal>();
 
     public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
     public static String EMPTY_PASSWORD = "EMPTY";
 
     private String returnURL = null;
 
     private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName,ax_email";
 
     private String optionalAttributes = null;
 
     protected List<Stringroles = new ArrayList<String>();
 
     // Whether the authenticator has to to save and restore request
     protected boolean saveRestoreRequest = true;
 
     protected OpenIDProcessor processor = null;
 
     // Incompatibilities in register() method across JBossWeb versions
     private Method theSuperRegisterMethod = null;
 
     public void setReturnURL(String returnURL) {
         this. = StringUtil.getSystemPropertyAsString(returnURL);
     }
 
     public void setRequiredAttributes(String requiredAttributes) {
         this. = requiredAttributes;
     }
 
     public void setOptionalAttributes(String optionalAttributes) {
         this. = optionalAttributes;
     }
 
     public void setSaveRestoreRequest(boolean saveRestoreRequest) {
         this. = saveRestoreRequest;
     }

    
A comma separated string that represents the roles the web app needs to pass authorization

Parameters:
roleStr
 
     public void setRoleString(String roleStr) {
         if (roleStr == null)
             throw new RuntimeException("Role String is null in configuration");
         List<Stringtokens = StringUtil.tokenize(roleStr);
         for (String token : tokens) {
             .add(token);
        }
    }
    public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig)
            throws IOException {
        if (request instanceof Request == false)
            throw new IOException("Not of type Catalina request");
        if (response instanceof Response == false)
            throw new IOException("Not of type Catalina response");
        return authenticate((Request) request, (Response) responseloginConfig);
    }

    
Authenticate the request

Parameters:
request
response
config
Returns:
Throws:
java.io.IOException
RuntimeException when the response is not of type catalina response object
    public boolean authenticate(Request request, HttpServletResponse response, LoginConfig configthrows IOException {
        if (response instanceof Response) {
            Response catalinaResponse = (Response) response;
            return authenticate(requestcatalinaResponseconfig);
        }
        throw new RuntimeException("Wrong type of response:" + response);
    }
    public boolean authenticate(Request request, Response response, LoginConfig loginConfigthrows IOException {
        if ( == null)
        Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal != null) {
            if ()
                .trace("Logged in as:" + userPrincipal);
            return true;
        }
        if (!.isInitialized()) {
            try {
                .initialize();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        HttpSession httpSession = request.getSession();
        String state = (StringhttpSession.getAttribute("STATE");
        if ()
            .trace("state=" + state);
        if (..name().equals(state))
            return true;
        if (state == null || state.isEmpty()) {
            return .prepareAndSendAuthRequest(requestresponse);
        }
        // We have sent an auth request
        if (state.equals(..name())) {
            Session session = request.getSessionInternal(true);
            if () {
                this.saveRequest(requestsession);
            }
            Principal principal = .processIncomingAuthResult(requestresponse, context.getRealm());
            if (principal == null)
                throw new RuntimeException("Principal was null. Maybe login modules need to be configured properly.");
            String principalName = principal.getName();
            request.getSessionInternal().setNote(Constants.SESS_USERNAME_NOTE, principalName);
            request.getSessionInternal().setNote(Constants.SESS_PASSWORD_NOTE, "");
            request.setUserPrincipal(principal);
            if () {
                this.restoreRequest(requestrequest.getSessionInternal());
            }
            if ()
                .trace("Logged in as:" + principal);
            registerWithAuthenticatorBase(requestresponseprincipalprincipalName);
            request.getSession().setAttribute("STATE"..name());
            return true;
        }
        return false;
    }
    protected void registerWithAuthenticatorBase(Request request, Response responsePrincipal principalString userName) {
        try {
            register(requestresponseprincipal, Constants.FORM_METHOD, userName"");
        } catch (NoSuchMethodError nse) {
            if ( == null) {
                Class<?>[] args = new Class[] { Request.class, HttpServletResponse.classPrincipal.classString.class,
                        String.classString.class };
                Class<?> superClass = getClass().getSuperclass();
                 = SecurityActions.getMethod(superClass"register"args);
            }
            if ( != null) {
                Object[] objectArgs = new Object[] { requestresponse.getResponse(), principal, Constants.FORM_METHOD,
                        userName. };
                try {
                    .invoke(thisobjectArgs);
                } catch (Exception e) {
                    .error("Unable to register:"e);
                }
            }
        }
    }
New to GrepCode? Check out our FAQ X