Wallet Objects API Java client library GoogleCredential lifetime - android-pay

With the Wallet Objects Java client library, can the GoogleCredential object be reused throughout the application lifetime, or is it intended for 1-time use?

The GoogleCredential object is intended to be reused for the application lifetime. It will transparently handle storing auth tokens and renewing expired tokens for you. To explicitly request a new access token you can refresh it with:
credential.refreshToken();
and get it with
credential.getAccessToken();

Related

Setting up distributed caching in node

I have an application, in which I have to fetch a list of users. The API to fetch the list requires an authentication token, which expires every 1 hour. So, in order to fetch the users, I first need to make a token call and post that I need to make the fetch call. How can I cache the token which is valid for 1 hour in Node? We have multiple pods, so I need a distributed cache to make sure that the token value is the same across the pods. Will it be possible to implement it in node and how to implement it? Any kind of resources/tutorials would be really helpful.
So you're calling an external service, but you need a valid token that you have to obtain first.
Take a look at how existing software tackles it. For example, Microsoft's Graph API SDK (which also uses bearer token auth):
https://github.com/microsoftgraph/msgraph-sdk-javascript/blob/dev/docs/CustomAuthenticationProvider.md
You inject an "authentication provider" that authenticates and retrieves a token from the remote service when necessary. Next, when you need to make a call to the API, the client checks if it has a token in-memory. If it doesn't (or if it's expired), it asks the authentication provider for a new token. So, the in-memory cache layer is in the client object.
Another approach is in-memory caching, but in the Authentication Provider layer - then, the client can blindly ask it for a token every time, and let the Provider decide whether to use the current token or ask for a new one.
I would refrain from putting the token on a network-accessible cache - it opens up a potential security hole for leaking the token, and does not seem to serve any purpose.

getstream chat: Using a new JWT token for each server side request

Following the GetStream chat API docs I've been wondering if there's any disadvantage in sending a newly signed token with each server-side API request.
That way my server will remain stateless and will allow me to generate very short lived tokens.
Generating a new token for server-side for each request doesn't make much sense because server-side has already full access since using API secret.
If you have multiple API keys, then having the same number of tokens with their respective secrets sounds fair. Here, we assume this is a secure environment because it uses secret to do anything on your account.
If you check server-size SDKs (Go, Python, etc), when you create a client, they actually generate your token and cache it.
However, client side is a different story. JWT is stateless but probably your app needs (session) state management and expiration should be done (logout for example). In this case, 15 mins to expire a token and refresh token under the hood is a pretty common practice.
Short JWT expiration
pros:
no need for central storage (blacklisting for logout, password change, etc)
more secure (changed more frequently even if stolen)
cons:
more processing time/resource are spent to sign a new token (cryptography is slow)
more network requests for refresh
bad user experience if token isn't saved, instead kept in memory (needs login and security might be a problem on saving since token could be stolen otherwise)

Does the client call back the server with the same JWT token it received?

I am new to JWT and hence trying to understand the intricacies and expectations when using JWT. In my case, I own the micro-service generating the JWT tokens. JWT supports RS256 and HS256 mechanisms. From what I understand, in case of RS256, I distribute the public key to my client. In case of HS256, I distribute the secret to my client.
Assuming I give access to either of these to my client, what is the expectation from the client? Should the client treat the token I passed back to them as immutable and they just send me the exact token back in the subsequent API calls? Or is it recommended/ okay for them to mutate the token and create a new one, for e.g. by changing things like audience in the token payload, and then for my server to verify the newly passed token? My server should be able to verify both tokens, but I don't know which is the recommended approach. If the recommended approach is for my client to not mutate the token, why do I need to distribute the keys to the client in the first place?
Do not distribute the key to the client. The client should not be able to modify the JWT access token. It should treat the token as opaque.
Only the resource server (exposing the API) that accepts the token should verify the signature.
In OAuth2, the client is the application getting the access token and using it to call an API server. It should not care about the token as long as it works to call the API.
The authorization server authenticates the user, gets the user's consent and issues the token to the client.
The client then uses the token to call the resource server (API) with the token in the Authorization header.
In your case, the authorization server and resource server may be the same, but they should not share signing keys with the client.

Can a user have two valid token at a time in oauth 2.0 for auth code grant type?

*I have simple question related to oauth token ,so my requirement is that user can have multiple scopes say A and B and he has generated token for it but later on he needs scope A and B both and his previous token is valid, So in that case
Should we update the scope for the existing token ?
Should we generate new token for new scope ?
Or should Generate multiple token for a single user ?
If you want to update the scope of the existing token and if your authorization server provides a mechanism for it, just do it. As a matter of fact, a certain authorization server implementation provides Web APIs to update scopes of existing access tokens (/auth/token/update API, /auth/client/authorization/update API).
Whether access tokens are modifiable or not depends on each authorization server implementation. For example, if the type of access token implementation is "self-contained" (e.g. like JWT), access tokens are not modifiable. On the other hand, if the type is "random string" (in this case, actual data are stored in the DB behind the authorization server), access tokens may be modifiable. See "7.1. Access Token Representation" in "Full-Scratch Implementor of OAuth and OpenID Connect Talks About Findings" for details.
Some authorization server implementations issue multiple access tokens for one combination of a user and a client application, and other implementations issue only one access token for the combination. A certain authorization server implementation provides a configuration flag to enable you to select either of the behaviors like below. See also this answer.
Which approach you should take depends on your use case. Look for an authorization server implementation which suits your use case best.
OAuth2 access token is no modifiable, so you should get a new access token with a different set of scopes. Access tokens are generated for an application, not a user, but yes, there can be multiple access tokens authorized by a single user - the user authorizes the application to perform some operations (scopes) on his behalf.

JWT Token strategy for frontend and backend

I'm writing an application with a front end in emberjs and backend/server-side in a nodejs server. I have emberjs configured so that a user can login/signup with an 3rd party Oauth (google, twitter, Facebook). I have a backend written in express nodejs server that hosts the RESTful APIs.
I do not have DB connected to emberjs and I don't think I should anyways since it's strictly client side code. I'm planning on using JWT for communicating between client side and server side. When a user logins with their oauth cred, I get a JSON object back from the provider with uid, name, login, access_token and other details.
I'm struggling with picking a strategy on how to handle user signup. There is no signup process since it's OAuth. So the flow is if the user is not in my db, create it. I do not support email/password authentication. What would be the flow when a user signs in with an OAuth provider for the first time? Should emberjs send all the details to the backend on every sign in so that backend can add new users to the db?
What should be part of my JWT body? I was thinking uid and provider supplied access token. One issue I can think of here is that provider specific access token can change. User can revoke the token from provider's site and signs up again with emberjs.
I'm open to writing the front-end in any other javascript client side framework if it makes it easier.
If we're talking about not only working but also secure stateless authentication you will need to consider proper strategy with both access and refresh tokens.
Access token is a token which provides an access to a protected resource.
Expiration here might be installed approximately in ~1 hour (depends on your considerations).
Refresh token is a special token which should be used to generate additional access token in case it was expired or user session has been updated. Obviously you need to make it long lived (in comparison with access token) and secure as much as possible.
Expiration here might be installed approximately in ~10 days or even more (also depends on your considerations).
FYI: Since refresh tokens are long lived, to make them really secure you might want to store them in your database (refresh token requests are performed rarely). In this way, let's say, even if your refresh token was hacked somehow and someone regenerated access/refresh tokens, of course you will loose permissions, but then you still can login to the system, since you know login/pass (in case you will use them later) or just by signing in via any social network.
Where to store these tokens?
There are basically 2 common places:
HTML5 Web Storage (localStorage/sessionStorage)
Good to go, but in the same time risky enough. Storage is accessible via javascript code on the same domain. That means in case you've got XSS, your tokens might be hacked. So by choosing this method you must take care and encode/escape all untrusted data. And even if you did it, I'm pretty sure you use some bunch of 3rd-party client-side modules and there is no guarantee any of them has some malicious code.
Also Web Storage does not enforce any secure standards during transfer. So you need to be sure JWT is sent over HTTPS and never HTTP.
Cookies
With specific HttpOnly option cookies are not accessible via javascript and are immune to XSS. You can also set the Secure cookie flag to guarantee the cookie is only sent over HTTPS.
However, cookies are vulnerable to a different type of attack: cross-site request forgery (CSRF).
In this case CSRF could be prevented by using some kind of synchronized token patterns. There is good implementation in AngularJS, in Security Considerations section.
An article you might want to follow.
To illustrate how it works in general:
Few words about JWT itself:
To make it clear there is really cool JWT Debugger from Auth0 guys.
There are 2 (sometimes 3) common claims types: public, private (and reserved).
An example of JWT body (payload, can be whatever you want):
{
name: "Dave Doe",
isAdmin: true,
providerToken: '...' // should be verified then separately
}
More information about JWT structure you will find here.
To answer the two specific questions that you posed:
What would be the flow when a user signs in with an OAuth provider for
the first time? Should emberjs send all the details to the backend on
every sign in so that backend can add new users to the db?
Whenever a user either signs up or logs in via oauth and your client receives a new access token back, I would upsert (update or insert) it into your users table (or collection) along with any new or updated information that you retrieved about the user from the oauth provider API. I suggest storing it directly on each users record to ensure the access token and associated profile information changes atomically. In general, I'd usually compose this into some sort of middleware that automatically performs these steps when a new token is present.
What should be part of my JWT body? I was thinking uid and provider
supplied access token. One issue I can think of here is that provider
specific access token can change. User can revoke the token from
provider's site and signs up again with emberjs.
The JWT body generally consists of the users claims. I personally see little benefit to storing the provider access token in the body of a JWT token since it would have few benefits to your client app (unless you are doing a lot of direct API calls from your client to their API, I prefer to do those calls server-side and send my app client back a normalized set of claims that adhere to my own interface). By writing your own claims interface, you will not have to work around the various differences present from multiple providers from your client app. An example of this would be coalescing Twitter and Facebook specific fields that are named differently in their APIs to common fields that you store on your user profile table, then embedding your local profile fields as claims in your JWT body to be interpreted by your client app. There is an added benefit to this that you will not be persisting any data that could leak in the future in an unencrypted JWT token.
Whether or not you are storing the oauth provider supplied access token within the JWT token body, you will need to grant a new JWT token every time the profile data changes (you can put in a mechanism to bypass issuing new JWT tokens if no profile updates occurred and the previous token is still good).
In addition to whatever profile fields you store as claims in the JWT token body, I would always define the standard JWT token body fields of:
{
iss: "https://YOUR_NAMESPACE",
sub: "{connection}|{user_id}",
aud: "YOUR_CLIENT_ID",
exp: 1372674336,
iat: 1372638336
}
For any OAuth workflow you should definitely use the passportjs library. You should also read the full documentation. It is easy to understand but I made the mistake of not reading the the whole thing the first time and struggled. It contains OAuth Authentication with over 300 Providers and Issuing Tokens.
Nevertheless, if you want to do it manually or want a basic understanding, here is the flow that I'd use:
Frontend has a login page listing Sign-in with Google/Facebook etc where OAuth is implemented.
Successful OAuth results in a uid, login, access_token etc. (JSON object)
You POST the JSON object to your /login/ route in your Node.js application. (Yes, you send the whole response regardless if it's a new or existing user. Sending extra data here is better than doing two requests)
The backend application reads the uid and the access_token. Ensure that the access_token is valid by following (https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken) or asking for user data from the provider using the access token. (This will fail for invalid access token since OAuth access tokens are generated on a per app/developer basis) Now, search your backend DB.
If the uid exists in the database, you update the user's access_token and expiresIn in the DB. (The access_token allows you to get more information from Facebook for that particular user and it provides access for a few hours usually.)
Else, you create a new user with uid, login etc info.
After updating the access_token or creating a new user, you send JWT token containing the uid. (Encode the jwt with a secret, this would ensure that it was sent by you and have not been tampered with. Checkout https://github.com/auth0/express-jwt)
On the frontend after the user has received the jwt from /login, save it to sessionStorage by sessionStorage.setItem('jwt', token);
On the frontend, also add the following:
if ($window.sessionStorage.token) {
xhr.setRequestHeader("Authorization", $window.sessionStorage.token);
}
This would ensure that if there is a jwt token, it is sent with every request.
On your Node.js app.js file, add
app.use(jwt({ secret: 'shhhhhhared-secret'}).unless({path: ['/login']}));
This would validate that jwt for anything in your path, ensuring that the user is logged-in, otherwise not allow access and redirect to the login page. The exception case here is /login since that's where you give both your new or unauthenticated users a JWT.
You can find more information on the Github URL on how to get the token and to find out which user's request you are currently serving.

Resources