Request the access_token Instagram

為{幸葍}努か 提交于 2019-12-07 06:59:52

问题


I got the following problem:

I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :

curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token

I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:

NameValueCollection parameters = new NameValueCollection();
            parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
            parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
            parameters.Add("grant_type", "authorization_code");
            parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
            parameters.Add("code", code);

            WebClient client = new WebClient();
            var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);

            var response = System.Text.Encoding.Default.GetString(result);

However I keep getting: System.Net.WebException: The remote server returned an error: (400) Bad Request.

What I am i doing wrong?


回答1:


Almost there the instagram api expects a POST not a GET.

Add the "POST" parameter.

var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);

Also check the instagram settings -> redirect url.

Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:

using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;

namespace Instagram
{
    public class InstagramClient
    {
        public InstagramClient(string code)
        {
            GetToken(code);
        }

        private void GetToken(string code)
        {
            using (var wb = new WebClient())
            {
                var parameters = new NameValueCollection
                                 {
                                     {"client_id", "ClientId"},
                                     {"client_secret", "ClientSecret"},
                                     {"grant_type", "authorization_code"},
                                     {"redirect_uri", "RedirectUri"},
                                     {"code", code}
                                 };

                var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                string json = Encoding.ASCII.GetString(response);

                try
                {
                    var OauthResponse = (InstagramOAuthResponse)    Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
                }
                catch (Exception ex)
                {
                    //handle ex if needed.
                }
            }
        }

        public class InstagramOAuthResponse
        {
            public string access_token { get; set; }
            public User user { get; set; }
        }

        public class User : System.Security.Principal.IIdentity
        {
            public string username { get; set; }
            public string website { get; set; }
            public string profile_picture { get; set; }
            public string full_name { get; set; }
            public string bio { get; set; }
            public string id { get; set; }

            public string OAuthToken { get; set; }

            public string AuthenticationType
            {
                get { return "Instagram"; }
            }

            public bool IsAuthenticated
            {
                get { return !string.IsNullOrEmpty(id); }
            }

            public string Name
            {
                get
                {
                    return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
                }
            }
        }
    }
}



回答2:


If you prefer HttpWebRequest class:

var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;

byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;

using (Stream outputStream = request.GetRequestStream())
{
    outputStream.Write(bytes, 0, bytes.Length);
}

var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;

if (code == HttpStatusCode.OK)
{
    using (var streamReader = new StreamReader(response.GetResponseStream()))
    {
        var jsonString = streamReader.ReadToEnd();
        var accessToken = ParseAccessToken(jsonString);
        return accessToken;
    }
}


来源:https://stackoverflow.com/questions/25094609/request-the-access-token-instagram

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!