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.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.picketlink.social.standalone.oauth.OpenIDAliasMapper;
 import  org.picketlink.social.standalone.oauth.OpenIdPrincipal;
 
 import  javax.servlet.http.HttpServletResponse;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;

Processor for the OpenID interaction

Author(s):
Anil Saldhana
Since:
Sep 22, 2011
 
 public class OpenIDProcessor {
     protected static Logger log = Logger.getLogger(OpenIDProcessor.class);
     protected boolean trace = .isTraceEnabled();
 
     public static final String AUTH_TYPE = "authType";
 
     private FetchRequest fetchRequest;
 
     private String openIdServiceUrl = null;
 
     private String returnURL = null;
 
     private String requiredAttributesoptionalAttributes = null;
 
     private boolean initialized = false;
 
     protected List<Stringroles = new ArrayList<String>();
 
     public static ThreadLocal<PrincipalcachedPrincipal = 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;
         }
 
         String get() {
             return ;
         }
     }
 
    public OpenIDProcessor(String theReturnURLString requiredAttributesString optionalAttributes) {
        this. = theReturnURL;
        this. = requiredAttributes;
        this. = optionalAttributes;
    }

    
Return whether the processor has initialized

Returns:
    public boolean isInitialized() {
        return ;
    }

    
Initialize the processor

Parameters:
requiredRoles
Throws:
MessageException
ConsumerException
    public void initialize(List<StringrequiredRolesthrows MessageExceptionConsumerException {
        if ( == null)
             = new ConsumerManager();
         = FetchRequest.createFetchRequest();
        // Work on the required attributes
        if (StringUtil.isNotNull()) {
            List<Stringtokens = StringUtil.tokenize();
            for (String token : tokens) {
                .addAttribute(token, OpenIDAliasMapper.get(token), true);
            }
        }
        // Work on the optional attributes
        if (StringUtil.isNotNull()) {
            List<Stringtokens = StringUtil.tokenize();
            for (String token : tokens) {
                String type = OpenIDAliasMapper.get(token);
                if (type == null) {
                    .error("Null Type returned for " + token);
                }
                .addAttribute(tokentypefalse);
            }
        }
        .addAll(requiredRoles);
         = true;
    }
    @SuppressWarnings("unchecked")
    public boolean prepareAndSendAuthRequest(Request request, Response responsethrows IOException {
        // Figure out the service url
        String authType = request.getParameter();
        if (authType == null || authType.length() == 0) {
            authType = (Stringrequest.getSession().getAttribute();
        }
        determineServiceUrl(authType);
        String openId = ;
        Session session = request.getSessionInternal(true);
        if (openId != null) {
            session.setNote("openid"openId);
            List<DiscoveryInformationdiscoveries;
            try {
                discoveries = .discover(openId);
            } catch (DiscoveryException e) {
                throw new RuntimeException(e);
            }
            DiscoveryInformation discovered = .associate(discoveries);
            session.setNote("discovery"discovered);
            try {
                AuthRequest authReq = .authenticate(discovered);
                // Add in required attributes
                authReq.addExtension();
                String url = authReq.getDestinationUrl(true);
                response.sendRedirect(url);
                request.getSession().setAttribute("STATE"..name());
                return false;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }
    @SuppressWarnings("unchecked")
    public Principal processIncomingAuthResult(Request request, Response response, Realm realmthrows 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 = (DiscoveryInformationsession.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 = .verify(receivingURL.toString(), responseParamListdiscovered);
        } 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 = (AuthSuccessverification.getAuthResponse();
            Map<StringList<String>> attributes = null;
            if (authSuccess.hasExtension(.)) {
                FetchResponse fetchResp;
                try {
                    fetchResp = (FetchResponseauthSuccess.getExtension(.);
                } 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();
            .set(openIDPrincipal);
            if (isJBossEnv()) {
                .set();
                principal = realm.authenticate(principalName);
            } else {
                // Create a Tomcat Generic Principal
                principal = new GenericPrincipal(realmprincipalNamenullopenIDPrincipal);
            }
            if ()
                .trace("Logged in as:" + principal);
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        }
        return principal;
    }
    private OpenIdPrincipal createPrincipal(String identifierURL openIdProviderMap<StringList<String>> attributes) {
        return new OpenIdPrincipal(identifieropenIdProviderattributes);
    }
    private boolean isJBossEnv() {
        Class<?> clazz = SecurityActions.loadClass(getClass(), "org.jboss.as.web.WebServer");
        if (clazz == null)
            clazz = SecurityActions.loadClass(getClass(), "org.jboss.system.Service");
        if (clazz != null)
            return true;
        return false;
    }
    private void determineServiceUrl(String service) {
         = ..get();
        if (StringUtil.isNotNull(service)) {
            if ("google".equals(service))
                 = ..get();
            else if ("yahoo".equals(service))
                 = ..get();
            else if ("myspace".equals(service))
                 = ..get();
            else if ("myopenid".equals(service))
                 = ..get();
        }
    }
New to GrepCode? Check out our FAQ X