Login with Twitter

24 / Aug / 2012 by Amit Kumar 2 comments

This application saves user’s time for registration by providing a way through which user can login into application with its twitter credentials. Application will get the user details from his corresponding twitter account and will do the registration programmatically, so user can easily manage account through his twitter account.

Five simple steps to connect with twitter

1. First of all, you have to register your application with twitter. Once the application is registered you will receive “consumer key” and “consumer secret”.

2. Write “consumer key” and “consumer secret” in Config.groovy as:

[groovy]
twitter {
oauth.consumer_key = ‘mjnSnJAtlpI0TTriR4gQ’
oauth.consumer_secret = ’86IEve8R37TNAIoSFoGPlMxbPCHpvvmFr2eAwwU’
}
[/groovy]

3. To provide twitter utility into grails app, add dependance into BuildConfig.groovy as:

[groovy]
build ‘net.homeip.yusuke:twitter4j:2.0.10’
[/groovy]

Twitter provide twitter4j named API to intract with twitter.

4. Create a link which says to login with twitter as:

[groovy]
Login with Twitter
[/groovy]

5. Create LoginController with actionName as loginWithTwitter:

[groovy]
import org.codehaus.groovy.grails.commons.ConfigurationHolder

class LoginController {

def requestLogin() {
def twitter = new twitter4j.Twitter()
def callbackUrl = g.createLink(action: ‘processLogin’, absolute:true).toString()
def consumerKey = ConfigurationHolder.config.twitter.oauth.consumer_key
def consumerSecret = ConfigurationHolder.config.twitter.oauth.consumer_secret
twitter.setOAuthConsumer(consumerKey, consumerSecret)
def requestToken = twitter.getOAuthRequestToken(callbackUrl)
session.twitter = twitter
session.requestToken = requestToken
redirect(url:requestToken.getAuthorizationURL())
}

def processLogin() {
if (!session.requestToken) {
redirect(action: ‘requestLogin’)
} else {
def accessToken = session.twitter.getOAuthAccessToken(session.requestToken, params.oauth_verifier)
def twitterUser = session.twitter.verifyCredentials()
session.twitterUser = twitterUser
redirect(action: ‘dashboard’)
}
}
}
[/groovy]

When user click on Login with Twitter link, requestLogin action is called which redirects request to twitter for authorization. On successful authorization from twitter, user will be redirected to call back url (on processLogin Action). processLogin Action gets all the information related to user (in twitterUser object) from twitter. Registration can be done for that user with that twitter information, and user can then access the application through his twitter account information.

More Blogs by Me

FOUND THIS USEFUL? SHARE IT

comments (2)

  1. vamsi

    hi i implemented this scenario. but i get a problem. twitter4j.Twitter() can’t be identified. it showing error. what can i do?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *