MySpace Open Platform

A Place For Developers

Welcome Developers!

in

Welcome!

in

Error while requesting Access_Token

Last post 08-25-2009 1:15 PM by [ P 0 | | U X ]. 22 replies.
Page 1 of 2 (23 items) 1 2 Next >
Sort Posts: Previous Next
  • 09-15-2008 12:47 AM

    • Bill
    • Top 500 Contributor
    • Joined on 07-21-2008
    • Posts 11

    Error while requesting Access_Token

    Hi,

     I have developed a web based applicaiton which allows users to add my application to their profiles. I am following the guidelines that are mentioned on http://developer.myspace.com/community/myspace/dataavailability.aspx. I am able to request a token and then redirect to MySpace signing page by giving a call back URL. Users successfully sign in and reach my call back page. My call back page receives the information and then requests for access_token as per the documentation mentioned on above link. At this point i get the following error The remote server returned an error: (401) Unauthorized. I am sending everything as signed per documentation but could not figure out the reason. Also, I tried to run my application parallel "External App Authication" application present at:http://developer.myspace.com/modules/apis/pages/accessdelegationtool.aspx. I noticed that the MySpace's External Authentication application gets a different Secret on its call back page where as I get the same one that I had mentioned in my call back URL. This is the only difference that I could find.


    Can you please help me in rectifying my application for this?

     

    Greatly appreciated!

    Best Regards
    Bill

     

  • 10-13-2008 7:14 AM In reply to

    Re: Error while requesting Access_Token

    Any update on this thread?  Bill? I'm encountering the same problem except I'm getting the following error....

    Exception: System.Net.WebException: The remote server returned an error: (401) oauth_problem="signature_invalid".
    at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000]
    at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000]

     

  • 10-16-2008 12:26 PM In reply to

    • Frank
    • Not Ranked
    • Joined on 10-07-2008
    • Posts 9

    Re: Error while requesting Access_Token

     Same problem here I can get the request token and authorize it but when I go to get the access token I get the following.

    "HTTP/1.1 401 oauth_problem="signature_invalid"[\r][\n]"

    Anybody???

  • 10-16-2008 12:43 PM In reply to

    Re: Error while requesting Access_Token

     when you generate the hmac sha1 you need to make sure you are concatenating the comsumerkey or secret i forget what it is with the oauth_token_secret

     

    right now if you are using the myspace toolkit

     

    it does something like this Comsumerkey+ "&" but it should be

    ConsumerKey +"&" + Oauth_token_secret

     

    hope this helps.

  • 10-16-2008 3:13 PM In reply to

    • Frank
    • Not Ranked
    • Joined on 10-07-2008
    • Posts 9

    Re: Error while requesting Access_Token

     Noyce works like a charm... thanks

  • 11-10-2008 3:15 PM In reply to

    • Andy
    • Top 200 Contributor
    • Joined on 04-07-2008
    • Posts 25

    Re: Error while requesting Access_Token

    Hey Frank,

    How you get it to work? Here is what I'm doing:

    Signature key = consumer shared secret & auth token secret
    Signature base string =
    GET&http%3A%2F%2Fapi.myspace.com%2Faccess_token.xml&oauth_co
    nsumer_key%3Dhttp%253A%252F%252Fwww.myspace.com%252F427990548%26oauth_
    nonce%3D586229792842641%26oauth_signature_method%3DHMAC-SHA1%26oa
    uth_timestamp%3D1226353607%26oauth_token%3D%2FJ%2FG2WM1FecSzpABv4hVyrKtqC
    03cvP6nss+lfWao7zsdHvgJeRqGQuUF6SUtmyQkzL0ZIfA39%2Fh97VD4Ula%2Fw%3D%3
    D%26oauth_token_secret%3Dddf15c20647148ec8654922d87c5c304%26o
    auth_version%3D1.0

    Access token request url =
    http://api. myspace. com/access_token. xml?oauth_consumer_key=http%3A%2F%2Fwww. myspace. com%2F427990548&oauth_nonce=586229792842641&oauth_signature=
    CBRa3%2F1VfnEo9y1BAUkBNtTOzLs%3D&oauth_signature_method=HMAC
    -SHA1&oauth_timestamp=1226353607&oauth_token=/J/G2WM1FecSzpA
    Bv4hVyrKtqC03cvP6nss+lfWao7zsdHvgJeRqGQuUF6SUtmyQkzL0ZIfA39/h97VD4Ula/w==&oauth_
    version=1. 0

    I'm getting the invalid signature error...

    Andy 

  • 11-13-2008 10:03 PM In reply to

    • Sammi
    • Top 500 Contributor
    • Joined on 10-05-2008
    • Posts 11

    Re: Error while requesting Access_Token

    Hi Andy, Same problem here. I use consumer_shared_secrect+"&"+oauth_token_secret, doesn't work too.
    	private String getAccessTokenUrlSignature(String baseString,String oauth_token_secret) throws Exception{
    		String key = shared_secret+"&"+oauth_token_secret;
    		String oauth_signature = Signature.calculateRFC2104HMAC(baseString, key);
    		return oauth_signature;
    	}
    
    I also tried by myspace test tool. input auto_token and secret and use the generated requestRUI, accessToken cannot get too. When authorize the request token, I found the return auth_token is a little different with the requestURl generated. I tried the two tokens. Both of them cannot work too. Sign..... Sammi
  • 11-14-2008 5:22 AM In reply to

    Re: Error while requesting Access_Token

     Did you base64 encoded it?

     Try to post more code...

  • 11-14-2008 7:05 AM In reply to

    • Andy
    • Top 200 Contributor
    • Joined on 04-07-2008
    • Posts 25

    Re: Error while requesting Access_Token

    Hey Idumont,

    If I was able to get the auth token and  auth token secret successfully, then I should be encoding everything correctly no? I'm doing this in flash and have used brock's as library and it works fairly well beside the fact i'm stuck getting an "signature invalid" error. I think this is an issue MDP is currently looking at. That is what rhondata have told me earlier this week.  However, I would love to see code of someone who actually have gotten an access token using an external app and willing to share the raw code.

    Thanks,

    Andy 

  • 11-14-2008 8:09 AM In reply to

    Re: Error while requesting Access_Token

    Well it works for me using a simple Python code written by myself and with the Python library available on oauth website.

     

    Here is my code for the first case: (Notice that this code was for understanding how OAuth works)

    import time, hashlib, urllib, hmac, base64, random, webbrowser
    from restclient import GET

    CONSUMER_KEY = u'http://www.myspace.com/416612491'
    CONSUMER_SECRET = u'XXXXXXXXXXXXXXXXXXXX'
    SIGNATURE_METHOD = u'HMAC-SHA1'
    VERSION = u'1.0'

    REQUEST_TOKEN_URL = 'http://api.myspace.com/request_token'
    AUTHORIZATION_URL = 'http://api.myspace.com/authorize'
    ACCESS_TOKEN_URL = 'http://api.myspace.com/access_token'

    oauth_token_secret = u''
    oauth_token = u''


    def gen_signature(url, params):   
        for p in params:
            params[p] = urllib.quote(params[p], '')   
                   
        params_keys = params.keys()
        params_keys.sort()
       
        sig = ''
       
        for key in params_keys:
            sig += key +'='+ params[key] +'&'

        sig = 'GET&' + urllib.quote(url, '') + '&' + urllib.quote(sig[:len(sig)-1])
        #print sig
        key = urllib.quote(CONSUMER_SECRET) + '&' + oauth_token_secret
        m = hmac.new(key, sig, hashlib.sha1)
        m = base64.b64encode(m.digest())
        return urllib.quote(m)

    def gen_nonce():
        return hashlib.md5(str(int(time.time())) + str(random.random())).hexdigest()
       
    def parse_response(response):
        response = response.split('&')
        return {'oauth_token': response[0].split('=')[1], 'oauth_token_secret': response[1].split('=')[1]}
       
    def do_get(url, params):   
        return GET(url + '?' + urllib.urlencode(params) + '&oauth_signature=' + gen_signature(url, params, quote))
       
    def pause():
        print ''
        time.sleep(1)
       
       
    # Obtain Request Token   
    print 'REQUEST TOKEN'
    pause()
    params = {'oauth_consumer_key': CONSUMER_KEY, 'oauth_version': VERSION, 'oauth_timestamp': u''+str(int(time.time())), 'oauth_nonce': u''+gen_nonce(), 'oauth_signature_method': SIGNATURE_METHOD}
    response = parse_response(do_get(REQUEST_TOKEN_URL, params))
    oauth_token = response['oauth_token']
    oauth_token_secret = response['oauth_token_secret']

    # Authorize Token
    print 'AUTORIZE TOKEN'
    pause()
    params = {'oauth_consumer_key': CONSUMER_KEY, 'oauth_version': VERSION, 'oauth_timestamp': u''+str(int(time.time())), 'oauth_nonce': u''+gen_nonce(), 'oauth_signature_method': SIGNATURE_METHOD, 'oauth_token': oauth_token, 'oauth_callback': 'http://localhost'}
    webbrowser.open(AUTHORIZATION_URL + '?' + urllib.urlencode(params) + '&oauth_signature=' + gen_signature(AUTHORIZATION_URL, params))

    # Time to authorized the token with the browser
    raw_input("Press enter when token is authorized...")

    # Exchange Request Token with an Access Token
    print 'EXCHANGE TOKEN'
    pause()
    params = {'oauth_consumer_key': CONSUMER_KEY, 'oauth_version': VERSION, 'oauth_timestamp': u''+str(int(time.time())), 'oauth_nonce': u''+gen_nonce(), 'oauth_signature_method': SIGNATURE_METHOD, 'oauth_token': oauth_token}
    response = parse_response(do_get(ACCESS_TOKEN_URL, params))

    oauth_token = response['oauth_token']
    oauth_token_secret = response['oauth_token_secret']

    oauth_token = urllib.unquote(oauth_token)
    oauth_token_secret = urllib.unquote(oauth_token_secret)

    # Request Data
    print 'REQUEST DATA'
    pause()
    params = {'oauth_consumer_key': CONSUMER_KEY, 'oauth_version': VERSION, 'oauth_timestamp': u''+str(int(time.time())), 'oauth_nonce': u''+gen_nonce(), 'oauth_signature_method': SIGNATURE_METHOD, 'oauth_token': oauth_token, 'format': 'json'}   
    print do_get('http://api.myspace.com/v2/people/@me/@self', params)   




     

     

  • 11-14-2008 9:57 AM In reply to

    • Andy
    • Top 200 Contributor
    • Joined on 04-07-2008
    • Posts 25

    Re: Error while requesting Access_Token

    Hey ldumont,

    Thanks for providing your sample code... 

     I'm actually urlencoding the signature rather than base64 encoding... is there a difference between this in actionscript? I will def test this and see what happens...

    Thanks,

    Andy 

  • 11-14-2008 10:53 AM In reply to

    • Andy
    • Top 200 Contributor
    • Joined on 04-07-2008
    • Posts 25

    Re: Error while requesting Access_Token

    Ok, I realize i am base64 encoding the signature then urlencode it as part of the url....

     Back to square 1.....

  • 11-14-2008 5:52 PM In reply to

    • Sammi
    • Top 500 Contributor
    • Joined on 10-05-2008
    • Posts 11

    Re: Error while requesting Access_Token

    Hi All, I've got the working version now. Tips here:
    1. baseString: consumber_key,oauth_token double encode, others encode once.
    2. signature key, don't encode
    3. request url: encode value once, that is name1=encode(value1)&name2=encode(value2)...
    4. don't add secret to baseString
    5. signature key for request token is consumber_shared_secret +"&"
    6. signature key for access token is consermer_shared_key+ "&" + request_oauth_secret
    
    here is my code
    package com.mynode.oauth.myspace;
    
    import java.net.URLEncoder;
    import java.security.SignatureException;
    import java.util.Calendar;
    import java.util.HashMap;
    import java.util.Random;
    
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    
    import org.apache.commons.codec.binary.Base64;
    
    import com.google.inject.Inject;
    import com.meterware.httpunit.GetMethodWebRequest;
    import com.meterware.httpunit.WebConversation;
    import com.meterware.httpunit.WebRequest;
    import com.meterware.httpunit.WebResponse;
    
    public class MySpaceOAuthService{
    	final private String requestTokenProviderUrl = "http://api.myspace.com/request_token";
    	final private String authorizeUrl                  = "http://api.myspace.com/authorize";
    	final private String accessTokenProvideUrl   = "http://api.myspace.com/access_token";
    	final private String oauth_signature_method  = "HMAC-SHA1";
    	final private String requestMethod           = "GET";
    	final private String oauth_version           = "1.0";
    	
    	private String oauth_consumer_key;
    	private String shared_secret;
    	private String callback_url;
    	private String oauth_timestamp;
    	private String oauth_nonce;
    	
    	private static HashMap> mySpaceKeyMap = new HashMap>();
    	
    	static{
    		HashMap signParams=new HashMap();
    		signParams.put("shared_secret","-----your shared_secret----");
    		signParams.put("callback_url", "--your callback--");
    		mySpaceKeyMap.put("--your consumer key--",signParams);
    	}
    	
    	@Inject
    	public MySpaceOAuthService(String oauth_consumer_key) {
    		this.oauth_consumer_key = oauth_consumer_key;
    		this.shared_secret      = mySpaceKeyMap.get(oauth_consumer_key).get("shared_secret");
    		this.callback_url       = mySpaceKeyMap.get(oauth_consumer_key).get("callback_url");
    		
    	}
    	
    	public 	String getRequestTokenURL() throws Exception{
    		String requestTokenUrl="";
    		String requestUrl = this.getRequestTokenUrlBaseString();
    		String oauth_signature = getRequestTokenUrlSignature(requestUrl);
    
    		requestTokenUrl = requestTokenProviderUrl + "?" + 
    		             "oauth_consumer_key="      + URLEncoder.encode(oauth_consumer_key,"UTF-8")    + 
    		             "&oauth_nonce="            + URLEncoder.encode(oauth_nonce,"UTF-8")           +
    		             "&oauth_signature="        + URLEncoder.encode(oauth_signature,"UTF-8")       +
    		             "&oauth_signature_method=" + URLEncoder.encode(oauth_signature_method,"UTF-8")+
    		             "&oauth_timestamp="        + URLEncoder.encode(oauth_timestamp,"UTF-8")       +
    		             "&oauth_version="          + URLEncoder.encode(oauth_version,"UTF-8");
    		System.out.println("Request Token URL");
    		System.out.println(requestTokenUrl);
    		return requestTokenUrl;
    	}
    	
    	public 	String getRequestToken() throws Exception{
    		String responseText = null;
    		try{
    			String requestUrl  = getRequestTokenURL();
    			
    			WebConversation conversation = new WebConversation();
    			WebRequest request   = new GetMethodWebRequest(requestUrl);
    			WebResponse response = conversation.getResponse(request);
    			response             = conversation.getResponse(request);
    			responseText         = response.getText();
    		}catch(Exception ex){
    			ex.printStackTrace();
    		}
    		System.out.println("Request Token");
    		System.out.println(responseText);
    		return responseText;
    	}
    	
    
    
    	public String getUserAuthorizationTokenURL() throws Exception{
    		String userAuthorizationTokenURL = this.getRequestToken();
    		userAuthorizationTokenURL = authorizeUrl + "?"+"oauth_callback="+callback_url+"&"+userAuthorizationTokenURL;
    		System.out.println("User Authorization URL");
    		System.out.println(userAuthorizationTokenURL);
    		return userAuthorizationTokenURL;
    	}
    
    	public String getAccessToken(String authorizedRequestToken,String oauth_token_secret) throws Exception{
    		String baseString       = this.getAccessTokenUrlBaseString(authorizedRequestToken);
    		String requestSignature = this.getAccessTokenUrlSignature(baseString, oauth_token_secret);
    		String accessTokenURL   = null;
    		try{
    			accessTokenURL = accessTokenProvideUrl  + "?"                     + 
    			             "oauth_consumer_key="      + URLEncoder.encode(oauth_consumer_key,"UTF-8") +
    			             "&oauth_nonce="            + URLEncoder.encode(oauth_nonce,"UTF-8") +
    			             "&oauth_signature="        + URLEncoder.encode(requestSignature,"UTF-8") +
    			             "&oauth_signature_method=" + URLEncoder.encode(oauth_signature_method,"UTF-8") +
    			             "&oauth_timestamp="        + URLEncoder.encode(oauth_timestamp,"UTF-8") +
    			             "&oauth_token="            + URLEncoder.encode(authorizedRequestToken,"UTF-8") +
    			             "&oauth_version="          + URLEncoder.encode(oauth_version,"UTF-8");
    		}catch(Exception ex){
    			ex.printStackTrace();
    		}
    		System.out.println("Access Token Request URL");
    		System.out.println(accessTokenURL);
    		
    		WebConversation conversation = new WebConversation();
    		WebRequest request   = new GetMethodWebRequest(accessTokenURL);
    		WebResponse response = conversation.getResponse(request);
    		response             = conversation.getResponse(request);
    		String responseText         = response.getText();
    		System.out.println("Access Token");
    		System.out.println(responseText);
    		
    		return responseText;
    	}
    	
    	private String getAccessTokenUrlBaseString(String authorizedRequestToken)  throws Exception{
    		//set oauth_timestamp and oauth_nonce
    		updateTimestampAndOnoce();
    		String encode_oauth_consumer_key =  URLEncoder.encode(oauth_consumer_key, "UTF-8");
    		authorizedRequestToken           =  URLEncoder.encode(authorizedRequestToken, "UTF-8");
    		String subBaseString = 
    			    "oauth_consumer_key="      + encode_oauth_consumer_key +
    			    "&oauth_nonce="            + oauth_nonce               +
    			    "&oauth_signature_method=" + oauth_signature_method    + 
    				"&oauth_timestamp="        + oauth_timestamp		   +
    			    "&oauth_token="            + authorizedRequestToken    +
    				"&oauth_version="          + oauth_version;
    		String baseString = 
    		       requestMethod                                     + "&" +
    		       URLEncoder.encode(accessTokenProvideUrl,"UTF-8")+ "&" +
    		       URLEncoder.encode(subBaseString, "UTF-8");
    		System.out.println("Access Token Url BaseString");
    		System.out.println(baseString);
    		return baseString;
    	}
    	
    	private String getRequestTokenUrlBaseString() throws Exception{
    		//set oauth_timestamp and oauth_nonce
    		updateTimestampAndOnoce();
    		String encode_oauth_consumer_key =  URLEncoder.encode(oauth_consumer_key, "UTF-8");
    		String subBaseString = 
    			    "oauth_consumer_key="      + encode_oauth_consumer_key +
    			    "&oauth_nonce="            + oauth_nonce               +
    			    "&oauth_signature_method=" + oauth_signature_method    + 
    				"&oauth_timestamp="        + oauth_timestamp		   +
    				"&oauth_version="          + oauth_version;
    		String baseString =
    		       requestMethod                                     + "&" +
    		       URLEncoder.encode(requestTokenProviderUrl,"UTF-8")+ "&" +
    		       URLEncoder.encode(subBaseString, "UTF-8");
    		System.out.println("Request Token Url BaseString");
    		System.out.println(baseString);
    		return baseString;
    	}
    	
    	/**
            Use this base string and the partner shared secret in the HMAC-SHA1 one
                way hashing algorithm, to generate the signature. 
                NOTE: OAuth does not mandate a specific signature algorithm, 
                but HMAC-SHA1 must be used for requests to the MySpace REST API. 
                The key used in the HMAC-SHA1 algorithm is a concatenation of the 
                partner shared secret and a token secret delimited by an ampersand (&). 
                The token secret is sometimes supplied in the body of the request for 
                the Access Token, but if it is not, the value in the key must be an 
                empty string. In this case the HMAC-SHA1 key will simply be the 
                partner shared secret followed by a trailing ampersand	
    	 * @return
    	 * @throws Exception
    	 */
    	private String getRequestTokenUrlSignature(String baseString) throws Exception{
    		String key = shared_secret+"&";
    		String oauth_signature = Signature.calculateRFC2104HMAC(baseString, key);
    		System.out.println("oauth_signature");
    		System.out.println(oauth_signature);
    		return oauth_signature;
    	}
    	
    	
    	private String getAccessTokenUrlSignature(String baseString,String oauth_token_secret) throws Exception{
    		String key = shared_secret+"&"+oauth_token_secret;
    		String oauth_signature = Signature.calculateRFC2104HMAC(baseString, key);
    		System.out.println("access token url signature");
    		System.out.println(oauth_signature);
    		return oauth_signature;
    	}
    	
    	private void updateTimestampAndOnoce(){
    		Calendar cal         = Calendar.getInstance();
    		long ms              = cal.getTimeInMillis();
    		Long timestamp       = new Long(ms / 1000);
    		this.oauth_timestamp = timestamp.toString();
    
    		Random r             = new Random();
    		long nonce1          = r.nextLong();
    		Long nonce           = Math.abs(new Long(nonce1));
    		this.oauth_nonce     = nonce.toString();
    	}
    	
    }
    
    class Signature {
    	private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
    
    	public static String calculateRFC2104HMAC(String data, String key)
    			throws java.security.SignatureException {
    		String result;
    		try {
    			SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(),
    					HMAC_SHA1_ALGORITHM);
    			Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    			mac.init(signingKey);
    			byte[ rawHmac = mac.doFinal(data.getBytes());
    			result = new String(Base64.encodeBase64(rawHmac));
    		} catch (Exception e) {
    			throw new SignatureException("Failed to generate HMAC : "
    					+ e.getMessage());
    		}
    		return result;
    	}
    }
    
    
    Cheers, Sammi
  • 11-17-2008 12:47 AM In reply to

    Re: Error while requesting Access_Token

     Correct me if I'm wrong but urlencoding and base64 encoding are two different operations and they need to be performed both.

     Read carefully the OAuth specs on oauth.net and follow the order of processing.

     Take a look at double encoding or partial encoding of the urls and sammy's tips.

     

  • 11-17-2008 10:36 AM In reply to

    • John
    • Not Ranked
    • Joined on 11-17-2008
    • Posts 1

    Re: Error while requesting Access_Token

Page 1 of 2 (23 items) 1 2 Next >