在Windows Phone上请求access_token时,Instagram API返回错误

时间:2014-01-02 21:03:08

标签: oauth instagram

我一直在尝试将Instagram API集成到我的应用中,但我坚持使用身份验证。当我刚刚使用隐式流版本时,我让它完全正常工作,它给了我access_token作为URI片段的一部分。 但是,现在我正在改为服务器端流程,我在用户登录后收到代码。然后我将此代码发布到访问令牌URL,然后会给我access_token以及有关的某些信息。用户,例如他们的用户名和个人资料图片链接。

我正在使用InstaSharp库,修改源代码。

        HttpClient client = new HttpClient { BaseAddress = new Uri(config.OAuthUri + "access_token/", UriKind.Absolute) };
        var request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress);

        request.AddParameter("client_secret", config.ClientSecret);
        request.AddParameter("client_id", config.ClientId);
        request.AddParameter("grant_type", "authorization_code");
        request.AddParameter("redirect_uri", config.RedirectUri);
        request.AddParameter("code", code);

        return client.ExecuteAsync<OAuthResponse>(request);

创建请求后,格式如下: {方法:POST,RequestUri:'https://api.instagram.com/oauth/access_token/?client_secret= {CLIENT_SECRET}&amp; client_id = {CLIENT_ID}&amp; grant_type = authorization_code&amp; redirect_uri = http://instagram.com&amp; code = {CODE}',Version:1.1,Content :,标题:{}} (我在redirect_uri和代码之间插入了空格,因为它不会让我发布问题)

地址中的所有内容都显示正常,但我在重新调整的json文件中始终收到错误:

“{”code“:400,”error_type“:”OAuthException“,”error_message“:”您必须提供client_id“}”

我不知道导致此错误的原因。任何帮助是极大的赞赏! 谢谢! 埃利奥特

1 个答案:

答案 0 :(得分:1)

您使用的是最新版本的InstaSharp吗?叉它here。您可以检查README.md,虽然它有点过时,您需要调整一些配置。以下是使用github中的最新版本的方法:

// create the configuration in a place where it's more appropriate in your app
InstaSharpConfig = new InstagramConfig(
    apiURI, oauthURI, clientId, clientSecret, redirectUri);

// then here's a sample method you can have to initiate auth 
// and catch the redirect from Instagram
public ActionResult instagramauth(string code)
{
    if (string.IsNullOrWhiteSpace(code))
    {
        var scopes = new List<InstaSharp.Auth.Scope>();
        scopes.Add(InstaSharp.Auth.Scope.likes);
        var link = InstaSharp.Auth.AuthLink(
            oauthURI, clientId, redirectUri, scopes);
        // where:
        // oauthURI is https://api.instagram.com/oauth
        // clientId is in your Instagram account
        // redirectUri is the one you set in your Instagram account; 
        // for ex: http://yourdomain.com/instagramauth

        return Redirect(link);
    }

    // add this code to the auth object
    var auth = new InstaSharp.Auth(InstaSharpConfig);

    // now we have to call back to instagram and include the code they gave us
    // along with our client secret
    var oauthResponse = auth.RequestToken(code);

    // save oauthResponse in session or database, whatever suits your case

    // oauthResponse contains the field Access_Token (self-explanatory), 
    // and "User" that'll give you the user's full name, id, 
    // profile pic and username


    return RedirectToAction("action", "controller");
}

请注意,您可以拆分“instagramauth”方法。这样做是为了简洁。