connect/authenticate with google using grails oauth plugin - grails

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

Related

Grails: Oauth Twitter userID from token

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.

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

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..,."
}

Grails Spring Security and CAS issue

I have installed Spring Security using s2-quickstart and the Spring Security CAS plugin. I have the CAS plugin set up correctly (I believe) but when I try to visit the localhost:8080/caslogin/j_spring_security_check page to force a CAS login I am redirected to the default Spring Security log in page rather than the CAS login page that our company has set up. Does anyone know what might be causing this behavior? Here is my current CAS setup in Config.groovy:
grails.plugins.springsecurity.cas.loginUri = '/login'
grails.plugins.springsecurity.cas.serverUrlPrefix = 'https://cas-server/cas'
grails.plugins.springsecurity.cas.key = 'grails-spring-security-cas'
grails.plugins.springsecurity.cas.filterProcessUrl = '/j_spring_security_check'
grails.plugins.springsecurity.cas.serverName = 'http://localhost:8080'
grails.plugins.springsecurity.cas.serviceUrl = 'http://localhost:8080/caslogin/j_spring_security_check'
grails.plugins.springsecurity.cas.proxyCallbackUrl = 'http://localhost:8080/caslogin/secure/receptor'
grails.plugins.springsecurity.cas.proxyReceptorUrl = '/secure/receptor'
grails.plugins.springsecurity.cas.active = true
grails.plugins.springsecurity.providerNames = ['casAuthenticationProvider']
// Added by the Spring Security Core plugin:
grails.plugins.springsecurity.userLookup.userDomainClassName = 'com.mycompany.caslogin.User'
grails.plugins.springsecurity.userLookup.authorityJoinClassName = 'com.mycompany.caslogin.UserRole'
grails.plugins.springsecurity.authority.className = 'com.mycompany.caslogin.Role'
We have successfully used CAS in a Grails application, check my Config.groovy below:
In my case, when I try to go to localhost:8080/MyApp/j_spring_cas_security_check I get an access denied 404.
grails.serverURL = "http://192.168.10.12:8080/MyApp"
plugins {
springsecurity {
active = true
rejectIfNoRule = false
password.algorithm = 'SHA-256'
securityConfigType = grails.plugins.springsecurity.SecurityConfigType.Requestmap //url permission
apf.filterProcessesUrl = '/j_spring_security_check'
auth {
forceHttps = false
loginFormUrl = '/access/login'
ajaxLoginFormUrl = '/access/login?remote=true'
}
adh {
errorPage = '/access/denied'
ajaxErrorPage = '/acesso/denied?remote=true'
}
ajaxHeader = 'X-Requested-With'
failureHandler {
ajaxAuthFailUrl = '/access/fail?remote=true'
defaultFailureUrl = '/access/fail?login_error=1' //TODO
}
successHandler {
defaultTargetUrl = '/'
alwaysUseDefault = false
}
// Configuracao do CAS
providerNames = ['casAuthenticationProvider']
cas {
serverUrlPrefix = 'https://mycompany.com.br:8443/cas'
loginUri = '/login'
proxyReceptorUrl = '/secure/receptor'
serviceUrl = "${grails.serverURL}/j_spring_cas_security_check"
proxyCallbackUrl = "${grails.serverURL}/secure/receptor"
}
logout.afterLogoutUrl = 'https://mycompany.com.br:8443/cas/logout?service=${grails.serverURL}/'
// Customizacao de Entidades
userLookup.userDomainClassName = 'br.com.mycompany.app.access.User'
userLookup.authoritiesPropertyName = 'permissions'
authority.className = 'br.com.mycompany.app.access.Permission'
requestMap.className = 'br.com.mycompany.app.access.UrlAccess'
requestMap.configAttributeField = 'ruleExpression'
}
}

Rest plugin: Setting cookie does not work

I want to invoke authenticated URL on server which is SSO authenticated. For this, I am coping cookies which are there in request to HTTPClient. Below code works fine.
def cookies = []
request.getCookies().each {
def cookie = new BasicClientCookie(it.name, it.value)
cookie['domain'] = it.domain
cookie['path'] = it.path
cookie.secure = true
cookies.add(cookie)
}
// **** Setting cookies using header *****
def output = withHttp(uri: "https://testserver.com") {
def builder = delegate;
def html = get(path : '/testactoin.do',
headers:['Cookie':cookies.collect{it.name+"="+it.value}.join("; ")],
contentType : ContentType.XML,
query :
[
query: params.query,
count: params.count,
cacheName: 'contentStoreCityState',
filterString: 'address.country=CA,GB,US'
]
)
return html
}
However, if I try to set cookies using api it does not work. See code snippet below:
def cookies = []
request.getCookies().each {
def cookie = new BasicClientCookie(it.name, it.value)
cookie['domain'] = it.domain
cookie['path'] = it.path
cookie.secure = true
cookies.add(cookie)
}
def output = withHttp(uri: "https://testserver.com") {
def builder = delegate;
// **** Setting cookies using api call *****
cookies.each {
builder.client.cookieStore.addCookie(it)
}
def html = get(path : '/testactoin.do',
contentType : ContentType.XML,
query :
[
query: params.query,
count: params.count,
cacheName: 'contentStoreCityState',
filterString: 'address.country=CA,GB,US'
]
)
return html
}
What is issue in setting cookies using addCookie method? Neither it generate any exception nor any warning message.
In your first code snippet you are setting Cookie, but the header is actually Set-Cookie.

Resources