Forum Discussion

karikalan's avatar
karikalan
New member | Level 1
11 years ago

Windows 8 store app Dropbox get access token and upload issue

I am able to successfully login and get the request token using rest apin in Windows 8 store app. But I am getting '401 Unauthorized' error while retrieving the access token as well as trying to uploading file in the dropbox using api. Please give me the solution.

10 Replies

Replies have been turned off for this discussion
  • Please share your code: specifically the part where you make the call to exchange the request token for an access token.

    From the terminology "request token," it sounds like maybe you're using OAuth 1? Are you using a library for OAuth, or are you writing your own code? Which signing method are you using? (HMAC-SHA1 or PLAINTEXT?)

  • karikalan's avatar
    karikalan
    New member | Level 1
    11 years ago

    We are using the following code and using OAuth1 and HMAC-SHA1 signing method.

    var authentication = new Authentication(AppKey, AppSecret);
    var token = await authentication.RequestToken("https://api.dropbox.com/1/oauth/request_token", WebAuthenticationBroker.GetCurrentApplicationCallbackUri().ToString());
    
    if (token != null)
    {
        var url = "https://www.dropbox.com/1/oauth/authorize?oauth_token=" + token.Key + "&oauth_callback=" + WebAuthenticationBroker.GetCurrentApplicationCallbackUri();
        System.Uri StartUri = new Uri(url);
    
        WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
                                                WebAuthenticationOptions.None,
                                                StartUri);
        if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
        {
    
            authentication.GetAccessToken("https://api.dropbox.com/1/oauth/access_token?oauth_token=" + token.Key, token.Key, token.Secret);
            Upload();
        }
    
    public async static void Upload()
    {
        var picker = new Windows.Storage.Pickers.FileOpenPicker();
        picker.FileTypeFilter.Add(".jpg");
        picker.FileTypeFilter.Add(".png");
        picker.FileTypeFilter.Add(".gif");
        picker.FileTypeFilter.Add(".doc");
        picker.FileTypeFilter.Add(".docx");
        picker.FileTypeFilter.Add(".xls");
    
        StorageFile attachmentFile = await picker.PickSingleFileAsync();
        byte[] imgBytes = await GetPhotoBytesAsync(attachmentFile);
    
        string apiKey ="yvynusucnu104zf" ;
    
        string consumerSecret = "<redacted>";
        string tokenKey = "vam1o365ldgp4wf7";
    
        TimeSpan SinceEpoch = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
        Random Rand = new Random();
    
        Int32 Nonce = Rand.Next(1000000000);
    
        var uri = new Uri(new Uri("https://api-content.dropbox.com/1/"),
            String.Format("files_put/{0}/{1}",
            "dropbox", @"Photos\car-acc2.jpg"));
    
        var requestUri = SignRequest(uri, apiKey, consumerSecret, tokenKey, "PUT");
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(requestUri);
        Request.Method = "PUT";
    
        //Request.Headers["Authorization"] = Data;
    
    
    
        using (Stream requestStream = await Request.GetRequestStreamAsync())
        {
            await requestStream.WriteAsync(imgBytes, 0, imgBytes.Length);
            await requestStream.FlushAsync();
        }
    
        HttpWebResponse Response = (HttpWebResponse)await Request.GetResponseAsync();
        StreamReader ResponseDataStream = new StreamReader(Response.GetResponseStream());
    
    }
    
  • What's the exact URL you're hitting when you get the 401? (Please X out any secrets in the URL.)

    Note that the app key in your code snippet below is for a disabled app. (That would certainly cause a 401.)

    If you can get the actual body for the 401 response, that would help.

  • karikalan's avatar
    karikalan
    New member | Level 1
    11 years ago

    I have used the following url, app key, app secret and data which has posted to retrieve the access token.

    URL: https://api.dropbox.com/1/oauth/access_token?oauth_token=KDIGaDoXjQBvT0pn

    AppKey = "qas1ok71ay8wqr0"
    AppSecret = "<REDACTED>"

    Posted Data : OAuth oauth_consumer_key="qas1ok71ay8wqr0", oauth_nonce="300571600", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1428469092", oauth_version="1.0", oauth_signature="tJTlNcaoYq6J01FwOjflR8s37P8%3D"

    GetAccess Token Method Code:

    public async void GetAccessToken(string url, string key, string secret)
    {
        TimeSpan SinceEpoch = (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());
        Random Rand = new Random();
    
        Int32 Nonce = Rand.Next(1000000000);
    
        String sigBaseStringParams = "oauth_consumer_key=" + _apiKey;        
        sigBaseStringParams += "&" + "oauth_nonce=" + Nonce.ToString();
        sigBaseStringParams += "&" + "oauth_signature_method=HMAC-SHA1";
        sigBaseStringParams += "&" + "oauth_timestamp=" + Math.Round(SinceEpoch.TotalSeconds);       
        sigBaseStringParams += "&" + "oauth_version=1.0";
        String SigBaseString = "POST&";
        SigBaseString += Uri.EscapeDataString(url) + "&" + Uri.EscapeDataString(sigBaseStringParams);
        var signature = GenerateSignature(SigBaseString, secret);
    
        String DataToPost = "OAuth oauth_consumer_key=\" + _apiKey + "\", oauth_nonce=\" + Nonce.ToString() + "\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\" + Math.Round(SinceEpoch.TotalSeconds) + "\", oauth_version=\"1.0\", oauth_signature=\" + Uri.EscapeDataString(signature) + "\";
    
        var postResponse = await PostData(url, DataToPost);
    }
    private async Task<string> PostData(String Url, String Data)
    {
    
        HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(Url);
        Request.Method = "POST";
        Request.Headers["Authorization"] = Data;
        HttpWebResponse Response = (HttpWebResponse)await Request.GetResponseAsync();
        StreamReader ResponseDataStream = new StreamReader(Response.GetResponseStream());
        return ResponseDataStream.ReadToEnd();
    
    }
    
  • I see two immediate issues:

    1. Your Authorization header on the call to /access_token seems to be missing the required parameter oauth_token. You seem to have it in the URL instead, which I don't think works. (I don't think you can mix parameters in the query string and in the Authorization header.)
    2. You're escaping the signature, which causes it to be invalid Base64. (It ends with %3D instead of =.)

    Also, I removed your app secret from your post, but others may have seen the post while it was visible, so you should consider it to be leaked.

  • karikalan's avatar
    karikalan
    New member | Level 1
    11 years ago

    Thanks for your reply. Still getting 401 unauthorized error even after passing oAuth token and removing escape data string in signature. But same code working fine in console appo

  • Would you please share your updated code?

    If you have two apps and one is working, I would suggest comparing the two to see what differences there are.

  • karikalan's avatar
    karikalan
    New member | Level 1
    11 years ago

    The code is not working only in WINRT store app. do you have any sample code to get the access token in the win RT Store app?

About Dropbox API Support & Feedback

Node avatar for Dropbox API Support & Feedback
Find help with the Dropbox API from other developers.

The Dropbox Community team is active from Monday to Friday. We try to respond to you as soon as we can, usually within 2 hours.

If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X, Facebook or Instagram.

For more info on available support options for your Dropbox plan, see this article.

If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!