Azure AD OAuth Refreshing Tokens - powershell

I'm making an application that among it's task will use the REST API in KeyVault. I already have functions written that will query the KeyVault for the secret without an issue.
I also have functions written to request an OAuth token from AAD, following the documentation on this link:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
What I'm not sure about is; Since the application is going to be installed on hundreds of computers when a token expires and the function to refresh the token is called chances are that more than one PC is going to make the POST. What is the best practice for a scenario like this? Should i just configure an exponential back off after a refresh token function is called?
The app installed on the machines will not have the ability to talk to each other.
The only way I can think to do this is to use a logic app as the broker but that would defeat the purpose of the KeyVault.

The document you provided is using the code grant flow to acquire the access token. This flow requires users to login to acquire the token. And did you mean all the PC you installed will use the same account to acquire the token?
If yes, you can design you own token cache. For example, you can using an SQL server to store the cache. Then the app will search the token/refresh token in the token cache before it sends the token request. And if the token is expired, you can refresh it. In this scenario, all PC will share the same access token since they are sign-in with same account.
If not, you need to refresh for the every PC when the access token is expired. Because the access token is different from each user.

So after some testing and verifying with MS it looks like the documentation on the link is outdated. When a token is generated it has a lifetime of 8 hours (this is configurable) so every time I make a request to /token a new token is handed out, since the time window is small I don't need to worry about token refreshes since PCs won't be on for over 8 hours.
The other part of this is that i built a function to test the validity of the existing token, before i query any azure service i test the token validity, if it fails a new token is requested. Since the token lifetime windows are short and each machine gets it's own token (i thought all machines were getting the same token, code error on my part) this is a non-issue anymore

Related

What is the point of refresh token in jwt?

Please don't mark as duplicate I came through a lot of questions like this but still I didn't get the point of refresh token. Some of the reason they said are:
If an attacker gets the access token it will expiry soon
But where I am confused is if the attacker was able to get the access token why they wouldn't be able to get the refresh token (both of them needed to access token by JS to sent request so they needed to store in local storage)
If the attacker gets the refresh token we can block it in server.
But we can also block the access token in server right. (with DB)
Note I am not talking about OAuth refresh token, because as per the answers I read,
The idea of refresh tokens is that if an access token is compromised,
because it is short-lived, the attacker has a limited window in which
to abuse it.
Refresh tokens, if compromised, are useless because the attacker
requires the client id and secret in addition to the refresh token in
order to gain an access token.
So it makes sense here but what about JWT?
Typically the access token gets sent with every request, and to your API.
Typically a refresh token only gets sent once, immediately expires after use and only goes to your authentication server. All these measures generally reduce risk.
JWT and OAuth2 can be used together, and it's highly recommended to use OAuth2 instead of trying to write something from scratch.
I talk a bit more about the pitfalls in my article: https://evertpot.com/jwt-is-a-bad-default/
The refresh token allows the client to make a call and ask for a new access token. For setups where the access token does have a certain expiry, the refresh token will typically have an expiry which is later than the access token itself. Here is a typical workflow using access and refresh tokens:
The client authenticates to the server via 1FA or 2FA
The server responds with an access token having an expiry in 5 minutes, along with a refresh token which expires a minute later
The client then uses the access token as needed.
When authentication fails using the current access token, under the hood the client will take the refresh token and hit the server to get a new access token. We then go to step #2 above and recycle.
Note that for certain instances, the refresh token is not needed. One example would be sites like Stack Overflow, which uses token which never expire. Another example would be certain high security sites such as banking sites. In these cases, the site might force you to reauthorize via 1FA/2FA in order to keep the session going.
One way in which an update of the authentication token can be carried out through another and without exposing it to client applications (avoiding its use in a malicious way), is to store it in a cache system such as REDIS and in the When the request token has expired, check in storage if the user has a refresh token that allows him to regenerate the authentication. This could be implemented within the same middleware that validates the token that accompanies the request or in an endpoint intended for this purpose.

What is the MUST have claims for JWT refresh tokens? Can it be identical to the access token (with a longer exp)?

Im playing around and creating a custom access token system using JWT. I have already created a system for signing and validating JWT access tokens.
However, I find it hard to obtain information about what claims a refresh token should consist of.
Should i create refresh tokens identical to the access token - with a longer expiratiom time so that the same function that validates access tokens can be used to validate the refresh token?
A refresh token is typically an opaque value that is only used by clients to refresh access tokens. The flow works like this:
Web or mobile client implements OpenID Connect to authenticate users and get tokens - prompting the user to consent in some cases
An Authorization Server (AS) issues the tokens and stores details of this 'delegation' in a database - tokens are a pointer to this state
Client sends access tokens to APIs until a 401 expired response is received
Client then tries to refresh the access token by sending the refresh token to the Authorixation Server, which then looks up claim details from the stored state
I would make sure you get these responsibilities right - in particular avoid building your own AS and use a free one provided by experts, such as Curity Community Edition. Many security solutions will then be easier to develop.

How does all services in microservice architecture (token based) know that the user has logged out?

When a user logs out (sign out) of the application, how does the gateway communicate to all services that the user has logged out?
In other words, what happens when a user logs out in microservice architecture application?
This is generic question, I will give my personal thoughts.
Let's take a Single page application, talking to bunch of Microservices and secured by a Gateway that validates the token.
When user logs in, token given by auth server is stored within browser storage(ex: localstorage).
When user log out, no communication is sent to Gateway or auth server, tokens will simply be deleted from browser storage.
So, if someone gets hold of access tokens, they can be used to call services as long as access tokens doesn't expire.
This is typically why there are two tokens given by auth server, an access token and a refresh token. Access token which is used to secure apis expires pretty quickly and a refresh token which has much longer expiry time can be used to get new access token.
As you've included the JWT tag, so I'm trying to give the response by considering that only. The JWT token is a self-sufficient encoded token that contained certain attributes including an expiration period. The sole purpose is to provide stateless authentication. Authentication service usually returns two token, access_token and refresh_token. Client store both of them in some storage on their end. Access token usually issued for a very short span of time and so the client can use the refresh_token in order to get a new access_token on the expiration of the latter. One can access the services until refresh_token get expired. After that client has to go through the authentication process to get new tokens. In case when user logout from the system client should remove both of the tokens from its storage. Because as there is no state maintain in the case of JWT, the server can still accept the old token until they're not expired.
Validation of token for expiration and integrity should be done at the gateway level.
One can avoid the use of the token for service to service communications as those are internal services and running in a private network although one can do the same validation at this level too.
So in case of user sign out, the user's auth token should be removed from the client-side and the gateway should not communicate to other services. There are other special cases where token revoke is a particular case that could be handled by taking the help of distributed cached store in scaleable authentication systems.
A token-based service can generally infer the following from a token -
Who made a request?
Upto what time this token is considered valid?
Which actions are allowed when using this token?
A token based service just accepts or rejects a request depending on provided token, regardless of whether it is a user or a machine making the request. A logged-in user is just someone who can perform actions which this user is authorized to do. A token is a limited representation of such a user.
My point being, it is the application telling the user that they are logged in (have a token it can still use), or logged out (no token yet, or expired). Such a token is obtained by authenticating to the service using ones username and password.
Answer is based on my knowledge, so everyone, please do point out mistakes if any. I don't know in detail about aws api gateway stuff, so maybe someone else can brief you on it in case it works differently.

OAuth - what to store on disk

TL;DR When using google oauth on desktop app, what to save on disk to avoid repeated sign in? Save the google user id? or the token? or an session id?
I'm creating an little desktop app, whitch must authenticate to my REST API server. I'm using google oauth2 for that.
The idea is, that when the desktop app will be authentivated, it generates some data that will be send to my server. The server will store the data with the google user id received from https://www.googleapis.com/userinfo/v2/me.
On the first run of the desktop app, it will open the default browser, with and url for my server and start an local http server. then:
my server will redirect the browser to google (with the clientid, secret, etc.)
user logs in and it will be redirected back to the server with the oauth code
server uses the code to get the token, and then the user profile and stores the token and the profile in db, then redirects the browser to localhost with an paramerer
the desktop app catches the parameter and stores it in an file on the disk
next time the desktop app will start it only reads the file for the parameter to send the generated data with it to my server
my question is: what the parameter should be? the google user id? the oauth token? an generated session id for this desktop app? or something else?
when it will be the google user id, it can conveniently sent the data with the user id and the rest server will just store it in db as is. but I don't think it's safe
when it will be the token, the rest server has to with every request also get the user profile from google with the token. and imho sending the token with every request isn't safe either
generating an session id means to store it with the user and the token on the server and the desktop app will just store it and send it with every request. but I don't know if it's safe to do that
As it's normally the case in software development you have a couple of options depending on requirements.
The mandatory requirement is that your client (desktop) application needs to send something to your REST API so that the API can perform up to two decisions:
Decide who the user is.
Decide if the user is authorized to perform the currently requested action.
The second step may not be applicable if all authenticated users have access to exactly the same set of actions so I'll cover both scenarios.
Also note that, for the first step, sending the Google user ID is not a valid option as that information can be obtained by other parties and does not ensure that the user did authenticate to use your application.
Option 1 - Authentication without fine-grained authorization
Either always sending the id_token or exchanging that token with your custom session identifier both meet the previous requirement, because the id_token contains an audience that clearly indicates the user authenticated to use your application and the session identifier is generated by your application so it can also ensure that. The requests to your API need to use HTTPS, otherwise it will be too easy for the token or session ID to be captured by an attacker.
If you go with the id_token alternative you need to take in consideration that the token will expire; for this, a few options again:
repeat the authentication process another time; if the user still has a session it will indeed be quicker, but you still have to open a browser, local server and repeat the whole steps.
request offline_access when doing the first authentication.
With the last option you should get a refresh token that would allow for your application to have a way to identify the user even after the first id_token expires. I say should, because Google seems to do things a bit different than the specification, for example, the way to obtain the refresh token is by providing access_type=offline instead of the offline_access from OpenID Connect.
Personally, I would go with the session identifier as you'll have more control over lifetime and it may also be simpler.
Option 2 - Authentication + fine-grained authorization
If you need a fine-grained authorization system for your REST API then the best approach would be to authenticate your users with Google, but then have an OAuth 2.0 compliant authorization server that would issue access tokens specific for your API.
For the authorization server implementation, you could either:
Implement it yourself or leverage open source components
⤷ may be time consuming, complex and mitigation of security risks would all fall on you
Use a third-party OAuth 2.0 as a servive authorization provider like Auth0
⤷ easy to get started, depending on amount of usage (the free plan on Auth0 goes up to 7000 users) it will cost you money instead of time
Disclosure: I work at Auth0.
There should be no problem sending the access_token with every request since they are created for that purpose and are thus short lived. You can use the Google Authorization Server endpoint to verify a token instead of using it to do a request for a users profile.
If you're only relying on Google for authentication, here's how your workflow can look:
the client (desktop application, in your case) retrieves the
Google id_token following the user's log in, and then sends it to
the server
the server validates the integrity of said token and extracts the user's profile data; this could mean a simple GET on Google's endpoint to verify this token: https://www.googleapis.com/oauth2/v3/tokeninfo?id_token={0}
On subsequent requests, nothing should change really, except that the user's login process will be automated (since he's given permissions & all), and thus much faster. #danielx is right, there's no problem with sending the token each and every time.

OAuth REST access_token and instance_url expiry time?

I am working with Oauth2.0. In that i could able get the access_token and instance_url. Is there any expiry time for these two.
Can I store them and use it for all my REST calls without getting the new access_token and the instance_url. Is it possible for me to use it for long hours or even days.
The access token is only valid for the length of a session (as defined in the Salesforce Org's settings — I believe the longest this can be is 8 hours without activity), as it's actually a session ID, that said, you should also be given a refresh token. The refresh token has a much longer lifetime and can be used to authenticate the user once the session has expired, without them having to enter any credentials — this allows you to do it in the background without them even having to concern themselves with the login process.
model metrics do a good job of explaining the token flow here.