Renew a JWT issued by Azure ACS - asp.net-mvc

We have Azure ACS configured to issue JWT that is valid for 15 minutes. Once the user is logged-in to the web application (MVC), the user will use the token to access resources on another server (WebAPI). The WebAPI server would then validate that token.
So, is there any way to renew the JWT somehow without interrupting user's work on the web app? We don't want to popup a window and ask the user to sign in again.
Thanks!

If you are using Active Directory Authentication Library (ADAL) for .NET, then it includes a token cache. Per this blog post:
One last thing I’d highlight at this point is that every time you get a token from the authority ADAL adds it to a local cache. Every subsequent call to AcquireToken will examine the cache, and if a suitable token is present it will be returned right away. If a suitable token cannot be found, but there is enough information for obtaining a new one without repeating the entire authentication process (as it is the case with OAuth2 refresh tokens) ADAL will do so automatically. The cache is fully queryable and can be disabled or substituted with your own implementation, but if you don’t need either you don’t even need to know it’s there: AccessToken will use it transparently.
ADAL.NET is available on Nuget here: https://www.nuget.org/packages/Microsoft.IdentityModel.Clients.ActiveDirectory/
If you aren't using ADAL.NET, provide more info, such as:
What library you are using
What is ACS on top of, AD FS or Azure Active Directory

We use ACS + ADAL and there seems to be no clever way to refresh the token. Even if the ExpiresOn Time on the Token inside the Cache is due the AcquireToken always returns the stale cached token. We cache the token ourself, so this code is only invoked when the ExpiresOn is due.
I ended up with this dirty hack:
var authContext = new AuthenticationContext(ServiceInfo.AcsUrl);
if (authContext.TokenCacheStore.Count > 0)
{
authContext.TokenCacheStore.Remove(authContext.TokenCacheStore.First());
}
result = authContext.AcquireToken(acsRealm, allProviders.First());

Related

Google Calendar API v3 - Persistent Authorization with Code

Im wondering if anyone has any answers to this. If one follows the quickstart here:
https://developers.google.com/calendar/api/quickstart/go
we can get authorization from a user that allows us to do things with their calendar.
It seems the HTTP Client given back from the config handles calling the refresh token and keeping the client up to date.
First, as a side-question, does anyone know how long this is allowed to persist? I read in a doc somewhere that for unpublished apps/projects its 7 days, but it didn't specify a timeline otherwise. Is it indefinite or will this expire at some point (ie the refresh token runs out after 30 days). And is this avoidable at all?
now, the real question - if you take the service down entirely, ie for an update, and restart it, is there any way to opick up the authorization again? In the tutorial its writing a code to disk and reading as needed. In my case I just hold reference to the things I need in the application, so obviously when the service went down id have to reauthorize. I then tried writing the code to disk on a persistent volume and re-reading from that, but it doesnt get authorized - I guess because the new instance of the service has a new instance of the oauth config, and it wont accept the old code perhaps?
In any case, im wondering if anyone knows of a way to make this persist through ssytem restarts, or if the only real option here is to move the calendar service client to a small microservice on the side that we do not restart, and contact it from elsewhere as needed.
Thanks in advance!
The refresh token expiration is documented here. As you've noted, tokens expire in 7 days for projects in "Testing" status. Refresh tokens for projects in production last indefinitely, but there are some scenarios where they may get invalidated (user revokes access, token has not been used in 6 months, the account has over 50 live tokens, etc.). It's not mentioned but if you change your OAuth scopes you'll probably need to reauthorize as well.
This means that as long as you keep your refresh tokens and none of the invalidation conditions are met, you should be able to keep using them to get new access tokens even if your service goes down temporarily. But as mentioned in the documentation, you should anticipate the possibility that the token stops working and redirect the user to authorize again.
My guess is that in your case the refresh token stopped working for some reason (maybe the 7 days limit) and the application just tried to use the same expired token. The Quickstarts in Google's documentation usually handle the creation of the token file and how to reuse it, but they don't include the part where you have an invalid token and need to reauthorize.
References:
Google's OAuth2 Overview
OAuth2 for Web Apps

Using nodemailer & Google OAuth to send email, working for 7 days, but get invalid grant

I've been working to setup Oauth communication for an auto-emailing node.js web app using nodemailer. (I don't wish to use gmail's Less Secure Apps setting).
I've taken steps to get the client id, secret, and refresh token from the oauth playground, and have set up the web app to use a stored refresh token to request new access tokens when it first loads.
It is able to send emails (for about 7 days), then I get error invalid status code 400 on client side, and/or invalid grant on server side.
Going back to google playground and getting another refresh token, then updating it in environment variables, solves this for another week. But I'd like to solve this indefinitely.
I read somewhere "A Google Cloud Platform project with an OAuth consent screen configured for an external user type and a publishing status of 'Testing' is issued a refresh token expiring in 7 days"... so last week I switched the app to "In Production" (at console.cloud.google.com) and tried having it verified with google. This week, the same issue has recurred suggesting that wasn't the right fix, or that it wasn't yet verified with google.
I don't know if this was done correctly, nor do I know if this is the true solution to this expiring/revoked refresh token, or invalid grant.
I've also come across these explanations:
The user has revoked your app's access.
The refresh token has not been used for six months.
The user changed passwords and the refresh token contains Gmail scopes.
The user account has exceeded a maximum number of granted (live) refresh tokens.
The client has reached a limit of 50 refresh tokens per account if it's not a service account.
(I didn't make ANY changes during the week, so...not sure why these would have changed)
Is the issue the refresh token?
Or the status of the application?
Would it be dns/cname/cloudflare server issues?
For those who have the same issue in the future:
It turned out that google verification wasn't necessary.
It seems like the refresh token expiring after a week or 7 days was due to the placement of the oauth2Client.setCredentials() function call and accessToken variable.
Calling setCredentials() and obtaining the access token INSIDE the SendEmail() function (at runtime, just before sending email, rather than at application start/spinup time) seemed like it enabled the code to more dynamically generate the tokens it needed. After 12 days, it still seems like its working so I'd call this a success.
My guess at why it wasn't working before was because setting credentials outside of a function meant that code only ran once on server/application startup. It would then store the obtained access token in a const.
The access token would eventually expire, and even if called again/later inside of a function to obtain a new access token, it would be unable to change the value of a const property/variable, and so the call would inevitably fail after a week when it failed to renew.
Hope this helps anyone else having a similar issue.
My apologies for the run-on sentences.
There are a lot of causes for invalid grant it sounds to me like your refresh token is expiring.
If your project on google developer console is still in testing, has not been moved to published and has not gone though the google application verification process then refresh tokens have a max two week life span after which they will expire which may explain your invalid grant. The thing is there is no official word from google that this is happening its just what a lot of developers are seeing these days.
Another one is with gmail scopes if the user changes their password this will also cause the refresh token to expire.

No cache tokens were found during token acquisition

I want to send a request from a Controller of the ASP.NET MVC application that is deployed on the Microsoft Azure Cloud Active Directory and receive a response from the service that is still deployed on the Microsoft Azure Cloud Active Directory.
For this purpose, I downloaded an example you can see from here and customize it for myself. A detailed document of my actions is contained in the same link.
When I tested service and web applications on my azure portal, I encountered an error message in the header:
Failed to acquire token silently as no token was found in the cache.
Call method AcquireToken
Where the error occurred is the following part in my controller:
ClientCredential credential = new ClientCredential( clientId, appKey );
result = await authContext.AcquireTokenSilentAsync( todoListResourceId, credential, new UserIdentifier( userObjectID, UserIdentifierType.UniqueId ) );
clientId: Identifier of my web application installed on Azure AD (For example: c95d45dd-ba7f-41be-a995-1db604afff32)
appKey: Hidden key value of my web application in the portal
todoListResourceId: Identification of my API application installed on Azure AD (For example: 4cfebcb4-6f2e-4eeb-84f2-4220f65774ed)
userObjectID: Value returned from the following piece of code
string userObjectID = ClaimsPrincipal.Current.FindFirst( "http://schemas.microsoft.com/identity/claims/objectidentifier" ).Value;
i.e. a value for the user who is online in the browser. As stated in the document on my GitHub link, this value is not my Microsoft account that I used when logging into my azure portal, but a value for my user that I registered to my Azure Active Directory
A similar topic to this topic has been discussed and answered here before, but this answer has not solved my problem.
I've been working for days, but I haven't gotten a response from the GET, POST, PUT, DELETE methods in the service. I keep dealing with the error in the title. I'm waiting for your help.
The reason you're receiving this error is because the call acquiretokensilentasync is EXPECTED to throw that error when the cache is empty. This call is meant to be caught in a try catch. If it does throw this error it should call the acquiretokenasync call.
In addition to that it looks like you're trying to utilize the client credential flow with the acquiretokensilentasync call, which is not the right method to use per the ADAL wiki docs.
See here on how to do this properly: https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/Client-credential-flows
It looks like you're using an app id and secret, the method in particular on how to do this per the doc linked above is :
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.microsoftonline.com/<tenantId>");
AuthenticationResult result = await authenticationContext.AcquireTokenAsync("https://resourceUrl", clientCredential);
More documentation specifically for the acquiretokensilentasync call can be found here : https://github.com/AzureAD/azure-activedirectory-library-for-dotnet/wiki/AcquireTokenSilentAsync-using-a-cached-token
From the doc above :
Recommended pattern to acquire a token
Now that you have seen both AcquireTokenAsync, AcquireTokenSilentAsync, it's the right moment to
present the recommended usage pattern for calling these methods. The
idea is that you want to minimize the number of signings for the user,
and therefore you'd want to:
first try to acquire a token silently, and if this call fails you try
to get one interactively. Note that, AcquireTokenSilent does not need
to be called in the Client credentials flow (when the application
acquires token without a user, but in its own name)
Note that AcquireTokenSilent can fail for several reasons, such as the
cache does not contain a token for the user, or the token has expired
and cannot be refreshed. For these reasons, a call to
AcquireTokenAsync will usually get a token. But there are also issues
such as network problems, STS unavailability, etc., which won't be
directly solvable. You will see them in more details in the article
about best practices for Handling errors.
In addition to that, it looks like you're using the ADAL Library, I suggest to move over to the MSAL library since Microsoft is slowly moving towards utilizing the MSAL libraries and will at some point in the future (maybe far future) move off of ADAL/V1.0 endpoint. There are no current hard dates for this however. The doc on moving over from ADAL to MSAL can be found here :
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Adal-to-Msal

Disable one time use on refresh tokens in Datapower/API Connect [OAuth2]?

We have an OAuth/OIDC service developed in API Connect/Datapower.
When a user requests a new refresh_token - if any unexpected error occurs in the flow, the new refresh_token is not issued, and their existing refresh_token is revoked. This forces the user to go through a new consent flow. This can be problematic if large numbers of customers are affected due to some unexpected error. We would like the old refresh_token to still be valid in this scenario.
We raised this with our IBM support contact - and he said this works as intended (i.e. - it should revoke the old refresh_token as the first action - it is single use, regardless of outcome).
He did suggest that it is possible to configure the refresh_token to be used multiple times until it is revoked/expired.
I am not sure how to do this - or what versions it is supported in. He said '(in 2018.4.1.x)? For v5 gw, use extension to enable it, You will need the latest DP firmware release for the above'. It's been hard to get any clarity on this. The IBM developer forums even directed me to Stack Overflow...
Does anyone have any more information/experience with enabling a refresh_token to be used multiple times? Or what versions this is supported in (or links to any documentation about this)? I'm struggling to find anything concrete on this.
Thanks
I suppose he's talking about the count configuration. it is located just below Enable refresh tokens.
Section 'OAuth 2' -> Tokens -> Enable refresh tokens -> count
Hope this could be helpfull
For IBM API Connect version 2018.4.1, you can specify whether the refresh token for OAuth provider is One time use only or not.
See OAuth native provider>Tokens screen.
After an access token expires, if the option is enabled in the OAuth provider API, the application can use refresh tokens. Each refresh token is valid for approximately 31 days after it is issued and can be used only once to request a new access token. Along with the new access token, a new refresh token is also returned.

How is access token refreshed / acquired when using API Client Library for .NET?

I have one quick question related to "acquiring a new access token upon expiration". I have read some tutorials where people write code to manually request a new access token.
In my case I wrote an ASP.NET MVC app to access Google APIs, such as Gmail API, and I am using API Client Library for .NET for that.
After OAuth 2.0 authorization I get back the result object of type AuthorizationCodeWebApp.AuthResult.
Where result.Credential.Token contains AccessToken and RefreshToken properties.
I save the refresh token in my web.config the very first time when it comes back (after the consent screen). All next requests dont have a refresh token, only an access token that expires after 1 hour.
So, my question is - before I make a call to instantiate a Gmail Service, I assign previously saved refresh token:
result.Credential.Token.RefreshToken = WebConfigurationManager.AppSettings["RefreshToken"];
var service = new GmailService(
new BaseClientService.Initializer { HttpClientInitializer = credential });
When result.Credential.Token.AccessToken expires, does Gmail API (or any other API Client Library for .NET) acquires a new access token automatically if result.Credential.Token.RefreshToken was assigned a valid refresh token value previously saved, like in my code sample?
Thank you!
UPDATE - More clarification to my question With the same refresh token, how many times I can aquire a new access token when making calls to Google API?
I will explain: access token expires in 1 hour, right.
If I keep making calls with, lets say, 10 minutes intervals to Gmail API (for example), after 6 calls (1 hour limit), Gmail API will use my refresh token to acquire a new access token. After 6 more calls (1 more hour) the whole thing repeats itself. Question - is there a limit to it? Remember, I am not changing my refresh token. Same refresh token is being used to acquire a new access token. And for how long this repetitive calls may continue without any error?
UPDATE AFTER THE TEST
I let my application run on my local machine in Visual Studio DEBUG mode trying to catch any exception, NO Human interaction.
The application kept receiving AJAX calls to Gmail Action with 2 minutes interval, everything was working fine, I went to the gym, came back 2 hours later - oops, Visual Studio debug is open on this Token has been revoked exception, here we go, so it's clear the token was revoked by the Google API service, as you can see from the Debug window. The only question remains - why, since there are no specific details are provided, there is no Inner Exception just that general error message and no reason, but the source is clear - Google API, we can even see it came back from
Google.Apis.Requests.ClientServiceRequest`1.Execute() в
C:\Users\mdril\Documents\GitHub\google-api-dotnet-client\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:row
96
I am guessing the service shuts down (revokes a token) after N number of calls, maybe within certain interval. If some one knows the limitations of Google API in terms of number of calls or time intervals between calls, please let me know.
It seems that Matthew Riley, the custodian of Google API on github, coded some logic to revoke a token based on some criteria: https://github.com/google/google-api-dotnet-client
Long response to comment :
One question though: can this be done indefinitely long, unlimited number of times, or I will get an error at some point?
Refresh tokens can be come invalid for the following reasons:
user can revoke it in there google account.
if a refresh token isn't used for 6 months to get a new access token it will expire automatically.
If a user authenticates your application you get a refresh token if they do it again you get a different refresh token. Both will work. you can do this up to 26 times. on the 27 th time the user Authenticates your application the first one you got will expire. You can only have 26 live refresh tokens. (DONT ASK how I know this! "#¤%&)
So assuming you don't reauthentcate your application to many times, use the refresh token at least once every six months. You can use it as many times as you want.
Update for comment:
I think you are still confused. Access tokens expire after 1 hour. Refresh tokens only expire for the above reasons you can use them as many times as you like. To get a new access token.
However you can only have 25 working refresh tokens.
Lets say I have a windows service application that backs up files to a users Google drive account. A user installs it on a server and authenticates it and gets a refresh token. Every night the windows service runs and backs up the files to google drive, it uses the refresh token to get a new access token.
Lets say this user really likes my auto super imba backup service. He installs it on another server. He gets another refresh token and the application goes about its business uploading files at night
Lets say my super user really has a server farm he installs my application on 25 servers. Those applications will be able to get new access tokens forever.
However if this crazy user installs it the 26 th time on a different server getting a new refresh token for this server. The first server they installed it on will stop working because google only allows you to have 25 outstanding refresh tokens for an application.
This is user application based so you can have any number of users each with a max of 25 refresh tokens

Resources