Grails: Oauth Twitter userID from token - grails

Its grails project,
Twitter Authentication is successful,
How to get twitter userID from this oauth_token received?
Thanks

Try this..,.
Config:
import org.scribe.builder.api.TwitterApi
...
oauth {
providers {
twitter {
api = TwitterApi
key = 'YOUR_KRY'
secret = 'YOUR_SECRET'
callback = "http://localhost:8080/appName/oauth/twitter/callback"
successUri = "http://localhost:8080/appName/myController/twitterSuccess"
failureUri = "http://localhost:8080/appName/myController/twitterFailure"
}
}
}
MyController:
def twitterSuccess() {
Token twitterAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('twitter')]
def twitterResource = oauthService.getTwitterResource(twitterAccessToken, "https://api.twitter.com/1.1/account/settings.json")
def twitterResponse = JSON.parse(twitterResource?.getBody())
def twitterResourceDetailed = oauthService.getTwitterResource(twitterAccessToken, "https://api.twitter.com/1.1/users/show.json?screen_name=${twitterResponse['screen_name']}")
def twitterResponseDetailed = JSON.parse(twitterResourceDetailed?.getBody())
log.info "twitterId = ${twitterResponseDetailed['id']}"
...
}
You can get working example from my git repo. Grails Oauth Plugin Demo.

Related

Using facebook social plugin how to get email address in grails

I want to get email address using social plugin of grails . I am using facebook plugin compile ':spring-security-oauth-facebook:0.1' and configured properly in Config.groovy like below.
oauth {
debug = true
providers {
facebook {
api = org.scribe.builder.api.FacebookApi
key = 'here is my-key'
secret = 'my-secret-key'
successUri = '/oauth/facebook/success'
failureUri = '/oauth/facebook/failure'
callback = "${baseURL}/oauth/facebook/callback"
scopes = "email"
}
}
}
After get successfully response, below method is called.
def onSuccess(String provider) {
if (!provider) {
log.warn "The Spring Security OAuth callback URL must include the 'provider' URL
parameter"
throw new OAuthLoginException("The Spring Security OAuth callback URL must include the
'provider' URL parameter")
}
def sessionKey = oauthService.findSessionKeyForAccessToken(provider)
if (!session[sessionKey]) {
log.warn "No OAuth token in the session for provider '${provider}'"
throw new OAuthLoginException("Authentication error for provider '${provider}'")
}
}
OAuthToken oAuthToken = springSecurityOAuthService.createAuthToken(provider,
session[sessionKey])
println "oAuthToken.principal = "+oAuthToken.principal.toString();
println "oAuthToken.socialId = "+oAuthToken.socialId;
println "oAuthToken.properties= "+oAuthToken.properties
println "oAuthToken.properties= "+oAuthToken.name
println "oAuthToken.properties= "+oAuthToken.toString();
How to get email address by using this. I successfully get response from facebook but it is same number for Username,socialId,profileId but i need email Address like myemailid#gmail.com
please help me.

oauth facebook with grails accessing token

Its a grails project,
Facebook authentication is successful via oauth,
Now when it comes back to my controller, I want to get emailID of the logged in user,
Searched a lot, but did not find proper documentation,
I am using scribe and have following code in Config.groory
import org.scribe.builder.api.FacebookApi
oauth {
providers {
facebook {
api = FacebookApi
key = 'xxxx'
secret = 'yyyy'
callback = "http://my-domain-name-here:8080/TestOAuth2/dashBoard/facebooklogin"
successUri = "http://my-domain-name-here:8080/TestOAuth2/dashBoard/success"
}
}
}
Any help much appreciated.
Thanks.
Try this..,.
Config:
import org.scribe.builder.api.FacebookApi
...
oauth {
providers {
facebook {
api = FacebookApi
key = 'XXX'
secret = 'YYY'
scope = 'email,read_stream,publish_actions,user_birthday,publish_stream'
callback = "http://localhost:8080/appName/oauth/facebook/callback" //callback to oauth controller of oauth plugin
successUri = "http://localhost:8080/appName/myController/facebookSuccess"
failureUri = "http://localhost:8080/appName/myController/facebookFailure"
}
}
}
MyController:
def facebookSuccess() {
Token facebookAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('facebook')]
def facebookResource = oauthService.getFacebookResource(facebookAccessToken, "https://graph.facebook.com/me")
def facebookResponse = JSON.parse(facebookResource?.getBody())
log.info "Email = ${facebookResponse.email}"
...
}
You can get working example from my git repo. Grails Oauth Plugin Demo.
Email is not part of a Facebook public_profile. The only way to get the users e-mail address is to request extended permissions on the email field. You can do this by adding a scope to the oauth provider.
config.groovy
oauth {
providers {
facebook {
api = org.scribe.builder.api.FacebookApi
scope = 'email'
...
...
}
}
}
As an example of how to return email and various public_profile fields please see below.
Take Note of: getFacebookResource params e.g. https://graph.facebook.com/me?fields=id,name,verified,age_range,email"
import grails.converters.JSON
import org.scribe.model.Token
import grails.plugin.springsecurity.oauth.OAuthToken
class SpringSecurityOAuthController {
def oauthService
def onSuccess = {
// Validate the 'provider' URL. Any errors here are either misconfiguration
// or web crawlers (or malicious users).
if (!params.provider) {
renderError 400, "The Spring Security OAuth callback URL must include the 'provider' URL parameter."
return
}
def sessionKey = oauthService.findSessionKeyForAccessToken(params.provider)
if (!session[sessionKey]) {
renderError 500, "No OAuth token in the session for provider '${params.provider}'!"
return
}
// Create the relevant authentication token and attempt to log in.
OAuthToken oAuthToken = createAuthToken(params.provider, session[sessionKey])
Token facebookAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('facebook')]
def facebookResource = oauthService.getFacebookResource(facebookAccessToken , "https://graph.facebook.com/me?fields=id,name,verified,age_range,email")
def facebookResponse = JSON.parse(facebookResource?.getBody())
println facebookResponse
...
...
}
}
public_profile (Default)
A person's public profile refers to the following properties on the user object by default:
id cover
name
first_name
last_name
age_range
link
gender
locale
picture
timezone
updated_time
verified

connect/authenticate with google using grails oauth plugin

I am trying to connect with Google using the grails oauth plugin. Following is my code
Config.groovy
oauth {
providers {
google {
api = org.scribe.builder.api.GoogleApi
key = 'XXX.apps.googleusercontent.com'
secret = 'XXXXXXX'
scope = 'https://www.googleapis.com/auth/userinfo.profile'
callback = "${grails.serverURL}/oauth/google/callback"
successUri = "${grails.serverURL}/oauthCallBack/google"
}
}
}
grails.google.api.url = "https://accounts.google.com/o/oauth2/auth"
OauthCallBackController.groovy
class OauthCallBackController {
def oauthService
def google() {
Token googleAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('google')]
def googleResource = oauthService.getGoogleResource(googleAccessToken, grailsApplication.config.grails.google.api.url)
def googleResponse = JSON.parse(googleResource?.getBody())
log.info "googleAccessToken = ${googleAccessToken}"
log.info "googleResponse = ${googleResponse}"
log.info "accesstoken = ${googleAccessToken.token}"
def googleResourceDetailed = oauthService.getGoogleResource(googleAccessToken, "https://www.googleapis.com/oauth2/v1/userinfo?access_token=${googleAccessToken.token}")
def googleResponseDetailed = JSON.parse(googleResourceDetailed?.getBody())
log.info "googleResourceDetailed = ${googleResourceDetailed}"
log.info "googleResponseDetailed = ${googleResponseDetailed}"
render params
}
}
When I trying to connect, google ask me to allow the application to access my credentials. After allowing my call back action executed(oauthCallBack/google) but I am not getting the data of my account.
Following is my output in my logs
INFO example.OauthCallBackController - googleAccessToken = Token[1/xxx , yyy]
INFO example.OauthCallBackController - googleResponse = [:]
INFO example.OauthCallBackController - accesstoken = 1/xxx
INFO example.OauthCallBackController - googleResourceDetailed = org.scribe.model.Response#2a088ca
INFO example.OauthCallBackController - googleResponseDetailed = [error:[message:Invalid Credentials, errors:[[message:Invalid Credentials, location:Authorization, reason:authError, locationType:header, domain:global]], code:401]]
I have no idea where I am wrong and why I am getting the error as response.
How can I get data from google?
Finally..,.
After lots of google search I finally figure out my problem and successfully got data from google.
The problem is in my grails.google.api.url entry in my config file.
Correct value is
grails.google.api.url = "https://www.googleapis.com/oauth2/v1/userinfo"
Now my code is
Config.groovy
oauth {
providers {
google {
api = org.scribe.builder.api.GoogleApi
key = 'XXX.apps.googleusercontent.com'
secret = 'XXXXXXX'
scope = 'https://www.googleapis.com/auth/userinfo.profile'
callback = "${grails.serverURL}/oauth/google/callback"
successUri = "${grails.serverURL}/oauthCallBack/google"
}
}
}
grails.google.api.url = "https://www.googleapis.com/oauth2/v1/userinfo"
OauthCallBackController.groovy
def google() {
Token googleAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('google')]
def googleResource = oauthService.getGoogleResource(googleAccessToken, grailsApplication.config.grails.google.api.url)
def googleResponse = JSON.parse(googleResource?.getBody())
log.info "googleAccessToken = ${googleAccessToken}"
log.info "googleResponse = ${googleResponse}"
log.info "accesstoken = ${googleAccessToken.token}"
log.info "id = ${googleResponse.id}"
log.info "name = ${googleResponse.name}"
render params
}
And my log out put is
INFO example.OauthCallBackController - googleAccessToken = Token[1/xxx , yyy]
INFO example.OauthCallBackController - googleResponse = [id:xxxxx, locale:en, link:yyyyy, name:MKB, gender:male, family_name:B, given_name:M]
INFO example.OauthCallBackController - accesstoken = 1/xxx
INFO example.OauthCallBackController - id = xxxxx
INFO example.OauthCallBackController - name = MKB
Grails Oauth Plugin Demo

Grails oauth plugin: Unknown provider linkedin, check your configuration

How to get Connected With Linked In Grails ??
Config.groovy
oauth {
linkedin {
requestTokenUrl="https://api.linkedin.com/uas/oauth/requestToken"
accessTokenUrl="https://api.linkedin.com/uas/oauth/accessToken"
authUrl="https://api.linkedin.com/uas/oauth/authorize"
consumer.key="xxx"
consumer.secret="xxx"
}
}
plugin:
compile ":oauth:2.1.0"
And GSP :
<oauth:connect provider="linkedin">Connect</oauth:connect>
But I trying to run this code.. on browser its showing this error
org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
Tag [oauthLink] does not exist. No tag library found for namespace: g
Use oauth taglib to create button to connect with linkedin rather than g tag
<oauth:connect provider="linkedin">Connect</oauth:connect>
EDIT...................................................................................
Following is my Config.groovy
oauth {
providers {
linkedin {
api = org.scribe.builder.api.LinkedInApi
key = 'xxx'
secret = 'yyy'
callback = "http://localhost:8080/test2/oauth/linkedin/callback"
successUri = "http://localhost:8080/test2/oauthCallBack/linkedin"
failureUri = "http://localhost:8080/test2/oauthCallBack/linkedinFailure"
requestTokenUrl = "https://api.linkedin.com/uas/oauth/requestToken"
accessTokenUrl = "https://api.linkedin.com/uas/oauth/accessToken"
authUrl = "https://api.linkedin.com/uas/oauth/authorize"
}
}
}
grails.linkedin.api.url = "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,date-of-birth)?format=json"
and I have a OauthCallBackController with an action linkedin
def linkedin() {
Token linkedinAccessToken = (Token) session[oauthService.findSessionKeyForAccessToken('linkedin')]
def linkedInResponse = oauthService.getLinkedInResource(linkedinAccessToken, grailsApplication.config.grails.linkedin.api.url)
def linkedinParsedResponse = JSON.parse(linkedInResponse?.getBody())
User user = User.findByLinkedInId(linkedinParsedResponse['id'])
if (user) {
springSecurityService.reauthenticate(user.username)
} else {
...
}
}
def linkedinFailure() {
render "I am back..,."
}

Can't twitter status using oAuth and .net Hammock library on Windows Phone 7

I've been able setup the oAuth calls to get the users access Token following a couple blog posts:
http://sudheerkovalam.wordpress.com/2010/08/28/a-windows-phone-7-twitter-application-part-1/
and
:/byatool.com/c/connect-your-web-app-to-twitter-using-hammock-csharp/comment-page-1/#comment-9955
But I'm having problems sending a status update. I can't find any examples so I may not be setting the proper values. Here's the code which keeps returning: "Could not authenticate with OAuth."
private void Tweet()
{
var credentials = new OAuthCredentials
{
Type = OAuthType.ProtectedResource,
SignatureMethod = OAuthSignatureMethod.HmacSha1,
ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
ConsumerKey = TwitterSettings.ConsumerKey,
ConsumerSecret = TwitterSettings.ConsumerKeySecret,
Token = _settings.AccessToken,
TokenSecret = _settings.AccessTokenSecret,
Version = TwitterSettings.OAuthVersion,
};
var client = new RestClient
{
Authority = "http://twitter.com/oauth",
Credentials = credentials,
HasElevatedPermissions = true
};
var request = new RestRequest
{
Path = "/statuses/update.json",
Method = WebMethod.Post
};
request.AddParameter("status", TwitterTextBox.Text);
client.BeginRequest(request, new RestCallback(TwitterPostCompleted));
}
private void TwitterPostCompleted(RestRequest request, RestResponse response, object userstate)
{
Dispatcher.BeginInvoke(() => MessageBox.Show(response.Content));
}
thanks for any help,
Sam
Ah figured it out finally I was using the wrong URL need to use:
Authority = "http://api.twitter.com" and not: "http://twitter.com/oauth"
Just in case other people find this I've written a blog post on using OAth with Hammock for Twitter. Might be of use to some people!

Resources