OAuth2 Login for Google Calendar API - api

I'm making a website for a football club. they have one google calender (and just one google account). on the website I'd like to have a list of upcoming events. So I've to access to Google Calendar via Google API. For Authorisation I've to use OAuth2. Is it possible to login with OAuth2 automatically so that the website visitors don't have login always via redirect (to google login site)? For example I make a the login via Java, instead of a user login? Because it's no so comfortable if every user of the website have to login, for just viewing the club calendar.

Not sure it is possible,
Important note concerning your design: if you login automatically to the club's account, it means that everyone that uses this website is logged in to Google Calendar on behalf of the club's user name. hence, everyone can CHANGE the calendar, delete events, etc.
Are you sure you want this to happen?
(you can set the login params to "read-only", but even then, it means that the club shows ALL his calendar to everyone. there is no privacy...)
I suggest that every user logins with his own creds, and the club's calendar can invite all registered users to his events....

Of course, you can do it, and even without giving the access to the visitor if you're doing this on the server side.
You need to do a initial step by hand.
After this step you get a refresh token, with this token you can regenerate the access token which you need to access to the calendar API, for instance to get the upcoming events.
You need to regenerate the access token if the previous access token is expired. In this case you also get an new refresh token. You need to save it, into a database or JSON file.
To get a refresh token you need to pass this options on authorization:
access_type: "offline"
approval_prompt: "force"
Without these options you only get an access token, no refresh token.
Here is the documentation: https://developers.google.com/accounts/docs/OAuth2WebServer#formingtheurl
And here a kind of tutorial: http://www.tqis.com/eloquency/googlecalendar.htm

Related

Clarification on Google Authentication and Authorization, with OAuth in 2022

I am writing an App and am trying to leverage Google for A&A. The app itself relies on access to the users Google Calendar, and so initially I leveraged their updated OAUTH2 library for A&A.
Here is my flow:
User goes to the index.html which has "https://accounts.google.com/gsi/client" script and google.accounts.oauth2.initCodeClient is called with my client_id, scopes, redirect url
<script src="https://accounts.google.com/gsi/client"></script>
<script>
let client;
function initClient() {
client = google.accounts.oauth2.initCodeClient({
client_id: 'xxxxx-xxxx.apps.googleusercontent.com',
scope:
'https://www.googleapis.com/auth/userinfo.profile \
https://www.googleapis.com/auth/userinfo.email \
https://www.googleapis.com/auth/calendar.readonly \
https://www.googleapis.com/auth/calendar.events',
ux_mode: 'redirect',
redirect_uri: 'http://localhost:5000/oauth2callback',
});
}
// Request an access token
function getAuthCode() {
client.requestCode();
}
The user clicks the login button, which kicks off requestCode() and they begin the login flow. They login or select their google account, then besides the unapproved app screen, they get to the consent screen with my requested scopes.
After, they are redirected to my expressjs endpoint and using the "googleapis" library I exchange with id_token for the access and refresh tokens.
...
const { tokens } = await oauth2Client.getToken(req.query.code); //exchange code for tokens
const userInfo = (
await oauth2Client.verifyIdToken({
idToken: tokens.id_token,
audience: config.google.clientID,
})
).payload;
if (!indexBy.email[userInfo.email]) { // check if user exists
const newUser = {
name: userInfo.name,
email: userInfo.email,
o_id: userInfo.sub,
picture: userInfo.picture,
r_token: tokens.refresh_token,
};
...
Ok, all good.... but not quite. The problem is, that next time the user wants to login to the app, they go through the entire flow again, including the consent screen (again).
So, after going through more docs, even looking at examples from google. I was surprised and I noticed that many of those apps used the passport oauth2 plugin :( Something i've done in the past, but was hoping to avoid that with the recently updated Google client and nodejs libraries.
Ok, how to not prompt for consent screen on subsequent logins?
Maybe separate A&A, so first I use "Sign In With Google" for Authentication, then when I get the user info, check if the user is already registered (hence I have already saved the refresh token) and they start the app.
On the other hand, if they are new (not in existing app user collection), after authenticating, I will then call the OAUTH2 authorization redirect, so again they on Googles site, this time to do the scopes api confirmation.
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed). Hopefully this will still work ok when things come up with expired/invalid refresh token (fingers crossed the default google library handles that).
When doing the Authorize for consent, can I pass something from the previous Authenticate flow so they don't need to do that again.
Or maybe when doing the Authenticate process (Google Identity Service), there is some flag or param so that if they have already consented, they don't have to do that again on subsequent logins.
Incase I wasn't clear, in a nutshell the question is: should I be doing Authenticate for login, separately from Authorization (oauth2 token). Or should I go right into the Authorization flow, which first Authenticates the user, and can I skip the Authorization consent screens if they've already done that. Or maybe there's another way which is the best practice.
Thanks for your attention.
Background info
Authentication is the act where by a user logs in into a system using their login and password. With authentication we know that the user is behind the machine. For this we use Open id connect, which was built on top of Oauth2. Open id connect returns and id_token which can be used to identify the user, it is often a jwt containing some claims to identify the subject or the user behind the Authentication.
The scope used for open id connect is profile and email. open id connect grants you consent to access a users profile information.
This is an example of the decrypted id token returned by google from a simple call using profile scope only. All this id token is telling you is who the user behind the machine is.
{
"iss": "https://accounts.google.com",
"azp": "4074087181.apps.googleusercontent.com",
"aud": "4074087181.apps.googleusercontent.com",
"sub": "1172004755672775346",
"at_hash": "pYlH4icaIx8PssR32_4qWQ",
"name": "Linda Lawton",
"picture": "https://lh3.googleusercontent.com/a-/AOh14GhroCYJp2P9xeYeYk1npchBPK-zbtTxzNQo0WAHI20=s96-c",
"given_name": "Linda",
"family_name": "Lawton",
"locale": "en",
"iat": 1655219027,
"exp": 1655222627
}
In the same call google also returned an access token. Now my call contained only the scope for profile, due to the fact that its open id connect. This means that I will only have access to the data that the profile scope would grant access to. In this case most of what is behind the Google people api.
Note: The user does not see a consent screen with open id connect, even though they are consenting to profile scope. It is assumed by signing into your account that the system you are logging into would have access to your profile info.
Authorization
Authorization is the process by which a user grants your application authorization to access their private user data. The user is shown a consent screen where they consent to your application accessing data defined by some scopes.
In the case of google calendar api there are serval
https://www.googleapis.com/auth/calendar See, edit, share, and permanently delete all the calendars you can access using Google Calendar
https://www.googleapis.com/auth/calendar.events View and edit events on all your calendars
https://www.googleapis.com/auth/calendar.events.readonly View events on all your calendars
https://www.googleapis.com/auth/calendar.readonly See and download any calendar you can access using your Google Calendar
https://www.googleapis.com/auth/calendar.settings.readonly View your Calendar settings
In this case you are only given an access token this is again Oauth2 it is authorization to access the users calendar data it is not authentication this is not related to login.
Your question
So, first question, is that the best practice with most apps with leverage a Google API via OAuth? To first Authenticate, then possibility Authorize (as needed).
You would do both at the same time.
When you authencation your user make sure to include your google calendar scope then the access token and refresh token returned will grant you access to google calendar.
I am going to assume that you have some kind of user system. When you store the user be sure to store the refresh token that is returned.
As far as Authentication goes i will assume you either have a remember me system which will set a cookie on their machine and remember the user so that you can then get the refresh token from their system the next time they come back.
If they did not chose to select a remember me option then will then have to login every time they visit your site but part of the login will return the "sub": "1172004755672775346", this is the users id on google system so you can use that in your database to match the user when they come back.
Your question is quite complex and will depend upon the type of system you have what it is designed to do as well as what programming language you are using. That being said I hope this very long answer clears things up a bit.

Obtain user information on Actions on Google Through OAuth in AoG?

Account Linking provides several ways of linking users to their own accounts such as their Google account or Twitter account.
I chose OAuth in Actions on Google website to do OAuth 2.0 Authorization Code Grant for obtaining access token in exchange for data resources. When I linked a user to a Google account Google Sign-In enabled, the fetching of user information was easy because the data is stored under payload, but OAuth implementation does not seem like it produces user data under payload inside User object.
So should I make an API call to the third party to fetch the user data and store that personal data to a database in this case? I wondered if there is a way that Google prepares on behalf of developers. If not, then greeting a user who visits my app again by saying 'Hello, {person name}' gets tedious...
You have two options with Account Linking.
In the case you describe, you're providing an OAuth endpoint and getting an auth token from the Assistant, and you are responsible for taking this token and using it to determine who the user is so you can get whatever you know about him. The token is one that you issue and control, so presumably you have that info in your database already. If you are reusing a token from another service, that service should be able to tell you who they are.
It sounds like you're using using a Google Sign In, however, in which case it is easier to use Google Sign In for Assistant. Once the user has signed into your service (either through an app or webapp) and granted permission to your service, then they will also be able to gain access through the Assistant. You will get an id token which can be decoded to get profile information about the user including their Google ID and name.

Is there a way to have a 'Google Sign In' button for google accounts that are not signed up with Google Plus?

I'm working on an internal website for the company I work for. The website will be only available to company staff. We use Google Apps for Business, so we would like authentication to be done using our google accounts.
I've gone through 'google sign in' samples from here: https://developers.google.com/+/
It works, but the problem we run into is that it requires the user to sign up to Google+. This is a speed bump we would prefer not to have.
Are there any ways around this? Thanks.
It shouldn't be too hard to roll your own sign in using the lower levels of Oauth, eg 'email' scope. It's hard to give a more specific answer because it depends on your architecture (eg. are you predominantly server-side or client-side) and what kind of session do you want to create by the sign in process. For example, if you are client/REST based, you probably don't want any session at all as REST encourages statelessness. On the other hand, if you are more web based, serving static pages, you will want a session.
In simple terms, you will be doing something that generates an access token, and then processing that access token to determine the email address (or Google ID) of the person who created it. You will then establish some sort of session (eg. using session cookies) that identifies future requests from that user.
Feel free to add some more detail to your architecture and I'll try to finesse the answer.
For simple http servlet sessions, it will be something like.
User requests a protected page
servlet detects that there is no session and/or session has no authenticated user
servlet redirects to an Oauth page to request an access code. something like
https://accounts.google.com/o/oauth2/auth?redirect_uri=xxx&response_type=code&client_id=zz&approval_prompt=auto&scope=email
NB research the exact URL, don't rely on this to be exact
If the user isn't logged on, he'll be prompted; if he has multiple logins, he'll be prompted; if he hasn't yet granted email access, he'll be prompted. If none of these conditions are met (the normal case) he won't see anything.
Browser will redirect to the redirect_uri, carrying an access token (or an auth code if this is the first time the user has used the app)
Post the token to the Google userinfo endpoint, and you will receive a decode containing the email address
Store the email into a session object (or retrieve your own user object and store that)
redirect back to the originally requested page. You can use the OAuth state parameter to pass that around
et voila. all future page requests from that user will be within a session containing some user identification.
NB This is just an outline and I may even have missed a step. You will still need to do your own OAuth research.
Apparently not:
(..) if a Google user who has not upgraded to a Google+ account clicks
on the Sign in with Google+ button, the same consent dialog that opens
will take the user into an account upgrade flow.
Weirdly the docs for OAuth2 states:
Google+ Sign-In works for all users with a Google account, whether or
not they have upgraded to Google+.

Can LinkedIn's access token renewal flow be performed on the server?

In the Facebook's Graph API, once we have initially authenticated the user, we can interact directly with the API (from the server) to obtain a long-lived page access token. This long-lived page access token never expires. (https://developers.facebook.com/docs/facebook-login/access-tokens/)
In reading LinkedIn's documentation, it appears that it is impossible to obtain an access token with an indefinite (non-expiring) access token. It seems that they expire every 60 days. However, these access tokens can be refreshed before the 60 days is up.
What isn't entirely clear from the documentation is whether or not the access token renewal can be performed on the server alone without the client's interaction. The language of the documentation suggests that the interaction of the client (browser) is required, but nothing is explicitly stated.
So, my question is, is it possible to renew a LinkedIn access token using the server alone, without the interaction of the client (browser)?
Relevant LinkedIn reference material: https://developer.linkedin.com/documents/handling-errors-invalid-tokens
As it turns out, the access tokens of linkedin can not be refreshed without having linkedin user logging in to linkedin. Please refer to the first comment here by LinkedIn employee which clearly states a note that "this refresh will only work if the user is still logged into LinkedIn (authenticated) and the current access token isn't expired. Otherwise, the user will be presented with the login dialog again."
I guess that is now a major issue for those who were previously storing the linkedin access tokens to database for later use.
I am mentioning few links here which refer to the issue with refreshing linkedin oauth2 tokens (hope this makes it clear for everyone who is struggling with the same issue):
1) This refresh will only work if the user is still logged into LinkedIn (authenticated) and the
current access token isn't expired. Otherwise, the user will be presented with the login
dialog again.
2) There is no way to refresh the token using the old authentication token/secret. User
needs to log into linkedin in order for you to refresh the tokens. We use this flow as it
protects our members and their data in the best possible manner.
3) Refreshing an access token is very simple and can happen without an authorization
dialog appearing for the user. In other words, it's a seamless process that doesn't affect
your application's user experience. Simply have your application go through the
authorization flow in order to fetch a new access token with an additional 60 day life span. When the following conditions exist:
-User is still logged into Linkedin.com
-The current access token isn't expired (within the 60 life span)
We will automatically redirect the user back to your redirect_uri without requiring them to reauthorize your application. If they don't exist, we'll prompt them to login and then redirect
them.
4) We have also standardized the duration of the authorization tokens. Previously, members
could choose to grant tokens that were as short as one day or as long as forever. Now all
tokens are 60 days in length, with the ability for you to extend them in a series of rolling 60 day increments whenever the member comes back to your application. To prevent a bad user experience in your application, be sure to proactively refresh tokens and elegantly route any expired tokens through a refresh flow.
5) As long as the user is logged into LinkedIn and their current access token hasn't expired, you can fetch an access token with a 60 day lifespan the next time the user comes to your application.
I had the same question and the LinkedIn docs and forum posts are confusing, but I'm pretty sure now that it's not possible to do it programmatically without user intervention (i.e. the user needs to login to your app via LinkedIn auth to refresh the token).

Authenticating a Google Places owner via the API

I am currently developing an app using the Google places API..
https://developers.google.com/places/documentation/
I want to use the Events methods, so that a Place/Business owner can add events..
https://developers.google.com/places/documentation/actions#event_intro
However I obviously need to restrict it, so that only the Business owner can create events for their Business. Is there anyway of authenticating a user via a Google api, to confirm that they are the Place owner? I looked at Google+ however there is no reference to any 'Places' setup by that user in the people request.
Looks like this is possible now. The workflow would be the following:
Your user triggers a places search and selects a specific place in the result
Your user selects an option in your app to claim they are the owner of your place
Your user is redirected into an OAuth flow to Google Places where they login with their Google credentials
Once authenticated, your app is provided with an OAuth token for the user
Your app submits that token along with a Place reference to a Places API owner verification service
The Places API returns a yes/no as to whether the user concerned is the verified owner of the Place
Source - https://code.google.com/p/gmaps-api-issues/issues/detail?id=3894 - comment #3
Enjoy!