[picketlink-commits] Picketlink SVN: r1247 - in social/trunk/openid: src/main/java/org/picketlink/social/openid/auth and 1 other directory.

picketlink-commits at lists.jboss.org picketlink-commits at lists.jboss.org
Thu Sep 22 14:54:35 EDT 2011


Author: anil.saldhana at jboss.com
Date: 2011-09-22 14:54:35 -0400 (Thu, 22 Sep 2011)
New Revision: 1247

Added:
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java
Modified:
   social/trunk/openid/pom.xml
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java
   social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java
Log:
refactor openid int

Modified: social/trunk/openid/pom.xml
===================================================================
--- social/trunk/openid/pom.xml	2011-09-22 18:54:06 UTC (rev 1246)
+++ social/trunk/openid/pom.xml	2011-09-22 18:54:35 UTC (rev 1247)
@@ -81,12 +81,12 @@
       <dependency>
          <groupId>org.picketlink</groupId>
          <artifactId>picketlink-fed-model</artifactId>
-         <version>${project.version}</version>
+         <version>2.0.1.final</version>
       </dependency>
       <dependency>
          <groupId>org.picketlink</groupId>
          <artifactId>picketlink-web</artifactId>
-         <version>${project.version}</version>
+         <version>2.0.1.final</version>
       </dependency>
       <dependency>
          <groupId>org.openid4java</groupId>

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java	2011-09-22 18:54:06 UTC (rev 1246)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDConsumerAuthenticator.java	2011-09-22 18:54:35 UTC (rev 1247)
@@ -22,11 +22,9 @@
 package org.picketlink.social.openid.auth;
 
 import java.io.IOException;
-import java.net.URL;
 import java.security.Principal;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -38,24 +36,8 @@
 import org.apache.catalina.connector.Request;
 import org.apache.catalina.connector.Response;
 import org.apache.catalina.deploy.LoginConfig;
-import org.apache.catalina.realm.GenericPrincipal;
 import org.apache.log4j.Logger;
-import org.openid4java.consumer.ConsumerException;
-import org.openid4java.consumer.ConsumerManager;
-import org.openid4java.consumer.VerificationResult;
-import org.openid4java.discovery.DiscoveryException;
-import org.openid4java.discovery.DiscoveryInformation;
-import org.openid4java.discovery.Identifier;
-import org.openid4java.message.AuthRequest;
-import org.openid4java.message.AuthSuccess;
-import org.openid4java.message.MessageException;
-import org.openid4java.message.ParameterList;
-import org.openid4java.message.ax.AxMessage;
-import org.openid4java.message.ax.FetchRequest;
-import org.openid4java.message.ax.FetchResponse;
 import org.picketlink.identity.federation.core.util.StringUtil;
-import org.picketlink.social.openid.OpenIdPrincipal;
-import org.picketlink.social.openid.constants.OpenIDAliasMapper;
 
 /**
  * Tomcat Authenticator that provides OpenID based authentication
@@ -65,56 +47,33 @@
 public class OpenIDConsumerAuthenticator extends FormAuthenticator
 {
    protected static Logger log = Logger.getLogger(OpenIDConsumerAuthenticator.class);
-   protected boolean trace = log.isTraceEnabled();
-   
-   private enum Providers
-   {
-      GOOGLE("https://www.google.com/accounts/o8/id"),
-      YAHOO("https://me.yahoo.com/"),
-      MYSPACE("myspace.com"),
-      MYOPENID("https://myopenid.com/");
-      
-      private String name;
+   protected boolean trace = log.isTraceEnabled(); 
 
-      Providers(String name)
-      {
-         this.name = name;
-      }
-      String get()
-      {
-         return name;
-      }
-   }
    private enum STATES { AUTH, AUTHZ, FINISH};
-   
+
    public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
-   
+
    public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
    public static String EMPTY_PASSWORD = "EMPTY";
-   
-   private ConsumerManager openIdConsumerManager = null;
-   
-   private String openIdServiceUrl = null;
-   
+
    private String returnURL = null;
-   
+
    private String requiredAttributes = "name,email,ax_firstName,ax_lastName,ax_fullName";
-   
+
    private String optionalAttributes = null;
-   
-   private FetchRequest fetchRequest;
+
    protected List<String> roles = new ArrayList<String>();
-   
+
    //Whether the authenticator has to to save and restore request
    protected boolean saveRestoreRequest = true;
-   
-   protected boolean initialized = false;
-   
-  public void setReturnURL(String returnURL)
-  {
-     this.returnURL = returnURL;
-  }
 
+   protected OpenIDProcessor processor = null;
+
+   public void setReturnURL(String returnURL)
+   {
+      this.returnURL = returnURL;
+   }
+
    public void setRequiredAttributes(String requiredAttributes)
    {
       this.requiredAttributes = requiredAttributes;
@@ -141,40 +100,20 @@
       }
    }
 
-   public void initialize() throws MessageException, ConsumerException
+   public boolean authenticate(HttpServletRequest request, HttpServletResponse response, LoginConfig loginConfig) throws IOException
    {
-      if(openIdConsumerManager == null)
-         openIdConsumerManager = new ConsumerManager();
-      
-      fetchRequest = FetchRequest.createFetchRequest();
-      //Work on the required attributes
-      if(StringUtil.isNotNull(requiredAttributes))
-      {
-         List<String> tokens = StringUtil.tokenize(requiredAttributes);
-         for(String token: tokens)
-         {
-            fetchRequest.addAttribute(token, OpenIDAliasMapper.get(token),true);
-         }
-      }
-      //Work on the optional attributes
-      if(StringUtil.isNotNull(optionalAttributes))
-      {
-         List<String> tokens = StringUtil.tokenize(optionalAttributes);
-         for(String token: tokens)
-         {
-            String type = OpenIDAliasMapper.get(token);
-            if(type == null)
-            {
-               log.error("Null Type returned for " + token);
-            }
-            fetchRequest.addAttribute(token, type,false);
-         }
-      }
-      initialized = true;
+      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)response, loginConfig);
    }
-
+   
    public boolean authenticate(Request request, Response response, LoginConfig loginConfig) throws IOException
    {  
+      if(processor == null)
+         processor = new OpenIDProcessor(returnURL, requiredAttributes, optionalAttributes);
+
       Principal userPrincipal = request.getUserPrincipal();
       if(userPrincipal != null)
       {
@@ -182,161 +121,43 @@
             log.trace("Logged in as:"+userPrincipal);
          return true;
       }
-      
-      if(!initialized)
+
+      if(!processor.isInitialized())
       {
          try
          {
-            initialize();
+            processor.initialize(roles);
          }
          catch (Exception e)
-         {
-            throw new RuntimeException(e); 
+         { 
+            throw new RuntimeException(e);
          }
       }
-      
+
       HttpSession httpSession = request.getSession();
       String state = (String) httpSession.getAttribute("STATE");
       if(trace) log.trace("state="+ state);
-      
+
       if( STATES.FINISH.name().equals(state))
          return true;
-      
+
       if( state == null || state.isEmpty())
       { 
-         return processSend(request, response, loginConfig);
+         return processor.prepareAndSendAuthRequest(request, response);
       } 
       //We have sent an auth request
       if( state.equals(STATES.AUTH.name()))
       {
-         return processIncomingResult(request, response, loginConfig);
-      }
-      return false;
-   } 
-   
-   @SuppressWarnings("unchecked")
-   protected boolean processSend(Request request, Response response, LoginConfig loginConfig) throws IOException
-   { 
-      //Figure out the service url
-      String service = request.getParameter("service");
-      determineServiceUrl(service);
-      
-      String openId = openIdServiceUrl;
-      Session session = request.getSessionInternal(true);
-      if(openId != null)
-      {
+         Session session = request.getSessionInternal(true);
          if (saveRestoreRequest)
          {
             this.saveRequest(request, session);
          }
-         session.setNote("openid", openId);
-         List<DiscoveryInformation> discoveries;
-         try
-         {
-            discoveries = openIdConsumerManager.discover(openId);
-         }
-         catch (DiscoveryException e)
-         { 
-            throw new RuntimeException(e);
-         }
 
-         DiscoveryInformation discovered = openIdConsumerManager.associate(discoveries);
-         session.setNote("discovery", discovered);
-         try
-         {
-            AuthRequest authReq = openIdConsumerManager.authenticate(discovered, returnURL);
-
-            //Add in required attributes
-            authReq.addExtension(fetchRequest);
-            
-            String url = authReq.getDestinationUrl(true);
-            response.sendRedirect(url);
-            
-            request.getSession().setAttribute("STATE", STATES.AUTH.name());
-            return false;
-         }
-         catch (Exception e)
-         { 
-            throw new RuntimeException(e);
-         }
-      } 
-      return false;
-   }
-   
-   @SuppressWarnings("unchecked")
-   protected boolean processIncomingResult(Request request, Response response, LoginConfig loginConfig) throws IOException
-   {
-      Session session = request.getSessionInternal(false);
-      if(session == null)
-         throw new RuntimeException("wrong lifecycle: session was null");
-      
-      // extract the parameters from the authentication response
-      // (which comes in as a HTTP request from the OpenID provider)
-      ParameterList responseParamList = new ParameterList(request.getParameterMap());
-      // retrieve the previously stored discovery information
-      DiscoveryInformation discovered = (DiscoveryInformation) session.getNote("discovery");
-      if(discovered == null)
-         throw new RuntimeException("discovered information was null");
-      // extract the receiving URL from the HTTP request
-      StringBuffer receivingURL = request.getRequestURL();
-      String queryString = request.getQueryString();
-      if (queryString != null && queryString.length() > 0)
-         receivingURL.append("?").append(request.getQueryString());
-
-      // verify the response; ConsumerManager needs to be the same
-      // (static) instance used to place the authentication request
-      VerificationResult verification;
-      try
-      {
-         verification = openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
-      }
-      catch (Exception e)
-      { 
-         throw new RuntimeException(e);
-      }
-
-      // examine the verification result and extract the verified identifier
-      Identifier identifier = verification.getVerifiedId();
-
-      if (identifier != null)
-      {
-         AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
-
-         Map<String, List<String>> attributes = null;
-         if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX))
-         {
-            FetchResponse fetchResp;
-            try
-            {
-               fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
-            }
-            catch (MessageException e)
-            {
-               throw new RuntimeException(e);
-            }
-
-            attributes = fetchResp.getAttributes();
-         }
-
-         Principal principal = null;
-         OpenIdPrincipal openIDPrincipal = createPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(),
-               attributes);
-         request.getSession().setAttribute("PRINCIPAL", openIDPrincipal);
-         
-         String principalName = openIDPrincipal.getName();
-         cachedPrincipal.set(openIDPrincipal);
-         
-         if(isJBossEnv())
-         {
-            cachedRoles.set(roles);
-            principal = context.getRealm().authenticate(principalName, EMPTY_PASSWORD); 
-         }
-         else
-         { 
-            //Create a Tomcat Generic Principal
-            principal = new GenericPrincipal(getContainer().getRealm(), principalName, null, roles, openIDPrincipal);
-         }
-         
+         Principal principal = processor.processIncomingAuthResult(request, response, 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);
@@ -353,51 +174,4 @@
       }
       return false;
    }
-   
-
-   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)response, loginConfig);
-   }
-
-   private OpenIdPrincipal createPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes)
-   {
-      return new OpenIdPrincipal(identifier, openIdProvider, attributes);
-   }
-   
-   private boolean isJBossEnv()
-   {
-      ClassLoader tcl = SecurityActions.getContextClassLoader();
-      Class<?> clazz = null;
-      try
-      {
-         clazz = tcl.loadClass("org.jboss.system.Service");
-      }
-      catch (ClassNotFoundException e)
-      { 
-      }
-      if( clazz != null )
-         return true;
-      return false;
-   }
-   
-   private void determineServiceUrl(String service)
-   {
-      openIdServiceUrl = Providers.GOOGLE.get();
-      if(StringUtil.isNotNull(service))
-      {
-         if("google".equals(service))
-            openIdServiceUrl = Providers.GOOGLE.get();
-         else if("yahoo".equals(service))
-            openIdServiceUrl = Providers.YAHOO.get();
-         else if("myspace".equals(service))
-            openIdServiceUrl = Providers.MYSPACE.get();
-         else if("myopenid".equals(service))
-            openIdServiceUrl = Providers.MYOPENID.get();
-      }
-   }
 }
\ No newline at end of file

Modified: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java	2011-09-22 18:54:06 UTC (rev 1246)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDLoginModule.java	2011-09-22 18:54:35 UTC (rev 1247)
@@ -33,7 +33,7 @@
 import org.jboss.security.auth.spi.UsernamePasswordLoginModule;
 
 /**
- * A {@link LoginModule} for JBoss environment
+ * A {@link LoginModule} for JBoss environment to support OpenID
  * @author Anil Saldhana
  * @since May 19, 2011
  */
@@ -42,13 +42,13 @@
    @Override
    protected Principal getIdentity()
    {
-      return OpenIDConsumerAuthenticator.cachedPrincipal.get();
+      return OpenIDProcessor.cachedPrincipal.get();
    }
 
    @Override
    protected String getUsersPassword() throws LoginException
    {
-      return OpenIDConsumerAuthenticator.EMPTY_PASSWORD;
+      return OpenIDProcessor.EMPTY_PASSWORD;
    }
 
    @Override
@@ -56,7 +56,7 @@
    {   
       Group group = new SimpleGroup("Roles"); 
 
-      List<String> roles = OpenIDConsumerAuthenticator.cachedRoles.get();
+      List<String> roles = OpenIDProcessor.cachedRoles.get();
 
       if(roles != null)
       {

Added: social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java
===================================================================
--- social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java	                        (rev 0)
+++ social/trunk/openid/src/main/java/org/picketlink/social/openid/auth/OpenIDProcessor.java	2011-09-22 18:54:35 UTC (rev 1247)
@@ -0,0 +1,326 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2011, Red Hat Middleware LLC, 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.picketlink.social.openid.auth;
+
+import java.io.IOException;
+import java.net.URL;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.catalina.Realm;
+import org.apache.catalina.Session;
+import org.apache.catalina.connector.Request;
+import org.apache.catalina.connector.Response;
+import org.apache.catalina.realm.GenericPrincipal;
+import org.apache.log4j.Logger;
+import org.openid4java.consumer.ConsumerException;
+import org.openid4java.consumer.ConsumerManager;
+import org.openid4java.consumer.VerificationResult;
+import org.openid4java.discovery.DiscoveryException;
+import org.openid4java.discovery.DiscoveryInformation;
+import org.openid4java.discovery.Identifier;
+import org.openid4java.message.AuthRequest;
+import org.openid4java.message.AuthSuccess;
+import org.openid4java.message.MessageException;
+import org.openid4java.message.ParameterList;
+import org.openid4java.message.ax.AxMessage;
+import org.openid4java.message.ax.FetchRequest;
+import org.openid4java.message.ax.FetchResponse;
+import org.picketlink.identity.federation.core.util.StringUtil;
+import org.picketlink.social.openid.OpenIdPrincipal;
+import org.picketlink.social.openid.constants.OpenIDAliasMapper;
+
+/**
+ * Processor for the OpenID interaction
+ * @author Anil Saldhana
+ * @since Sep 22, 2011
+ */
+public class OpenIDProcessor
+{
+   protected static Logger log = Logger.getLogger(OpenIDProcessor.class);
+   protected boolean trace = log.isTraceEnabled();
+   
+   public static final String AUTH_TYPE = "authType";
+   
+   private ConsumerManager openIdConsumerManager;
+   private FetchRequest fetchRequest;
+   
+   private String openIdServiceUrl = null;
+   
+   private String returnURL = null;
+   
+   private String requiredAttributes,optionalAttributes = null;
+   
+   private boolean initialized = false;
+
+   protected List<String> roles = new ArrayList<String>();
+   
+   public static ThreadLocal<Principal> cachedPrincipal = new ThreadLocal<Principal>();
+   
+   public static ThreadLocal<List<String>> cachedRoles = new ThreadLocal<List<String>>();
+   public static String EMPTY_PASSWORD = "EMPTY";
+
+   private enum STATES { AUTH, AUTHZ, FINISH};
+   
+   private enum Providers
+   {
+      GOOGLE("https://www.google.com/accounts/o8/id"),
+      YAHOO("https://me.yahoo.com/"),
+      MYSPACE("myspace.com"),
+      MYOPENID("https://myopenid.com/");
+      
+      private String name;
+
+      Providers(String name)
+      {
+         this.name = name;
+      }
+      String get()
+      {
+         return name;
+      }
+   }
+   
+   public OpenIDProcessor(String theReturnURL, String requiredAttributes, String optionalAttributes)
+   {
+      this.returnURL = theReturnURL;
+      this.requiredAttributes = requiredAttributes;
+      this.optionalAttributes = optionalAttributes;
+   }
+   
+   /**
+    * Return whether the processor has initialized
+    * @return
+    */
+   public boolean isInitialized()
+   {
+      return initialized;
+   }
+   
+   /**
+    * Initialize the processor
+    * @param requiredRoles
+    * @throws MessageException
+    * @throws ConsumerException
+    */
+   public void initialize(List<String> requiredRoles) throws MessageException, ConsumerException
+   {
+      if(openIdConsumerManager == null)
+         openIdConsumerManager = new ConsumerManager();
+      
+      fetchRequest = FetchRequest.createFetchRequest();
+      //Work on the required attributes
+      if(StringUtil.isNotNull(requiredAttributes))
+      {
+         List<String> tokens = StringUtil.tokenize(requiredAttributes);
+         for(String token: tokens)
+         {
+            fetchRequest.addAttribute(token, OpenIDAliasMapper.get(token),true);
+         }
+      }
+      //Work on the optional attributes
+      if(StringUtil.isNotNull(optionalAttributes))
+      {
+         List<String> tokens = StringUtil.tokenize(optionalAttributes);
+         for(String token: tokens)
+         {
+            String type = OpenIDAliasMapper.get(token);
+            if(type == null)
+            {
+               log.error("Null Type returned for " + token);
+            }
+            fetchRequest.addAttribute(token, type,false);
+         }
+      }
+      
+      roles.addAll(requiredRoles);
+      initialized = true;
+   }
+   
+   @SuppressWarnings("unchecked")
+   public boolean prepareAndSendAuthRequest(Request request, Response response) throws IOException
+   { 
+      //Figure out the service url
+      String authType = request.getParameter(AUTH_TYPE);
+      if(authType == null || authType.length() == 0)
+      {
+         authType = (String) request.getSession().getAttribute(AUTH_TYPE);
+      }
+      determineServiceUrl(authType);
+      
+      String openId = openIdServiceUrl;
+      Session session = request.getSessionInternal(true);
+      if(openId != null)
+      { 
+         session.setNote("openid", openId);
+         List<DiscoveryInformation> discoveries;
+         try
+         {
+            discoveries = openIdConsumerManager.discover(openId);
+         }
+         catch (DiscoveryException e)
+         { 
+            throw new RuntimeException(e);
+         }
+
+         DiscoveryInformation discovered = openIdConsumerManager.associate(discoveries);
+         session.setNote("discovery", discovered);
+         try
+         {
+            AuthRequest authReq = openIdConsumerManager.authenticate(discovered, returnURL);
+
+            //Add in required attributes
+            authReq.addExtension(fetchRequest);
+            
+            String url = authReq.getDestinationUrl(true);
+            response.sendRedirect(url);
+            
+            request.getSession().setAttribute("STATE", STATES.AUTH.name());
+            return false;
+         }
+         catch (Exception e)
+         { 
+            throw new RuntimeException(e);
+         }
+      } 
+      return false;
+   }
+   
+   @SuppressWarnings("unchecked")
+   public Principal processIncomingAuthResult(Request request, Response response, Realm realm) throws IOException
+   {
+      Principal principal = null;
+      Session session = request.getSessionInternal(false);
+      if(session == null)
+         throw new RuntimeException("wrong lifecycle: session was null");
+      
+      // extract the parameters from the authentication response
+      // (which comes in as a HTTP request from the OpenID provider)
+      ParameterList responseParamList = new ParameterList(request.getParameterMap());
+      // retrieve the previously stored discovery information
+      DiscoveryInformation discovered = (DiscoveryInformation) session.getNote("discovery");
+      if(discovered == null)
+         throw new RuntimeException("discovered information was null");
+      // extract the receiving URL from the HTTP request
+      StringBuffer receivingURL = request.getRequestURL();
+      String queryString = request.getQueryString();
+      if (queryString != null && queryString.length() > 0)
+         receivingURL.append("?").append(request.getQueryString());
+
+      // verify the response; ConsumerManager needs to be the same
+      // (static) instance used to place the authentication request
+      VerificationResult verification;
+      try
+      {
+         verification = openIdConsumerManager.verify(receivingURL.toString(), responseParamList, discovered);
+      }
+      catch (Exception e)
+      { 
+         throw new RuntimeException(e);
+      }
+
+      // examine the verification result and extract the verified identifier
+      Identifier identifier = verification.getVerifiedId();
+
+      if (identifier != null)
+      {
+         AuthSuccess authSuccess = (AuthSuccess) verification.getAuthResponse();
+
+         Map<String, List<String>> attributes = null;
+         if (authSuccess.hasExtension(AxMessage.OPENID_NS_AX))
+         {
+            FetchResponse fetchResp;
+            try
+            {
+               fetchResp = (FetchResponse) authSuccess.getExtension(AxMessage.OPENID_NS_AX);
+            }
+            catch (MessageException e)
+            {
+               throw new RuntimeException(e);
+            }
+
+            attributes = fetchResp.getAttributes();
+         }
+
+         OpenIdPrincipal openIDPrincipal = createPrincipal(identifier.getIdentifier(), discovered.getOPEndpoint(),
+               attributes);
+         request.getSession().setAttribute("PRINCIPAL", openIDPrincipal);
+         
+         String principalName = openIDPrincipal.getName();
+         cachedPrincipal.set(openIDPrincipal);
+         
+         if(isJBossEnv())
+         {
+            cachedRoles.set(roles);
+            principal = realm.authenticate(principalName, EMPTY_PASSWORD); 
+         }
+         else
+         { 
+            //Create a Tomcat Generic Principal
+            principal = new GenericPrincipal(realm, principalName, null, roles, openIDPrincipal);
+         }
+
+         if(trace)
+            log.trace("Logged in as:" + principal); 
+      }
+      return principal;
+   }
+
+   private OpenIdPrincipal createPrincipal(String identifier, URL openIdProvider, Map<String, List<String>> attributes)
+   {
+      return new OpenIdPrincipal(identifier, openIdProvider, attributes);
+   }
+   
+   private boolean isJBossEnv()
+   {
+      ClassLoader tcl = SecurityActions.getContextClassLoader();
+      Class<?> clazz = null;
+      try
+      {
+         clazz = tcl.loadClass("org.jboss.system.Service");
+      }
+      catch (ClassNotFoundException e)
+      { 
+      }
+      if( clazz != null )
+         return true;
+      return false;
+   }
+   
+   private void determineServiceUrl(String service)
+   {
+      openIdServiceUrl = Providers.GOOGLE.get();
+      if(StringUtil.isNotNull(service))
+      {
+         if("google".equals(service))
+            openIdServiceUrl = Providers.GOOGLE.get();
+         else if("yahoo".equals(service))
+            openIdServiceUrl = Providers.YAHOO.get();
+         else if("myspace".equals(service))
+            openIdServiceUrl = Providers.MYSPACE.get();
+         else if("myopenid".equals(service))
+            openIdServiceUrl = Providers.MYOPENID.get();
+      }
+   }
+}
\ No newline at end of file



More information about the picketlink-commits mailing list