Using the Instagram Login API via Grails

04 / Apr / 2014 by Komal Jain 0 comments

In my current web application, I had to integrate login functionality via Instagram. To do so, I had to go through the following steps:

1. First you have to register your application using this link. In order to register your application, you need to have an Instagram account which can be done through Instagram’s mobile application.

2.After registering your application you will get the following credentials:
client_id
client secret

3. Once you have the required access credentials for your app, login into Instagram using the following piece of code:

def loginInstagram() {
 String redirectUri = 'http://abc.com:8080/sample/instagramAnalysis/instagramCallBack'
 String clientId = "123456778909jnjfnjnjfrgnjgn"
 String oAuthUrl="https://api.instagram.com/oauth/authorize/?client_id="
 String instagramOAuthUrl = [oAuthUrl, clientId, "&redirect_uri=", redirectUri, "&response_type=code"].join("")
 redirect(url: instagramOAuthUrl)
}

Here redirectUri refers to the URI of our application, where we will access response from Instagram’s API once the credentials are verified and login is successful.

4. On successful login, Instagram provides a code parameter in the response. Once we have the code parameter, it can be used to get an access_token by making a post request to the URL https://api.instagram.com/oauth/access_token. This URL provides us a response in JSON format which contains the logged in user’s information. You are now supposed to save this access_token in order to fetch Instagram data by making different API calls.

def instagramCallBack() {
   User currentUser = User.findUserByUserName(springSecurityService.c urrentUser.username)
   String clientId = "123456778909jnjfnjnjfrgnjgn"
   String clientSecret = '123456778909jnjefjefhejhrfjehrejejjfnjnjfrgnjgn'
   String redirectUri = 'http://abc.com:8080/sample/instagramAnalysis/instagramCallBack'
   String accessTokenUrl = "https://api.instagram.com/oauth/access_token"

   Map accessTokenMap = [
                        client_id: clientId,
                        client_secret: clientSecret,
                        grant_type: 'authorization_code',
                        redirect_uri: redirectUri,
                        code: params.code
                     ]
   JSONObject instagramJson = fetchInstagramAccessToken(accessTokenUrl, accessTokenMap) // extract access token from URL
   render instagramJson
 }

To learn more about it you can follow the link http://instagram.com/developer

FOUND THIS USEFUL? SHARE IT

Leave a comment -