如何在不登录的情况下从 Instagram 获取 oauth 2 访问令牌(隐式流)?

How to get an oauth 2 access token from Instagram without logging in (implicit flow)?

我想在网站和应用程序上显示来自不同 Instagram 用户的动态。内容为public。我计划使用 Instagram api 端点来检索数据。要访问 Instagram APIs,我需要一个访问令牌。但是我无法通过 API 调用获得有效的访问令牌。我想使用 oauth 2 隐式流(客户端凭据),因为交互是静默的并且不应该涉及手动授权(用户不必授权访问)。以下 C# 代码给出了 "BAD REQUEST" 响应。客户端 ID、密码和重定向 url 已在 Instagram 客户端配置中设置。

string instagramClientId = "1111111111111111111111111111111";
string instagramClientSecret = "2222222222222222222222222222222";
string instagramTokenUrl = "https://api.instagram.com/oauth/access_token";
string instagramRedirectUrl = "http://socialmedia.local/api/posts/instagram";
string instagramAccessToken = "";

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(instagramTokenUrl);
    client.DefaultRequestHeaders.Accept.Clear();

    var content = new FormUrlEncodedContent(new[] 
    {
        new KeyValuePair<string, string>("client_id", instagramClientId),
        new KeyValuePair<string, string>("client_secret", instagramClientSecret),
        new KeyValuePair<string, string>("grant_type", "authorization_code"),
        new KeyValuePair<string, string>("redirect_uri", instagramRedirectUrl),
        new KeyValuePair<string, string>("code", "CODE")
    });
    HttpResponseMessage response = await client.PostAsync("", content);
    if (response.IsSuccessStatusCode)
    {
        var result = response.Content.ReadAsStringAsync().Result;
        if (result.IndexOf("access_token") >= 0)
        {
            instagramAccessToken = result.Substring(result.IndexOf("=") + 1);
        }
    }
}

如果您发出未经授权的请求(即没有用户访问令牌),则不需要 oauth2 隐式流程。您可以将 access_token:{users access token} 替换为 client_id:{applications client id}

请注意,您只能对某些端点执行此操作。例如,您无法获取用户提要(他们关注的人的最新帖子),因为这是用户私有的并且需要访问令牌。您可以从

的用户那里获取最近的帖子
https://api.instagram.com/v1/users/{user_id}/media/recent/?client_id={app client_id}