How the AAD token is refreshed after expiry? - azure-active-directory

I am working on a SDK where we send telemetry(1000s of events/minute) to Ingestion Service owned by Microsoft.(SDK is used by webapps hosted on Azure VMS or App services) The Ingestion Service currently support authentication using Managed Identities (both system and user assigned). My idea is to take a dependency on the Azure Identity SDK and use the existing DefaultAzureCredential or ManagedIdentityCredential implementations of 'TokenCredential' to get the tokens as shown below and Use this defaultCredential while initializing the sdk. Once I have the sdk initialized my idea is to get the token and attach to authorization header on each request.
DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
.managedIdentityClientId("<MANAGED_IDENTITY_CLIENT_ID>")
.build();
Questions:
How frequently are the tokens refreshed? How to control the expiry of these tokens?
When the token is expired, are the managed Identities smart enough to call the AAD and get new tokens. Or is it the SDKs(client) responsibility to get a new token and update the header.

In my opinion, the token won't be refreshed automatically, and if you wanna know the expired time, you could use tools like fiddler to catch the request which used the token and use jwo.io to decode it, you will get a claim of 'exp', it's a unix timestamp, you can convert it then you can know the expire time.
And the expire time is managed by the policy of your tenant, you can follow the tutorial to create a policy for your access token. And because your code just new DefaultAzureCredential(), any time execute the line, it will generate a new instance so that you don't worry about the token expired.

Related

Azure app Service authentication token not refreshing after calling .\auth\refresh endpoint

I have an angular app hosted in one azure windows app service and a asp.net core api hosted in another, both are protected using the app service authentication feature. I am using an app service plan which currently has two servers. I am using the token store and it is using the file system to store the tokens.
When the angular app calls the api it needs to pass an access token in the authorization header. The access token is retrieved by performing a GET on the \.auth\me endpoint and sending the AppServiceAuthSession cookie as the credential. The returned token is then cached in session storage and used for subsequent requests until the token expires. When the token expires I call the \.auth\refresh endpoint (and send the AppServiceAuthSession cookie) and then call the \.auth\me to get the refreshed token.
All this works well when running on one server but when the app service plan is scaled to 2 or more servers the call to \.auth\refresh succeeds but the subsequent call to the .auth\me endpoint gets a token which has already expired. I can tell the token has expired by checking the internal exp claim and also the call to the api fails with a 401 Unauthorized when it would normally succeed.
If I scale back to one server the problem goes away and if I enable ARR affinity the problem goes away but I don't want to have to enable affinity just to resolve this.
also the call to the api fails with a 401 Unauthorized when it would normally succeed.
You shouldn't be calling /.auth/refresh on the API app. You must call /.auth/refresh on the WEB app because the auth token is produced on the WEB app.
Alternative to the bearer token is the AppServiceAuthSession cookie from your client request to /.auth/refresh.
The returned token is then cached in session storage and used for subsequent requests until the token expires. When the token expires I call the .auth\refresh endpoint (and send the AppServiceAuthSession cookie) and then call the .auth\me to get the refreshed token.
We have a user-facing web application that calls an API backend, which in turn queries the MSFT graph, just to be sure we have the context correctly captured. At each phase, we anticipate a distinct AAD registration:
Web app registration (with permission to API app)
API app registration (with permission to Microsoft Graph)
Our initial assumption is that the user hasn't explicitly given their agreement to using the Microsoft Graph because this looked to be tied to adding the graph permission. Since the user isn't involved if you're merely updating the existing token, there isn't a chance for that consent to be obtained. The user would need to re-login with an explicit consent prompt, which could be done by calling /.auth/login/aad?prompt=consent. But we wouldn't anticipate that to cause the expiration problem. I'm speculating here, but it's possible that a cached, outdated value is being utilised in place of the permission error. There would need to be input from Connor.
The logs from the actual Authentication / Authorization layer itself, particularly if there is an error message, are another piece of information that would be useful to have. To obtain these logs:
From your app in the portal (the API app is what I'm most interested in): “Platform features” > “Diagnostic logs”. Change “Application Logging (Filesystem)” to “On” and set the level to “verbose.” Hit Save.
Back to “Platform features” > “Log stream” and keep that window open as you reproduce the issue (in this case, the call to the API app)
Actually, the issue is that AAD bearer tokens are incompatible with the /.auth/refresh API. Instead, you must use a session token (_x-zumo-auth_ header) or a session cookie (_AppServiceAuthSession_ cookie), which are the results of a login activity.
For more info - see here #refreshing-the-access-tokens

What is the difference between 0Auth and JWT in Azure AD the best practice for using access tokens in Azure AD?

I am a newbie to Azure AD. What is the best practice for using Azure AD access tokens?
What is the difference between an 0Auth and JWT token and which one should I use to follow best practices?
I used the below code to get the Token. Do I need to convert it to an 0Auth Token?
var AzureData = await DependencyService.Get<IAuthenticator>()
.Authenticate(App.tenanturl, App.GraphResourceUri, App.ApplicationID, App.ReturnUri);
App.AuthenticationResult = AzureData;
var userToken = Azuredata.AccessToken;
Please help. Thanks.
JWT is a type of Token, and OAuth is a Framework.
JWT (JSON Web Tokens) is just a token format, it defines a compact and self-contained mechanism for transmitting data between parties in a way that can be verified and trusted because it is digitally signed.
Oauth is an authentication framework, where it has a general procedures and setups defined by framework. JWT can be used as a mechanism inside OAuth. You do not need to convert your token.
Use JWT when...
Federation is desired. For example, you want to use Azure AD as the token issuer, and then use Apigee Edge as the token validator. With JWT, an app can authenticate to Azure AD, receive a token, and then present that token to Apigee Edge to be verified. (Same works with Google Sign-In. Or Paypal. Or Salesforce.com. etc)
Asynchrony is required. For example, you want the client to send in a request, and then store that request somewhere, to be acted on by a separate system "later". That separate system will not have a synchronous connection to the client, and it may not have a direct connection to a central token dispensary. a JWT can be read by the asynchronous processing system to determine whether the work item can and should be fulfilled at that later time. This is, in a way, related to the Federation idea above. Be careful here, though: JWT expire. If the queue holding the work item does not get processed within the lifetime of the JWT, then the claims should no longer be trusted.
Use OAuth when...
There is no federation. The issuer of the token is the same party that validates the token. All API requests bearing the token will go through the token dispensary.
There is no need or desire to allow the holder of the token to examine the claims within the token.
When you wish to unilaterally allow token revocation. It is not possible to revoke JWT. They expire when they are marked to expire at creation time.
See this thread for more details.

Scope for multiple web apis

I have 2 web apis (A and B) on my b2c. Each one of them publishes their own permissions respectively (scopeA1, scopeA2) and (scopeB1, scopeB2).
On my web application (which already configured and have granted access permission on both apis and the 4 scopes), in order to get authorization code for both apis during authentication, I tried to set my OpenIdConnectAuthenticationOptionsin scope property to include the 4 scopes.
I got an error AADB2C90146: The scope 'scopeA1 scopeA2 scopeB1 scopeB2 openid offline_access' provided in request specifies more than one resource for an access token, which is not supported.
While if I specify only scopes for web api A or B, then it works as per this link
How can I get my web app to use both web apis even with granted permissions for both
Thanks for help
If the two web APIs are separate applications in Azure AD, then you need to request access tokens separately for them.
I'm not familiar with the sample you used as a starting point, but it looks like these lines are where you need to make your change:
// Retrieve the token using the provided scopes
ConfidentialClientApplication app = new ConfidentialClientApplication(authority, Startup.ClientId,
Startup.RedirectUri, credential,
new NaiveSessionCache(userObjectID, this.HttpContext));
AuthenticationResult result = await app.AcquireTokenSilentAsync(scope);
accessToken = result.Token;
You should create an app instance for each of your APIs, and acquire a token for each of them. Then, when you call the APIs somewhere else, use the correct access token in the Bearer authentication header.
I had the same issue and asked a similar question Extend MSAL to support multiple Web APIs
but i have not had an answer, basically to get around it in the short term i have made both my API's use the same authorization client ID + secret and therefore I can reuse the same scopes accross my APIS
its not what i want but if you want to use Azure AD B2C you need to get used to compromising for a while until the support is there
-- I would also say you are using an older version of MSAL which i am also using, im waiting until the version 1 release before upgrading again.
The github talks about using this format
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet
Step 1: Add MSAL to your Solution/Project
Right click on your project > Manage packages.
Select include prerelease > search msal.
Select the Microsoft.Identity.Client package > install.
Step 2: Instantiate MSAL and Acquire a Token
Create a new PublicClientApplication instance. Make sure to fill in your
app/client id
PublicClientApplication myApp = new PublicClientApplication(CLIENT_ID);
Acquire a token
AuthenticationResult authenticationResult = await
myApp.AcquireTokenAsync(SCOPES).ConfigureAwait(false);
Step 3: Use the token!
The access token can now be used in an HTTP Bearer request.

Graph SDK OAUTH ADAL client credentials for reuse? later

So we have an application that allows you to create a xml file that runs the app again at a later stage (which may or may not have a user in attendance). Files are stored on the user cloud drive platform of choice. So the process is
Workflow 1
Authenticate to cloud with User 1 details/input
Select files to Download and use
Save and encrypt file metadata and Refresh token to xml file. (app workflow 1)
Workflow 2 ( can be repeated multiple thousands of times)
Send xml file to another pc with User 2. (either by email or remotely through a console
that pc then runs under user 2
start app
App authenticates automatically using refresh token saved in xml file with no user input (as there is a very high chance of the user who created workflow 1 not being in the same city as where workflow 2 is running
Downloads files
applies files (app workflow 2)
PROBLEM
all other platforms we cater for (Dropbox and google and onedrive) gives us access to the refresh token and allow us to authenticate with it again , however the onedrive for business (graph sdks) give us a Token cache which is session based?
Questions
So I need to know how I can get the refresh token from the Token Cache so we can reuse it at a later stage. (yes I'm aware that it will expire after 6 months which is acceptable) .
When i have the refresh token how do initiate a call to refresh the token
Further note - I have managed to handle all platforms before Within silverlight (where the sdks are not supported) through directly calling the rest api calls but we are converting our solution to WPF and would want to use the sdks
thanks
I assume you were developing Microsoft Graph SDK when you mentioned graph sdks.
AFAIK, this library does not include any default authentication implementations. Instead, the user will want to authenticate with the library of their choice, or against the OAuth endpoint directly, and built-in DelegateAuthenticationProvider class to authenticate each request.
And if you were authenticating Azure AD with Active Directory Authentication Library, you can use the default token cache which use memory to store the cache or you can implement the token cache based on your requirement.
So I need to know how I can get the refresh token from the Token Cache so we can reuse it at a later stage. (yes I'm aware that it will expire after 6 months which is acceptable) .
When you using the ADAL library, there is no need to get the refresh token manually, it will handle for us to renew the access token if the refresh token is existed.
When i have the refresh token how do initiate a call to refresh the token
If you want to perform the request yourself to refresh the access token, you can refer the request below, and more detail you can refer this document.
POST /{tenant}/oauth2/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&refresh_token=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq...
&grant_type=refresh_token
&resource=https%3A%2F%2Fservice.contoso.com%2F
&client_secret=JqQX2PNo9bpM0uEihUPzyrh // NOTE: Only required for web apps
OK so the answer is taking the tokencache from the PublicIdentityApp and serializing as below.
var tokenCache = _app.UserTokenCache;
var tokenBytes = tokenCache.Serialize();
var tokenString = Convert.ToBase64String(tokenBytes);
And deserializing it later.
_app = new Microsoft.Identity.Client.PublicClientApplication(ClientID);
var array = Convert.FromBase64String(bytestring);
_app.UserTokenCache.Deserialize(array);
authHelper = new AuthenticationHelper(_app);
var authorise = await authHelper.GetTokenForUserAsync()

when using mirror api, how do i handle access token expiration

I am building a glass app using the PHP sample app as reference.
To my understanding, the glass app is a web app which is user facing. When the user visit the web app, they will authorize the web app (using oauth2) to access their resources, and once authorization succeeded the web app will get an access token, which is then saved in a sqlite database (there's this store_credentials() function which stores the access token).
So if I have 100 users who visit the web app and register, the database will hold 100 access tokens for these users. Let's say I have some backend code which pull from a RSS feed every hour, and whenever I find there's a new story I will push it to all registered users. Let's say I have a cron job which does this, when when this job is triggered, I will find all the access tokens in the database and use them to make mirror API calls to insert cards. But what if some of the access token is expired when I am trying to make the mirror API call? It seems I will need to ask user to re-authorized, but at this point I am not interacting with the user. If I have a refresh token, I may be able to call oauth again to get a new access token.
Thanks.
You pretty much answered your own question - when you request permission using OAuth, you should also request "offline" access. The first time you do this for each user it will give you a refresh token along with your access token, and you should store both. If you did not request offline access initially, you will need to revoke the tokens that have been granted and re-grant them with offline access.
If the sample app you're referring to is the one at https://github.com/googleglass/mirror-quickstart-php, all this should be done for you already with the libraries included. The credentials returned from $client->getAccessToken() in oauth2callback.php should include both the access and refresh tokens, and these are saved in that same file by calling store_credentials(). The client libraries should check if the access token has expired and, if so, it gets a new one with the refresh token before making the call.
You may want to take a look at the contents of the credentials object at these various points and make sure there is a refresh token. If not, try revoking all the tokens and starting again, since it sounds like the first time you authorized the client you did so without requesting offline access.
If you are doing this yourself, best practice is to either refresh the access token if it has expired or is about to expire (since there may be some delay) before use, or (even better) attempt to make the call with an access token and, if it fails with an authentication error, get a new access token via the refresh token and try again.

Resources