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

📄 openidutil.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.openid;

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.message.AuthRequest;
import org.openid4java.message.MessageException;
import org.openid4java.message.ParameterList;
import org.wso2.solutions.identity.IdentityConstants;
import org.wso2.solutions.identity.IdentityProviderException;
import org.wso2.solutions.identity.UserStore;
import org.wso2.solutions.identity.openid.extensions.OpenIDPape;
import org.wso2.utils.ServerConfiguration;

public class OpenIDUtil {

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

    private static final Set<Character> UNRESERVED_CHARACTERS = new HashSet<Character>();

    private static Map<String, String> axMapping = new HashMap<String, String>();

    static {
        for (char c = 'a'; c <= 'z'; c++)
            UNRESERVED_CHARACTERS.add(Character.valueOf(c));

        for (char c = 'A'; c <= 'A'; c++)
            UNRESERVED_CHARACTERS.add(Character.valueOf(c));

        for (char c = '0'; c <= '9'; c++)
            UNRESERVED_CHARACTERS.add(Character.valueOf(c));

        UNRESERVED_CHARACTERS.add(Character.valueOf('-'));
        UNRESERVED_CHARACTERS.add(Character.valueOf('.'));
        UNRESERVED_CHARACTERS.add(Character.valueOf('_'));
        UNRESERVED_CHARACTERS.add(Character.valueOf('~'));

        axMapping.put(IdentityConstants.CLAIM_EMAIL_ADDRESS,
                IdentityConstants.OpenId.ExchangeAttributes.EMAIL_NS);
        axMapping.put(IdentityConstants.CLAIM_POSTAL_CODE,
                IdentityConstants.OpenId.ExchangeAttributes.POSTAL_CODE_NS);
        axMapping.put(IdentityConstants.CLAIM_NICKNAME,
                IdentityConstants.OpenId.ExchangeAttributes.NICK_NAME_NS);
        axMapping.put(IdentityConstants.CLAIM_COUNTRY,
                IdentityConstants.OpenId.ExchangeAttributes.COUNTRY_NS);
        axMapping.put(IdentityConstants.OpenId.SimpleRegAttributes.FULL_NAME,
                IdentityConstants.OpenId.ExchangeAttributes.FULL_NAME_NS);
        axMapping.put(IdentityConstants.OpenId.SimpleRegAttributes.DOB_NS,
                IdentityConstants.OpenId.ExchangeAttributes.DOB_NS);
        axMapping.put(IdentityConstants.OpenId.SimpleRegAttributes.TIMEZONE_NS,
                IdentityConstants.OpenId.ExchangeAttributes.TIMEZONE_NS);
        axMapping.put(IdentityConstants.OpenId.SimpleRegAttributes.GENDER_NS,
                IdentityConstants.OpenId.ExchangeAttributes.GENDER_NS);
        axMapping.put(IdentityConstants.OpenId.SimpleRegAttributes.LANGUAGE_NS,
                IdentityConstants.OpenId.ExchangeAttributes.LANGUAGE_NS);
    }

    /**
     * Find the user name corresponding to the given OpenID.
     * @param openId User's OpenID
     * @return User name corresponding the given OpenID.
     * @throws IdentityProviderException
     */
    public static String getUserName(String openId)
            throws IdentityProviderException {

        UserStore userStore = null;
        List<String> users = null;

        userStore = UserStore.getInstance();
        users = userStore.getAllUserNames();

        if (users == null)
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.NO_USERS_FOUND);

        Map<String, String> mapValues = null;
        Iterator<String> iterator = null;

        iterator = users.iterator();

        while (iterator.hasNext()) {

            String user = iterator.next();
            mapValues = userStore.getClaimValues(user, null);

            if (mapValues != null && !mapValues.isEmpty()) {
                // User has defined claims!
                String claimId = (String) mapValues
                        .get(IdentityConstants.CLAIM_OPENID);
                if (claimId != null && claimId.equals(openId)) {
                    return user;
                }
            }
        }
        return null;
    }

    /**
     * Generate OpenID for a given user.
     * @param user User
     * @return Generated OpenID
     * @throws IdentityProviderException
     */
    public static String generateOpenID(String user)
            throws IdentityProviderException {

        ServerConfiguration serverConfig = null;
        String openIDServerUrl = null;
        String openID = null;
        URI uri = null;
        URL url = null;

        serverConfig = ServerConfiguration.getInstance();
        openIDServerUrl = serverConfig.getFirstProperty("OpenIDServerUrl");

        user = normalizeUrlEncoding(user);

        openID = openIDServerUrl + "/user/" + user;

        try {
            uri = new URI(openID);
        } catch (URISyntaxException e) {
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.INVALID_USERNAME_FOR_OPENID);
        }

        try {
            url = uri.normalize().toURL();
            if (url.getQuery() != null || url.getRef() != null)
                throw new IdentityProviderException(
                        IdentityConstants.ErrorCodes.INVALID_USERNAME_FOR_OPENID);
        } catch (MalformedURLException e) {
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.INVALID_USERNAME_FOR_OPENID);
        }

        openID = url.toString();

        log.info("OpenID generated : " + openID);

        return openID;
    }

    /**
     * Check whether the given user exists in the system.
     * @param userName User name.
     * @return
     */
    public static boolean isUserExist(String userName) {

        UserStore userStore = null;
        List<String> users = null;
        Iterator<String> iterator = null;

        try {
            userStore = UserStore.getInstance();
            users = userStore.getAllUserNames();
            iterator = users.iterator();

            String user = null;

            while (iterator.hasNext()) {
                user = iterator.next();
                if (user.equals(userName))
                    return true;
            }
        } catch (IdentityProviderException e) {
            return false;
        }

        return false;
    }

    /**
     * @param text
     * @return
     */
    private static String normalizeUrlEncoding(String text) {

        if (text == null)
            return null;

        int len = text.length();
        StringBuffer normalized = new StringBuffer(len);

        for (int i = 0; i < len; i++) {
            char current = text.charAt(i);
            if (current == '%' && i < len - 2) {
                String percentCode = text.substring(i, i + 3).toUpperCase();
                try {
                    String str = URLDecoder.decode(percentCode, "ISO-8859-1");
                    char chr = str.charAt(0);
                    if (UNRESERVED_CHARACTERS.contains(Character.valueOf(chr)))
                        normalized.append(chr);
                    else
                        normalized.append(percentCode);
                } catch (UnsupportedEncodingException e) {
                    normalized.append(percentCode);
                }
                i += 2;
            } else {
                normalized.append(current);
            }
        }
        return normalized.toString();
    }

    /**
     * Normalize the provided relying party URL
     * @param rpUrl Relying party URL to be normalized
     * @return Normalized relying party URL
     * @throws RelyingPartyException
     */
    public static String getRelyingPartyUrl(String rpUrl)
            throws IdentityProviderException {

        URI uri = null;
        URL url = null;

        try {
            uri = new URI(rpUrl);
        } catch (URISyntaxException e) {
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.INVALID_OPENID_RETURNTO);
        }

        try {
            url = uri.normalize().toURL();
            url = new URL(url.getProtocol().toLowerCase(), url.getHost()
                    .toLowerCase(), url.getPort(), url.getPath());
            return url.toString();

        } catch (MalformedURLException e) {
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.INVALID_OPENID_RETURNTO);
        }
    }

    /**
     * This provides a mapping between http://schema.openid.net/ and
     * http://axschema.org
     * @param val schema name-space URL
     * @return mapped value
     */
    public static String getMappedAxSchema(String val) {
        if (axMapping.containsKey(val)) {
            return axMapping.get(val);
        }

        return val;
    }

    /**
     * Extracts authentication policies from the PAPE request
     * @param params OpenID parameter list
     * @return Set of authentication policies as requested by PAPE request
     * @throws IdentityProviderException
     */
    public static String[] getRequestedAuthenticationPolicies(
            ParameterList params) throws IdentityProviderException {
        // Process an authentication request.
        try {
            AuthRequest authReq = AuthRequest.createAuthRequest(params,
                    OpenIDProvider.getManager().getRealmVerifier());
            return OpenIDPape.getAuthenticationPolicies(authReq);
        } catch (MessageException e) {
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.OPENID_RESP_GENERATION_FAILED,
                    e);
        }
    }

    /**
     * Find the OpenID corresponding to the given user name.
     * @param userName User name
     * @return OpenID corresponding the given user name.
     * @throws IdentityProviderException
     */
    public static String getOpenID(String userName)
            throws IdentityProviderException {

        UserStore userStore = null;
        List<String> users = null;

        userStore = UserStore.getInstance();
        users = userStore.getAllUserNames();

        if (users == null)
            throw new IdentityProviderException(
                    IdentityConstants.ErrorCodes.NO_USERS_FOUND);

        Map<String, String> mapValues = null;
        Iterator<String> iterator = null;

        iterator = users.iterator();

        while (iterator.hasNext()) {

            String user = iterator.next();
            mapValues = userStore.getClaimValues(user, null);

            if (mapValues != null && !mapValues.isEmpty()) {
                if (user.equals(userName)) {
                    return (String) mapValues
                            .get(IdentityConstants.CLAIM_OPENID);
                }
            }
        }
        return null;
    }

}

⌨️ 快捷键说明

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