obtain a Google OAuth 2.0 Bearer token from a client and secret [duplicate] - google-oauth

This question already has answers here:
How do I authorise an app (web or installed) without user intervention?
(2 answers)
Closed 5 years ago.
I have a client id and client secret for my Google Container Engine app obtained via Credentials and I just want to do some local testing of the JSON API endpoints.
How can I convert this into a Bearer token so that I can just get some work done? Is there a Google page where I provide these things and get a token that I can use in my app?
I don't want to have to write an entire OAuth handling mechanism at this point in time (which would use the flow described in oauthplayground). It's an app to be run only for my account, in headless mode, on a trusted machine, to manage my cluster.
NOTE: must not require any proprietary software installations (e.g. the Google SDK).

Google provides an API Client Library for Java, which itself depends on an OAuth client library.
For the project of 9Cards launcher for Android, within the back-end, we had to use this library to fetch applications usage statistics from Google Analytics. In our code, because it is a case of "server to server" authentication, we use a Service Account's credentials. The code issues a request from Google a short-lived OAuth2 Auth Token. The library may provide similar features if you use a Client-ID and Client-Secret.
Regarding the issue of licenses, the library is published under Apache License v2, so in that regard it is not too proprietary.

I have a client id and client secret for my Google Container Engine app obtained via Credentials and I just want to do some local testing of the JSON API endpoints.
Good start. I guess by "the JSON API endpoints" you mean the Google APIS. Make sure you created OAuth Client IDs and not one of the other options.
How can I convert this into a Bearer token so that I can just get some work done? Is there a Google page where I provide these things and get a token that I can use in my app?
Yes the OAuth Playground will do that for you. The detailed steps and sample code to consume the token is at How do I authorise an app (web or installed) without user intervention? (canonical ?)
I don't want to have to write an entire OAuth handling mechanism at this point in time (which would use the flow described in oauthplayground).
Follow the steps linked to above and you will see that you don't need to write any code at all. Once you have the refresh token (a one time procedure), you're all set. I exaggerate slightly, you do need one line of code to post the refresh token to the Google Oauth endpoint to fetch an access token. See the bottom of the linked answer for an example. Or you could just compose a curl to do it from the command line and put the Access Token into an environment variable.
I just wanted to avoid the whole thing and get a code printed on the screen
A bit like https://youtu.be/hfWe1gPCnzc?t=198

Related

How to send a JWT from my back-end server to my front-end after Google OAuth2 Authorization flow

I am creating an application with a React front-end and a Java Spring Boot back-end.
My login flow looks like this:
A user clicks on login on the front end
User is redirected to the Google Oauth authorization endpoint on my server
OAuth 2.0 Authorization flow happens: User is redirected to Google and logs in. Google interacts with my server first exchanging an authorization code and then a JWT access token. My server now has the JWT access token for the user.
ISSUE: I now need to redirect the JWT token to my React front-end so that the token can be saved and used every time the user wants to request access to a protected resource on my server.
Is there now an industry standard/best practice for redirecting the token to my React front-end from the server?
There are similar questions on this subject on Stack Overflow, however they are at least 3 years old, e.g. How to provide frontend with JSON web token after server authentication?
Since then the implicit flow has been deprecated, storing JWTs in local storage is no longer recommended, and https://datatracker.ietf.org/doc/html/rfc6750 explicitly discourages passing bearer tokens to the front end in a redirect URL.
I was wondering if anyone knows of an up to date solution for this problem.
There's a draft IETF BCP for OAuth 2.0 for Browser-Based Apps - see here. Basically, it's very similar to native mobile apps using authorization code with PKCE (proof key for code exchange).
FWIW I agree implicit flow shouldn't be used, but IMO you shouldn't be using authorization code flow without PKCE, as this flow is for server side rendered web apps.
EDIT - Auth0 (one of the most popular CIAM solutions on the market) docs say the same thing - see here.
If the Client is a Single-Page App (SPA), an application running in a
browser using a scripting language like JavaScript, there are two
grant options: the Authorization Code Flow with Proof Key for Code
Exchange (PKCE) and the Implicit Flow with Form Post. For most cases,
we recommend using the Authorization Code Flow with PKCE...
Don't.
You seem to mix 2 issues here.
First, you would like to use OIDC for authentication in your SPA. For this you would use OIDC Implicit Flow or Authorization Code Flow with PKCE.
Second, you would like to delegate authentication to google instead of doing it yourself. Basically this is known as federation - you trust external Identity Provider.
The full-blown version would be to setup your own Identity-Provider server (like e.g. keycloak) and configure federation to google there. Your SPA would initiate OIDC against your Identity Provider and wouldn't even know that google did the authentication. You could also easily add further Identity Providers (e.g. facebook) if necessary.
An easier workaround would be to initiate OIDC login from your SPA directly to Google. This way your SPA would receive token directly from google and you would need to protect your own backend as a resource-server accepting and validating those tokens. Adding further Identity-Providers like facebook would be a challenge.

API Authentication for multiple apps

I have been doing a lot of research into how to authenticate mobile apps with an API - I still feel a bit unsure about which flow & architecture would be better to use in my particular use case.
I think what's confusing me is some of the terminology used.
My use case:
An API & database on one server. Which holds the users & and the users resources.
A web app, which I have built and consumes the API. Hosted on the same server as the API. So it's dogfooding.
A web app, which I have built and consumes the API. Hosted on a different server to the API.
A mobile app, which I have built and consumes the API.
I'd like to be able to authenticate with the API using username & password.
The API will never be opened up for consumption by other 3rd party services except the web app and the mobile app.
Initially I felt like using the Resource Owner Password Credentials Grant flow would be sufficient. However in the docs it states that this flow should be used if "The client is absolutely trusted with the user credentials".
Since both my mobile & web apps will be built by me, I'm assuming they are seen as 1st party clients. Therefore am I right in thinking they are considered to be trusted with the user credentials? As I typically thought that when implementing oAuth, the idea would be to have the authentication server separate from the resource server. Which would allow you to have one authentication server for multiple APIs.
After reading this post: Why the Password Grant is not suitable for modern applications
It threw me off track a bit. But then, is this post talking about using this flow in my use case?
I was also looking at the Implicit Grant Tokens flow. However using this flow I couldn't really see how the user would enter their credentials first?
I also question if any of the oAuth flows is really needed for my use case and I should instead look at other ways of authenticating?
I'm really quite lost with this I would like some direction to go in with how to authenticate users in my particular case.
Thanks in advance!
I'll most likely be using Laravel to house my API and so I do have Passport available to me to implement oAuth
EDIT
From following this oauth article I've found that in all use cases of my app, I end at Password Credentials Grant flow. Would I be correct here?

REST API + OAuth + Mobile Flow

I have to develop a RESTful API for a mobile application and I have some concerns about the flow of the communication between those parts. I'm new to the API development for mobile devices and OAuth.
The project in common should work this way:
users are allowed to login using only their Google accounts
the mobile application uses the website API and all the information is stored on the backend
I found a similar question here OAuth on REST API for mobile app and I prefer the first solution from it, but I have some questions about the security of this solution.
1) Should I use OAuth2 for the API? I'm not sure it's a good idea just to send the user's Google ID to the API to get user's data.
2) How can I check on the server that the Google ID is correct and actual? Or it's not important at all?
I'm thinking about this scenario, but I'm not sure it's the best solution:
1) The user logs in on the mobile application for the first time using his Google Account.
2) The mobile application receives Google ID and some additional information.
3) The mobile application sends the Google ID to the server.
4) The server uses OAuth2. It creates an account for the user (saving the Google ID in the database) and returns an access token to the mobile application.
5) The mobile application stores the access token locally and uses it for requests to the server. Once the access token expires, the user has to login in the mobile application again using his Google account.
I have some concerns about using just Google ID for generating a token. I mean, anybody can just use somebody's Google ID to create a token. Bad idea :(
Also should I use JWT better as a token?
Thanks for your help!
You should send the user's id_token to the API instead
There are a couple of different ways in which you can validate the integrity of the ID token on the server side:
a) "Manually" - constantly download Google's public keys, verify signature and then each and every field, including the iss one; the main advantage (albeit a small one in my opinion) I see here is that you can minimize the number of requests sent to Google.
b) "Automatically" - do a GET on Google's endpoint to verify this token
https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
c) Using a Google API Client Library.
As for the workflow, it's mostly correct, except for the last step, where you can instead refresh an access token without prompting the user for permission. Btw, Google's id_token is actually a JWT.

How to access to my own API from my web application securely?

I have APIs. Some of them are limited to access from third party applications by OAuth.
I also have a web application. Users can login and see their private information.
The API is called from the web application too. My question is what is the good way to access the API with security measures.
1. Third party applications -> OAuth
2. My own web application -> ???
My web application uses session id for authentication. I guess that transferring the session id with HTTP header may be good way but I don't have a confidence.
For exmaple...
$ curl -X PUT \
-H "X-Sample-Application-Id: "My own web application's ID" \
-H "X-Sample-Session-Token: yeoql2dvn7whpm4tbe61viscv" \
If API receive this request, use session for authentication instead of oauth and identify the user....
Any help will be appreciated.
Thanks,
.. I found similar questions
Questions About Consuming Your Own API with OAuth
Update1
Some say JWT(Json Web Token) is good.
https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/
http://blog.mitsuruog.info/2014/08/jwtjson-web-tokenwebapicredential.html
Update2
I may be able to use OAuth's "Resource Owner Password Credentials"
https://www.ipa.go.jp/security/awareness/vendor/programmingv2/contents/709.html
Or... "Client Credentials grant" looks much better.
I'm going to elaborate a bit on this, because it's a good question, and there is a lot of confusion around it -- so bear with me here.
If the API you are trying to protect is going to exclusively be used by individuals for server-side apps, and not third-party developers, I'd highly, HIGHLY recommend you use HTTP Basic Authentication to secure your API service.
The way this works is super straight forward:
For your user(s), generate API Key pair(s) that consist of an ID and Secret. API keys are synonymous with username/passwords. Just generate random ID / Secret values using a UUID library.
When you authenticate against your API service, supply those API credentials in the HTTP Authorization header to identify yourself. Here's how it looks using curl:
$ curl --user my-api-keyid:my-api-key-secret https://api.myservice.com/blah
What's great about Basic Auth is that:
It's very simple to implement.
It's a well defined standard.
As long as you are making requests over HTTPS, and you don't publicize your API keys, you should be safe.
Now -- if you're building an API service where you want to authenticate users from a variety of environments (not just server side applications), you really need to use the OAuth2 protocol.
This is what it was designed for.
The OAuth2 protocol can authenticate users in a variety of ways -- but as a result, is quite complicated. Adding OAuth to your site can be a challenge, even if you're using popular libraries / etc.
Here's how OAuth works (a quick breakdown):
The Password Grant
The Password flow in OAuth is where you exchange a username/password for an Access Token (usually a JWT). You then use the Access Token in the HTTP Authorization header to identify yourself with your API service.
This is what most people do when building SPAs with Angular / React, as well as mobile apps.
The Client Credentials Grant
The Client Credentials flow is where you exchange an API key (just like basic auth) for an Access Token. You then use the Access Token in the HTTP Authorization header to identify yourself with your API service.
This is what people do when building server side apps with OAuth.
The Implicit Grant
This flow is what you see when you log into some place like Facebook. You click a button, are redirected to some other site to authenticate / accept permissions, and finally you're returned back to the main site with an Acccess Token that you use to identify yourself. This is NOT ideal for API services.
The Authorization Code Grant
This flow is exactly like the implicit flow, except you get back an authorization code that you then EXCHANGE for an Access Token that you use to identify yourself. This is NOT ideal for API services. It's slightly more secure.
If you are planning on going with OAuth because of your use case, I'd highly recommend checking out an authentication provider like Stormpath. They automate a lot of this stuff, and solve a lot of complexities around OAuth.
Otherwise, give Basic Auth a go!

Security for "Private" REST API

I am currently developing a web application that is right now comprised of a front end which displays and interacts with the data using a REST API we have written. The only thing that will ever use the API is our front end website, and at some point a mobile app that we will develop.
I have done a lot of reading about how OAuth is the ideal mechanism for securing an API and at this point I am starting to have a good understanding of how it works.
My question is -- since I am never granting access to my API to a third-party client, is OAuth really necessary? Is there any reason it is advantageous? Furthermore, because the back end is simply the API, there is no gateway for a user to authenticate from (like if you were writing an app using the Twitter API, when a user authenticates they would be directed to the Twitter page to grant to access then redirected back to the client).
I am not really sure which direction to go in. It seems like there must be some approach halfway between http authentication and OAuth that would be appropriate for this situation but I'm just not getting it.
From my point of view, one of the scenarios that favor OAuth over other options is to work with untrusted clients, no matter if these are developed by you or a third party.
What's an untrusted client? Think from the point of who handles the credentials that grant access to your API.
For example, your web application could interact with your API in two falvors:
Your web app server side talks to your API. Your web app server is a trusted client because the credentials to access your API can only be access by whom have access to the server...You and your team. You could authenticate your web app server with a client_id and a client_secret.
You may want to make calls directly to your API from your Web app client, which runs on the end user's browser using JavaScript. The end user's browser is an untrusted client. If you were to deliver the credentials to your API down to the browser, anyone could check the JavaScript code and steal your credentials.
A third party Native App is also untrusted. A malicious developer that uses your API could save the credentials of and end user of your platform.
Your Native App is a trusted client and could manage the authentication with a simple username , password and a client id identifying your App.
How can OAuth help? OAuth Authorization code and Implicit grants can help you with this issue. These flows only work with clients that support a redirect, like a browser. And let you authenticate an untrusted client and a user against your Authorization Server to gain access to your Resource Server, your API, without exposing the credentials. Take a look at the RFC to see how it is done.
The good thing of OAuth is that it not only supports these redirect based authentication flows, but it also supports client credentials grant and user credentials grant. So an OAuth Authorization Server would cover all cases.
OAuth 2.0 originally seems like a PITA if you think about having to build a lot of it yourself, but most languages have some really solid OAuth 2.0 setups which you can just bolt in with varying amounts of fiddling. If you're using a framework like Laravel or RoR then it's barely any work.
PHP: http://oauth2.thephpleague.com/
Ruby (Rails or Grape): https://github.com/doorkeeper-gem/doorkeeper
If you don't want to redirect users as suggested in your post then ignore other comments and answers that talk about two legged flows. You can use the client_credentials grant type to have apps just provide their client id and secret in return for an access token, which is nice and easy.
I would ask how private are we talking, because if the only systems talking to it are within the backend and have no interaction with the outside world you could probably leave it wide open and just rely on the network to keep it safe (VPN/Firewall).
But if it's private in the sense of "our iPhone app uses it" then you definitely want to go with OAuth 2.0, or something like it.
2 legged OAuth is probably what you want to use. It's basically hashing a shared key, but you have the advantage of not having to write the code yourself.
Here's a related question: Two-legged OAuth - looking for information
You should use Oauth for mobile device to API layer communication.
However, there is no benefit of Oauth in this web UI layer to middle-layer access (machine to machine).
On the other hand there are some potential issues
Managing the access token expiry becomes a pain. Consider that your UI has to cache the access token across multiple nodes in a cluster. Refresh it when expired, and the fact that UI layer is negotiating security with backend will just take extra time once in a while.
In two legged Oauth (OAuth Client Credential as in v2.0) does not support any encryption. So you still need to send key and secret both to the server for getting an access token.
Backend has to implement issuing access token, refresh token, validating access token etc, without any significant benefit