How to extract the ID token after google authentication if I use the scope openid in java? - spring-boot

I made a small spring boot project and I need the id token. When I try to open an endpoint what requires google login I can login and then see the result of the endpoint calling. My question is that how to get the ID token? Where it can be found? How to extract it?
I send the openid scope but no idea where is the id token can be found to put the name/email/whatever on the front page if I want to:
security.oauth2.resource.user-info-uri = https://www.googleapis.com/userinfo/v2/me
security.oauth2.client.client-id = clientid
security.oauth2.client.client-secret = clientsecret
security.oauth2.client.user-authorization-uri = https://accounts.google.com/o/oauth2/v2/auth
security.oauth2.client.access-token-uri = https://oauth2.googleapis.com/token
security.oauth2.client.scope = openid email profile
Thanks in advance.

Related

Error using google API and OAUTH2 in Python to get user info

My web app is successfully going through google's recommended flow to get credentials to query Google Drive API. This works fine. However, when I try to use the same credentials already obtained to get the user's email and name, I get an error.
Here I retrieve credentials and query Google Drive API. This works perfectly fine
def analyze():
credentials = getCredentials()
drive_service = googleapiclient.discovery.build('drive', 'v3', credentials=credentials)
theFiles = drive_service.files().list(pageSize=1000,q="trashed=false", fields="files(id,name,modifiedTime, size)").execute() #THIS WORKS
Right after that, I try to use the SAME CREDENTIALS to get user info, but now it doesn't work
oauth2_client = googleapiclient.discovery.build('oauth2','v2',credentials=credentials)
user_info= oauth2_client.userinfo().get().execute() #THIS FAILS
givenName = user_info['given_name']
Error: https://www.googleapis.com/oauth2/v2/userinfo?alt=json returned "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.">
SOME OTHER IMPORTANT FUNCTIONS:
def getCredentials():
*Loads credentials from the session.*
sc = session['credentials']
credentials = google.oauth2.credentials.Credentials(token=sc.get('token'),
client_id=sc.get('client_id'),
refresh_token=sc.get('refresh_token'),
token_uri=sc.get('token_uri'),
client_secret=sc.get('client_secret'),
scopes=sc.get('scopes'))
the credentials are obtained in the callback page:
#app.route('/OAcallback')
def OAcallback():
flow =google_auth_oauthlib.flow.Flow.from_client_secrets_file('client_id.json', scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile'])
flow.redirect_uri = return_uri
authorization_response = request.url
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
* Store the credentials in the session.*
credentials_to_dict(credentials)
Please help me understand why my credentials are not working when trying to get user info. What should I change?
Thanks in advance!!!
You are only requesting the profile scope. To also request the email address add the scope email.
Change this part of your code from:
scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile']
to:
scopes=['https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile' 'email']

Identity Server4 access logged in users access token

I am using the Identity server 4 ( with .Net core 2.0 ) and all the clients are working perfectly and can retrieve the access_token. In my MVC client, i am using following command to retrieve the access_token.
var accessToken = await this.HttpContext.GetTokenAsync("access_token");
But for a functional requirement , I need to get this access_token inside my Identity server itself. The same code returns null when I'm trying to use it inside my Identity server's code.
It would be great if someone can help me on this.
May be your request authentication is not included the access token.
I guess it is rare case that Idm using access token.
You should be able to find out most of the information looking at the URL !! once you get the clientId then making a call to ConfigurationStore.
In general the following are the ways to get access_token
var authenticateInfo = HttpContext.Authentication.GetAuthenticateInfoAsync("oauth2").Result;
var accessToken = await HttpContext.Authentication.GetTokenAsync("access_token"); 2.0
string accessToken = authenticateInfo.Properties.Items[".Token.access_token"];

Google Social Login with Auth0 Tokens for [Authorized] API Calls

Anyone here implemented social login through Google for Auth0? I have an issue with the tokens (access and id) being returned after validating with Google.
Here's my code:
var waGoogle = new auth0.WebAuth({
domain: 'testApplication.auth0.com',
clientID: '************',
redirectUri: 'http://localhost:8080/'
})
waGoogle.authorize({
connection: 'google-oauth2',
responseType: 'id_token token'
}, function(err, authResult){
if(err){
console.log('Google Login Error')
console.log(err)
}
});
Google screen shows up, I log in and I am redirected back to my application. From the application, I parse the URL so that I can get the access and id tokens.
let getParameterByName = (name) => {
var match = RegExp('[#&]' + name + '=([^&]*)').exec(window.location.hash);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var access_token = getParameterByName('access_token')
var id_token = getParameterByName('id_token')
Issue I am having is that none of the tokens allow me to call my APIs (asp.net web api) which are decorated with the [Authorize] attribute. It returns a:
401 (Unauthorized)
I know that my API is working, as using the normal
Username-Password-Authentication
method where I also obtain an access token, my api calls are just pulling through.
Are there any next steps which I need to do after obtaining the access and id_token from Google? Do I need to make an additional call to Auth0 to obtain the proper access token to be able to call my web api?
Thanks.
The token you are looking for is called an IdP (Identity Provider) Token. This is different from the one issued to you after logging in. There are pretty good instructions on the Auth0 site that walk you through the process of getting that token.
Here is the overview of IdP tokens
Here is a step-by-step guide to calling the Identity Provider
The tl;dr:
To access the IdP token you need to call the Auth0 management API from your server. For that, your server will need a management token. Then use that token to access the endpoint /api/v2/users/[USER_ID]. In the object sent back from Auth0, look for the google identity and extract that token.
Also note, you should probably keep that token on your server if you can. If you can keep those power tokens away from your client your users will be happy.

Spring boot webapp as client of Google Oauth2

I'm writing a webapp using Spring Boot. For my project, I need to connect to Google for retrieving calendar information about users.
So, I integrate Spring security Oauth2 for user connection and after I want to use the Google calendar API.
The connection is ok and after it, Google redirects to a page of my webapp defined by this controller:
#Controller
class ConnectedController {
private String token
#RequestMapping("/welcome")
String welcome(Principal principal,
Model model) {
OAuth2Authentication auth = principal
model.addAttribute("user", auth.userAuthentication.details)
// credential
def api = new CalendarApi()
token = auth.details.tokenValue
println "Token: [$token]"
api.fetch(token)
return 'welcome'
}
}
For the Calendar API, I need the access token value and the refresh token value. I find the access token value in the principal object but where is the refresh token?
For information, I configured the authorization like below to have the resfresh token (normally):
userAuthorizationUri: https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent
As I interpret the google Oauth2 doc you get a authorization code when consent is given by the user. And this code should be used to get an access token and a refresh token from the API.
The result is an authorization code, which the application can
exchange for an access token and a refresh token.
Have you tried this?

LinkedIn JS API token exchange to REST token using Spring Social for Linkedin

I'm trying to do the following:
Let the user authenticate and authorize through Linkedin using Linkedin JSAPI, then take the authentication details and send them to my server to get the user profile via server side communication.
I got the Linkedin button setup, got the authorization cookie all the way to my server (as described here), and was able to verify that the token is indeed signed correctly with my secret key.
Now I'm stuck at the point where I am supposed to take the token I got from JSAPI and exchange it for an access token.
This is the code I'm using, as mentioned it uses Spring Social for Linkedin, and it doesn't work as it throws a 401 Unauthorized response:
LinkedInConnectionFactory connectionFactory =
new LinkedInConnectionFactory(myLinkedinId, myLinkedinSecret);
OAuth1Operations oauthOperations = connectionFactory.getOAuthOperations();
AuthorizedRequestToken art = new AuthorizedRequestToken(new OAuthToken(codeIGotFromJSAPI, aSecretKey), whereDoIGetThisSignature);
OAuthToken accessGrant = oauthOperations.exchangeForAccessToken(art, null);
if (accessGrant == null) return null;
Connection<LinkedIn> connection = connectionFactory.createConnection(accessGrant);
if (connection != null) {
LinkedIn linkedin = connection.getApi();
return linkedin.profileOperations().getUserProfile();
}
What I'm actually confused about is the AuthorizedRequestToken object. The codeIGotFromJSAPI part is simple enough I think, it's just access_token, but what about aSecretKey, is it just my linkedin secret key? what about whereDoIGetThisSignature, how do I create that one? Do I use the same hash method as I used to validate the linkedin response and hash the access_token with my secret linkedin key? In the linkedin page, it says:
You need to pass four values as query parameters:
oauth_consumer_key, to identify yourself
xoauth_oauth2_access_token parameter, set to the value of the access_token field in the cookie.
signature_method set to HMAC-SHA1
signature, calculated as described in the OAuth 1.0a spec
So (1) is automatically done by the connection I suppose, (2) is the access token I provided, but how do I do (3) and (4)?
Lets suppose I get the following data in the JSAPI cookie set by Linkedin:
{
"signature_method":"HMAC-SHA1",
"signature_order": ["access_token", "member_id"],
"access_token":"AD2dpVe1tOclAsNYsCri4nOatfstw7ZnMzWP",
"signature":"73f948524c6d1c07b5c554f6fc62d824eac68fee",
"member_id":"vvUNSej47H"
"signature_version": 1
}
What do I need to do with it to go through the next step?
Use the following process:
Read the cookie
Transform "signature":"..." to &signature=...
Transform "signature_method":"HMAC-SHA1" to &signature_method=HMAC-SHA1
Transform "member_id":"..." to &oauth_customer_key=...
Transform "access_token":"..." to &xoauth_oauth2_access_token=...
Append all to the LinkedIn url plus ?
The LinkedIn JSAPI Token Exchange as described in Exchange JSAPI Tokens for REST API OAuth Tokens is currently not supported by Spring Social, according to a Spring forum discussion on this topic.
But there are implementation available to solve this task without Spring Social by using standard OAuth libraries available for Java. The LinkedIn user's access token, that you get from the exchange, can be put into a new AccessGrant object which can be used to create a Spring Social Connection<?> in the user's ConnectionRepository.
The code published in the LinkedIn developer forum discussion shows how to use Scribe to perform the exchange. The request that has to be sent to LinkedIn is a standard OAuth request but must ship the access_token field from the JSAPI token object as a HTTP query parameter xoauth_oauth2_access_token. The member_id that is also available to you is just for your information, and the signature allows you to verify both access_token and member_id without querying LinkedIn.

Resources