I have a mobile app communicates with a server. For authentication in the mobile app, I'm using sign in with google. The sign in returns an accessToken which I send to my server and verify using google-auth-library as suggested here: https://developers.google.com/identity/sign-in/web/backend-auth
import GoogleAuth from 'google-auth-library'
const auth = new GoogleAuth()
const client = new auth.OAuth2(MyClientId, '', '')
apiRoutes.use((req, res, next) => {
// get the token from the request
const token = req.token
if (token) {
// verify secret with google
client.verifyIdToken(token, MyClientId, (err, payload) =>
// proceed with the user authenticated
...
Is it necessary to make this call with every request that the user makes? Would it be good practice to do some sort of caching? Or to have my own implementation of JWT on my server that includes the google payload?
No, the server should usually creates an account for the user once it validates the access token, saving the Google ID in the database along other user details (ID, email, name etc), and then returns an access token to the mobile application.
Once the latter (usually stored locally) expires, it can be refreshed without prompting the user for permission.
Related
I am getting an access token like this:
private async _promptForToken(scopes: string[], prompt: "none" | "consent"): Promise<string> {
const that = this
return new Promise(resolve => {
const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.clientId,
scope: scopes.join(' '),
callback: function (tokenResponse) {
that._storeTokenResponse(tokenResponse)
resolve(tokenResponse.access_token)
}
})
tokenClient.requestAccessToken({prompt})
})
}
I storing the token in local storage. If I leave the browser for an hour, so the access token expires, and I come back to my app and click a button that requires a new access token, I am requesting the new token using this code:
this._promptForToken(scopes, 'none')
In other words, I am asking for the same access permissions, but without consent. When I do that I get back a response like this:
{error_subtype: "access_denied", error: "interaction_required"}
Which I can't find documented anywhere, but that's another issue.
If instead, I ask for a new access token using consent i.e.
this._promptForToken(scopes, 'consent')
The Google dialog box for permissions pops up for a second, then disappears, which is horrible UX. And this will happen every time an access token expires. Horrible I say!
What is the recommended way to request a new access token?
Context: browser only, so implicit flow only, I do not want to have to maintain refresh tokens in the backend.
I'm using the Google Login iOS SDK to login, then passing GIDGoogleUser.authentication.idToken to the server, which I'm then verifying in Node JS. The verification in the code below works fine. "payload" var ends up being correct with basic information about the user.
How do I translate the idToken into credentials that I can use to git the people.get endpoint? (I want to know whether the user is using the default Google profile photo or not, and that is available from the people.get endpoint.) This does not seem to be documented anywhere.
https://developers.google.com/people/api/rest/v1/people/get
var auth = new GoogleAuth;
var client = new auth.OAuth2(GoogleUtils.clientIDs, '', '');
client.verifyIdToken(
token,
GoogleUtils.clientIDs,
// Or, if multiple clients access the backend:
//[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3],
function(e, login) {
if (e) {
return next(e, null);
}
var payload = login.getPayload();
return next(null, payload);
});
Thanks for your help. I can't seem to find any of this info in the documentation. Google's APIs are very poorly documented it seems.
Unfortunately, as noted, the current ID token payload does not say whether the photo is the default one (probably something we should add). If you need an access token to call Google's REST APIs (such as people.get) for more user data, then you need to obtain an OAuth auth code, and exchange it for access and refresh tokens, as documented at https://developers.google.com/identity/sign-in/ios/offline-access
I am using the Passport AAD project with the bearer strategy to protect my endpoints. After I receive tokens with the OIDC strategy when logging in, I can't seem to get the bearer strategy to validate the signature of the access token. I get:
authentication failed due to: invalid signature
I have no problems validating the id_token, but I would prefer not to use this for our client app if the id_token can't be refreshed with AAD. Also, when using jwt.io to test the validation with the published public keys, I see the same issue (can validate the id_token, but not the access_token).
Am I missing a step when grabbing the access token, or is there a gap in my understanding of how access tokens are validated?
Update with more details
I am requesting an access token from my tenant:
identityMetadata: https://login.microsoftonline.com/your_tenant_name.onmicrosoft.com/.well-known/openid-configuration,
responseType: 'id_token code'
Using the OIDCStrategy in the AAD Passport project.
const callbackOIDC = (iss, sub, profile, accessToken, refreshToken, params, done) => {
return done(null,{
profile,
accessToken,
refreshToken
});
};
passport.use(new OIDCStrategy(config.creds, callbackOIDC));
Then I run authenticate, shown below:
auth.adCallback = function (req, res, next) {
passport.authenticate('azuread-openidconnect', {
response: res,
resourceURL: 'https://graph.microsoft.com',
session: false
}, function (err, user, info) {
console.log(user.access_token);
})(req, res, next);
};
I think I may have been asking for a graph access token above by specifying the resource URL. If I remove that resource URL, I still get an access token, but the bearer strategy throws an invalid token error (instead of an invalid signature error). Is there a different resource URL I should be setting to match with my tenant and get the access token I'm looking for?
What access tokens are you requesting? If the access token is meant to be used against the Microsoft Graph, for example, it is the Graph's task to validate them- not your app's.
Can you expand on the exact scenario you are trying to implement, and at what point you need to refresh id_tokens?
I wrote desktop application on java, which have access to the Google drive. (it just uploads and downloads files).
At the moment access type is online. when I need to access files/folders to the drive, I
redirect he browser to a Google URL and get access code:
String code = "code that was returned from brouser"
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
GoogleCredential credential = new GoogleCredential().setFromTokenResponse(response);
everything works well! but I need to have that redirection only first time.
When I google, in the Google Drive API documentation I found that I can get refresh token via browser redirection and save it on DB for instance. (In the other word, I can use offline access).
And every time when I need to read data from google drive, I get access token using refresh token without redirection. is not it?
so I get refresh token like that:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=695230079990.apps.googleusercontent.com&scope=https://www.googleapis.com/auth/drive&response_type=code&redirect_uri=https://localhost
question 1
I get code, from the browser redirecting. it's refresh token, is not it?
now, I need to get access token using that refresh token.
$.ajax({
type: "POST",
url: 'https://accounts.google.com/o/oauth2/token',
data: {
client_id: "695230079990.apps.googleusercontent.com",
client_secret: 'OWasYmp7YQ...4GJaPjP902R',
refresh_toke: '4/hBr......................xwJCgQI',
grant_type: 'refresh_token'
},
success: function(response) {
alert(response);
}
});
but I have error 400;
question 2) when I try to change redirect url I have that error: *
Invalid parameter value for redirect_uri: Non-public domains not allowed: https://sampl.ecom
so, must I create web applications Client ID , instead of installed application from google APIs console? Can't I change Redirect URI in installed application? I'm confused, I don't know, which should I use.
1) when you try to have offline access, you get authorization code which may be redeemed for an access token and a refresh token.
For isntance:
https://accounts.google.com/o/oauth2/auth?access_type=offline
&approval_prompt=auto
&client_id=[your id]
&redirect_uri=[url]
&response_type=code
&scope=[access scopes]
&state=/profile
after you get authorization code, you cat get refresh token.
static Credential exchangeCode(String authorizationCode)
throws CodeExchangeException {
try {
GoogleAuthorizationCodeFlow flow = getFlow();
GoogleTokenResponse response =
flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute();
return flow.createAndStoreCredential(response, null);
} catch (IOException e) {
System.err.println("An error occurred: " + e);
throw new CodeExchangeException(null);
}
}
See the section on Implementing Server-side Authorization tokens for more information.
and after you get refresh token , you must save it. see that sample for mor information.
2) If you don't have installed application, you should create web applications to change redirecting URL.
I'm working with client who provided me with somewhat vague
instructions. Here's what I'm doing (using CommonsHttpOAuthConsumer as
consumer and DefaultOAuthProvider as provider)
I'm able to get response token from doing this:
String requestToken = provider.retrieveRequestToken
(OAuth.OUT_OF_BAND);
this is in form of URL with params so I'm parsing the actual token
out for example:
https://foobar.com/oauth/login_authorize?oauth_token=XRFCGPbES3M2bYZy...
Now - the instructions that I get say:
Given the request token obtained in step 1, login with the user’s
credentials (name and password) as POST parameters and sign the
request with the request token/secret
POST https://foobar.com/oauth/login_authorize
That's where I'm having difficulties. Obviously I have to input that
requestToken somewhere so I do this (post is HttpPost that contains user credentials):
consumer.setTokenWithSecret(requestToken, SECRET);
consumer.sign(post);
It doesn't work. It actually generates 200 status but what I get is a
generic error message.
retrieveRequestToken does not return a request token, it returns an authenticationUrl that you need to send your users to so they can sign in. Request token is saved in provider object.
String authenticationUrl = provider.retrieveRequestToken( call_back_url )
Note: According to the oauth standard the users sign in on the providers site with their credentials. After they have done that you (as a consumer) can get the Access Token and after that you can access their data on the providers site.
// After user has signed in
provider.retrieveAccessToken(null)
// access token is saved in provider and provider knows which consumer uses it
// so now you can sign with your consumer and connect with the request
URL url = new URL( protected_resources_url )
HttpURLConnection request = (HttpURLConnection) url.openConnection();
consumer.sign(request)
request.connect()
If you have the user credentials you can do the authorization in your script
// Using grails and functional-tests
get(authenticationUrl)
// Image the site shows a simple form with username/password and a login button
setRedirectEnabled false
form {
username = "mario"
password = "peach"
click "login"
}
And then do retrieveRequestToken and the code mentioned above
Hope this helps you
// Jonas