⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 openidconsumer.java

📁 开源的OpenId的一个java实现
💻 JAVA
字号:
/*
 * Copyright 2005-2008 WSO2, Inc. (http://wso2.com)
 *
 * 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.wso2.solutions.identity.relyingparty.openid;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.OpenIDException;
import org.openid4java.consumer.ConsumerException;
import org.openid4java.consumer.ConsumerManager;
import org.openid4java.consumer.InMemoryConsumerAssociationStore;
import org.openid4java.consumer.InMemoryNonceVerifier;
import org.openid4java.consumer.VerificationResult;
import org.openid4java.discovery.DiscoveryInformation;
import org.openid4java.discovery.Identifier;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.AuthSuccess;
import org.openid4java.message.Message;
import org.openid4java.message.ParameterList;
import org.wso2.solutions.identity.IdentityConstants;
import org.wso2.solutions.identity.relyingparty.RelyingPartyException;
import org.wso2.solutions.identity.relyingparty.TokenVerifierConstants;
import org.wso2.solutions.identity.relyingparty.openid.extensions.OpenIDExtension;
import org.wso2.solutions.identity.relyingparty.openid.extensions.OpenIDInfoCardExtension;

public class OpenIDConsumer {

    private ConsumerManager manager;
    private static OpenIDConsumer consumer;

    private static Log log = LogFactory.getLog(OpenIDConsumer.class);

    /**
     * Creates an instance of OpenIDConsumer
     * @throws RelyingPartyException
     */
    private OpenIDConsumer() throws RelyingPartyException {

        // Instantiate a ConsumerManager object.
        try {
            manager = new ConsumerManager();
        } catch (ConsumerException e) {
            log.error(e.getMessage());
            // Present error to the user
            throw new RelyingPartyException(
                    IdentityConstants.ErrorCodes.RP_INITIATION_FAILED, e);
        }
        manager.setAssociations(new InMemoryConsumerAssociationStore());
        manager.setNonceVerifier(new InMemoryNonceVerifier(5000));

        // Not enforcing RP realm discovery
        // since this new feature is not deployed in openid4java.
        manager.getRealmVerifier().setEnforceRpId(false);
    }

    /**
     * @return An instance of OpenIDConsumer
     * @throws RelyingPartyException
     */
    public static OpenIDConsumer getInstance() throws RelyingPartyException {

        if (consumer == null)
            consumer = new OpenIDConsumer();

        return consumer;
    }

    /**
     * Authenticates the OpenID url.
     * @param request OpenID authentication request.
     */
    public void doOpenIDAuthentication(OpenIDAuthenticationRequest request)
            throws RelyingPartyException {

        if (request == null)
            throw new RelyingPartyException(
                    IdentityConstants.ErrorCodes.INVALID_OPENID_AUTHENTICATION_REQUEST);

        if (request.getReturnUrl() == null)
            request.setReturnUrl((String) request.getRequest().getParameter(
                    "returnUrl"));

        authRequest(request);
    }

    /**
     * Populates session attributes.
     * @param request HttpServletRequest
     */
    public void setSessionAttributes(HttpServletRequest request)
            throws RelyingPartyException {

        ParameterList response = null;
        AuthSuccess authSuccess = null;
        String mode = null;
        OpenIDExtension extension = null;

        try {
            // Extract the parameters from the authentication response
            // (which comes in as a HTTP request from the OpenID provider)
            response = new ParameterList(request.getParameterMap());

            mode = response
                    .getParameterValue(IdentityConstants.OpenId.ATTR_MODE);

            if (mode != null && IdentityConstants.OpenId.CANCEL.equals(mode))
                // User has denied sending his profile info :(
                throw new RelyingPartyException(
                        IdentityConstants.ErrorCodes.OPENID_AUTHENTICATION_FAILED);

            authSuccess = (AuthSuccess) verifyOpenID(request, response);

            request.setAttribute(IdentityConstants.OpenId.OPENID_IDENTIFIER,
                    authSuccess.getIdentity());

            for (Object alias : authSuccess.getExtensions()) {
                extension = OpenIDExtensionFactory.getInstance().getExtension(
                        (String) alias, authSuccess);
                if (extension != null)
                    extension.setSessionAttributes(request);
            }

            request.setAttribute(TokenVerifierConstants.SERVLET_ATTR_STATE,
                    TokenVerifierConstants.STATE_SUCCESS);

        } catch (OpenIDException e) {
            log.error(e.getMessage());
            // Present error to the user.
            throw new RelyingPartyException(
                    IdentityConstants.ErrorCodes.OPENID_AUTHENTICATION_FAILED,
                    e);
        }
    }

    /**
     * Populates session attributes
     * @param request HttpServletRequest
     * @throws RelyingPartyException
     */
    public void setInfocardSessionAttributes(HttpServletRequest request)
            throws RelyingPartyException {
        new OpenIDInfoCardExtension().setSessionAttributes(request);
    }

    /**
     * @param request
     * @param openidResp
     * @return
     * @throws OpenIDException
     * @throws RelyingPartyException
     */
    public Message verifyOpenID(HttpServletRequest request,
            ParameterList openidResp) throws OpenIDException,
            RelyingPartyException {

        DiscoveryInformation discovered = null;
        StringBuffer receivingURL = null;
        String queryString = null;
        VerificationResult verification = null;
        Identifier verified = null;
        HttpSession session = null;

        session = request.getSession();

        // Retrieve the previously stored discovery information
        discovered = (DiscoveryInformation) session
                .getAttribute(IdentityConstants.OpenId.DISC);

        receivingURL = request.getRequestURL();
        queryString = request.getQueryString();

        if (queryString != null && queryString.length() > 0)
            receivingURL.append("?").append(request.getQueryString());

        // Verify the response
        verification = manager.verify(receivingURL.toString(), openidResp,
                discovered);

        // Examine the verification result and extract the verified
        // identifier
        verified = verification.getVerifiedId();

        if (verified == null)
            throw new RelyingPartyException(
                    IdentityConstants.ErrorCodes.OPENID_VERIFICATION_FAILED);

        return verification.getAuthResponse();
    }

    /**
     * Authenticates the OpenID url.
     * @param request OpenID authentication request.
     * @throws RelyingPartyException
     */
    protected void authRequest(OpenIDAuthenticationRequest request)
            throws RelyingPartyException {

        List discoveries = null;
        DiscoveryInformation discovered = null;

        try {
            // Perform discovery on the user-supplied identifier
            discoveries = manager.discover(request.getOpenIDUrl());

            // Attempt to associate with the OpenID provider
            // and retrieve one service end-point for authentication
            discovered = manager.associate(discoveries);

            // Store the discovery information in the user's session
            request.getRequest().getSession().setAttribute(
                    IdentityConstants.OpenId.DISC, discovered);

            // Obtain a AuthRequest message to be sent to the OpenID provider
            AuthRequest authReq = manager.authenticate(discovered, request
                    .getReturnUrl());

            for (OpenIDRequestType type : request.getRequestTypes()) {
                authReq.addExtension(OpenIDExtensionFactory.getInstance()
                        .getExtension(type).getMessageExtension(request));
            }

            // Redirect to the OpenID provider server for authentication.
            try {
                request.getReponse().sendRedirect(
                        authReq.getDestinationUrl(true));
            } catch (IOException e) {
                log.error(e.getMessage());
                throw new RelyingPartyException(e.getMessage(), e);
            }

        } catch (OpenIDException e) {
            log.error(e.getMessage());
            // Present error to the user
            throw new RelyingPartyException(
                    IdentityConstants.ErrorCodes.INVALID_OPENID, e);
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -