Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
569 views
in Technique[技术] by (71.8m points)

c# - OAuth 2.0 In .NET With Instagram API

I am working on consuming the Instagram API and I am stuck at step 2 of their OAuth. I have a code from their redirect back to me, but then they want me to do a post with parameters like below...

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 am implementing this as an ASP.NET MVC 3 solution. I tried to implement the post like so...


    WebRequest request = HttpWebRequest.Create("https://api.instagram.com/oauth/access_token");
    request.Method = "POST";
    request.Headers.Add("client_id", "sdlf0982jiejfopijfp92jjiwoijf90");
    request.Headers.Add("client_secret", "39993939393939393939393939393");
    request.Headers.Add("grant_type", "authorization_code");
    request.Headers.Add("redirect_uri", "http://localhost:34962/Home/Auth");
    request.Headers.Add("code", 111111);
    var response = request.GetResponse();
    return View();

This gives me a 400 error saying that "client_id is required". I have included the client_id, but I'm clearly not implementing this correctly.

What is the "best practice" way to perform the second leg of the OAuth?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got the answer from the above mentioned SO post about adding POST parameters to an HttpWebRequest. Here are the details of my implementation.

NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "3498wjfoi2892jf0j2ij02fjakjf2");
parameters.Add("client_secret", "392621gfdlfj2k2hf7g2lfhj2g");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "http://localhost:34962/Home/Auth");
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);

return View("Index", (object)response);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...