Package org.wso2.carbon.identity.oauth

Source Code of org.wso2.carbon.identity.oauth.OAuthService

/*
*  Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
*  WSO2 Inc. licenses this file to you 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.carbon.identity.oauth;

import java.net.URLEncoder;
import java.util.Date;

import org.wso2.carbon.identity.core.dao.OAuthConsumerDAO;
import org.wso2.carbon.identity.core.util.IdentityTenantUtil;
import org.wso2.carbon.identity.core.util.IdentityUtil;
import org.wso2.carbon.identity.oauth.dto.OAuthConsumerDTO;
import org.wso2.carbon.identity.oauth.internal.OAuthServiceComponent;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.core.Registry;
import org.wso2.carbon.registry.core.RegistryConstants;
import org.wso2.carbon.registry.core.service.RegistryService;
import org.wso2.carbon.user.core.UserRealm;
import org.wso2.carbon.user.core.service.RealmService;
import org.wso2.carbon.user.core.util.UserCoreUtil;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthUtil;

public class OAuthService {

    public boolean isOAuthConsumerValid(OAuthConsumerDTO oauthConsumer) throws Exception {
        GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
        oauthParameters.setOAuthConsumerKey(oauthConsumer.getOauthConsumerKey());
        oauthParameters.setOAuthConsumerSecret(getOAuthSecretKey(oauthConsumer
                .getOauthConsumerKey()));
        oauthParameters.setOAuthNonce(oauthConsumer.getOauthNonce());
        oauthParameters.setOAuthTimestamp(oauthConsumer.getOauthTimeStamp());
        oauthParameters.setOAuthSignatureMethod(oauthConsumer.getOauthSignatureMethod());
        OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
        String baseString = OAuthUtil.getSignatureBaseString(oauthConsumer.getBaseString(),
                oauthConsumer.getHttpMethod(), oauthParameters.getBaseParameters());
        String signature = signer.getSignature(baseString, oauthParameters);

        if (signature != null
                && URLEncoder.encode(signature).equals(oauthConsumer.getOauthSignature())) {
            return true;
        } else if (signature != null && signature.equals(oauthConsumer.getOauthSignature())) {
            return true;

        }
        return false;
    }

    public boolean validateAuthenticationRequest(OAuthConsumerDTO oauthConsumer,
            String shortLivedToken) throws Exception {

        if (shortLivedToken == null) {
            return false;
        }
       
        boolean isAuthenticated = isOAuthConsumerValid(oauthConsumer);

        if (isAuthenticated) {
            String tenantDomain = UserCoreUtil.getTenantDomain(OAuthServiceComponent
                    .getRealmService(), oauthConsumer.getOauthConsumerKey());
            RegistryService registryService = OAuthServiceComponent.getRegistryService();
            String username = UserCoreUtil.getTenantLessUsername(oauthConsumer
                    .getOauthConsumerKey());
            RealmService realmService = OAuthServiceComponent.getRealmService();
            int tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
            UserRealm realm = registryService.getUserRealm(tenantId);
            int userId = realm.getUserStoreManager().getUserId(username);

            String baseString = "TenantId:=" + tenantId + "&UserId:=" + userId;
            Registry registry = registryService.getConfigSystemRegistry(tenantId);

            String path = RegistryConstants.PROFILES_PATH + username;
            Collection profile = null;
            if (!registry.resourceExists(path)) {
                return false;
            } else {
                profile = (Collection) registry.get(path);
            }

            String key = profile.getProperty(RegistryConstants.USER_TOKEN);

            if (key == null) {
                return false;
            }

            String[] keys = key.split("&");
            String signatureKey = null;
            String timestamp = null;
            String ttl = null;

            if (keys != null && keys.length > 0) {
                for (int i = 0; i < keys.length; i++) {
                    if (keys[i] != null) {
                        String[] tokens = keys[i].split(":=");
                        if (tokens == null || tokens.length < 2) {
                            return false;
                        }
                        if ("Key".equals(tokens[0])) {
                            signatureKey = tokens[1];
                        } else if ("Timestamp".equals(tokens[0])) {
                            timestamp = tokens[1];
                        } else if ("TTL".equals(tokens[0])) {
                            ttl = tokens[1];
                        }
                    }
                }
            }

            if (timestamp == null || ttl == null || signatureKey == null) {
                return false;
            }

            String newSignature = IdentityUtil.getHMAC(signatureKey, baseString);
            String signature = null;
            String[] userTokens = shortLivedToken.split("&");
            if (userTokens != null && userTokens.length > 0) {
                for (int i = 0; i < userTokens.length; i++) {
                    if (keys[i] != null) {
                        String[] tokens = userTokens[i].split(":=");
                        if (tokens == null || tokens.length < 2) {
                            return false;
                        }
                        if ("Signature".equals(tokens[0])) {
                            signature = tokens[1];
                            break;
                        }
                    }
                }
            }

            if (!newSignature.equals(signature)) {
                return false;
            }

            Date date = new Date();
            long timeNow = date.getTime();

            if (Long.parseLong(timestamp) + Long.parseLong(ttl) < timeNow) {
                return false;
            }
        } else {
            return false;
        }

        return true;
    }

    private String getOAuthSecretKey(String consumerKey) throws Exception {
        String tenatUser = null;
        String domain = null;
        OAuthConsumerDAO dao = null;

        tenatUser = UserCoreUtil.getTenantLessUsername(consumerKey);
        domain = UserCoreUtil.getTenantDomain(OAuthServiceComponent.getRealmService(), consumerKey);
        dao = new OAuthConsumerDAO(IdentityTenantUtil.getRegistry(domain, consumerKey));
        return dao.getOAuthConsumerSecret(tenatUser);

    }
}
TOP

Related Classes of org.wso2.carbon.identity.oauth.OAuthService

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.