Search code examples
c#oauthinstagramaccess-tokeninstagram-api

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


I want to show feeds from various Instagram users on websites and apps. The content is public. I am planning to use Instagram api endpoints to retrieve data. To get access to Instagram APIs I need an access token. But I am unable to get a valid access token via the API calls. I want to use oauth 2 implicit flow (client credentials), since the interaction is silent and should not involve manual authorization (user don't have to authorize access). The following C# code gives me a "BAD REQUEST" response. The client id, secret and redirect url have been set within Instagram client configuration.

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);
        }
    }
}

Solution

  • If you are making an unauthorised request (i.e without a users access token) you do not need oauth2 implicit flow. You can just replace access_token:{users access token} for client_id:{applications client id}

    Note you can only do this for certain endpoints. For example you cannot get a users feed (recent posts from people they follow) as that is private to the user and requires access token. You can get recent posts from a user with

    https://api.instagram.com/v1/users/{user_id}/media/recent/?client_id={app client_id}