Search code examples
oauthoauth-2.0instagramtwitter-oauthinstagram-api

Get access_token using Windows Service's or Console App. for Instagram Api


My windows service is collect instagram datas from instagram api. I was using client_id but this uses format is removed.

Instagram api is want to access_token but Oauth 2.0 is web-based. or not?

I using .NET and my application type is windows service and web request don't work because this call url: "https://www.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code" is have one more contain redirect. so web response haven't contain my web application link also auto redirect is open..

what should I do?

Thanks..


Solution

  • Steps to get instagram access token register ur application in instagram account. get a client id and client secret.

    Step 1: HIT the below url.

    https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

    step 2: after hitting above url you will be taken to login page. enter the login credentials and take the code from address bar. it will be live for only 20 seconds i guess.

    step 3: The code which you got put it in CODE parameter in the below source code, then run the below code in console application n hit breakpoint at response. you will get access token and userid.

        public void GetDataInstagramToken()
        {
            try
            {
                NameValueCollection parameters = new NameValueCollection();
                parameters.Add("client_id", "CLIENT-ID");
                parameters.Add("client_secret", "CLIENT-Secret");
                parameters.Add("grant_type", "authorization_code");
                parameters.Add("redirect_uri", "REDIRECT-URI");
                parameters.Add("code", "CODE");
    
                WebClient client = new WebClient();
                var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
                var response = System.Text.Encoding.Default.GetString(result);
    
                // deserializing nested JSON string to object  
                var jsResult = (JObject)JsonConvert.DeserializeObject(response);
                string accessToken = (string)jsResult["access_token"];
            }
            catch (Exception)
            {
               //exception catch
            }
        }