I am using Trustpilot API and I need to handle a scenario when refresh token expires. I did not find the response in API documentation.
If the API indicates that your token is expired, the scenario is covered. How you handle this is the scope of you application and not the API.
I'm creating an API server which will be consumed by a mobile app that I will work on later. I have yet to see any reference of API best practices related to user flow and returned data even after searching for several hours.
My question is whether the login response of an API should return the a personal access token with the refresh token along with the user info? Or should I just return the token and make another API call for getting the user info.
I could just do what I have in mind but I'm trying to learn the best practices so that I don't have to adjust a lot of things later.
I need suggestions as well as good references related to my question.
Thank you.
It depends on what you are using for your authentication. If you are using libraries like Laravel Passport or JWT, you can have the token endpoint which returns the access token, refresh token, validity period and the token type (Bearer). You can then have an authenticated endpoint which will be used to get a user's profile based of the token passed in the request header.
However, if you go through the documentation for those libraries, in most there is an allowance to manually generate a token. You can use this in a custom endpoint that will return the token as well as the user profile Passport Manually Generate Token.
If you are using JWT, you can also embed a few user properties in the token itself. The client can the get the profile info from the JWT itself without having to make a round trip to the server. Passport ADD Profile to JWT
If you have a custom way in which you are handling authentication, you can pass the token as well as the user profile in the same response.
In the end, it's up to you to decide what suits you best.
Have you looked at OpenID Connect? It's another layer on top of OAuth 2.0 and provides user authentication (OAuth 2.0 does not cover authentication, it just assumes it happens) and ways to find information about the current user.
It has the concept of an ID_token, in addition to the OAuth access token, and also provides a /userinfo endpoint to retrieve information about the user.
You could put user information in your access token, but security best practice is to NOT allow your access token to be accessible from JavaScript (i.e. use HTTP_ONLY cookies to store your access token).
I'm moderately familiar with OAuth2 and the concepts of the AccessToken and RefreshToken.
It looks like MSAL is doing some work for us when using ClientApplicationBase.AcquireTokenSilentAsync().
I'm not clear as to whether it will always check the expiration of the current AccessToken and automatically refresh it (using the RefreshToken) on method call.
Regardless, is there a "best practice" for how often we should call AcquireTokenSilentAsync() ? Should we keep track of the expiration ourselves and call this method to update our bearer authentication header? Should we be calling AcquireTokenSilentAsync() on every Request? (doubtful)
I can't see how the GraphServiceClient (tangent topic, I know) using the DelegateAuthenticationProvider will do anything helpful WRT refreshing. Do we need to extend that class and perform our own refresh when the token is nearing expiration? I feel like this would/should be already in the SDK.
Thanks for any tips.
-AJ
Update Nov 2020
This answer was originally written for V2 of the MSAL client. Since then a V3 has been released which may work differently from V2.
Original answer
I'm not clear as to whether it will always check the expiration of the current AccessToken and automatically refresh it (using the RefreshToken) on method call.
A refresh token is automatically supplied when the offline_access scope is provided, if I understand this answer correctly
...you've requested the offline_access scope so your app receives a Refresh Token.
The description of AcquireTokenSilentAsync implies that when an refresh token is provided, it will check the expiration date on the token, and get a new one if it's expired or close to expiring.
If access token is expired or close to expiration (within 5 minute
window), then refresh token (if available) is used to acquire a new
access token by making a network call.
It will repeat this behavior until the refresh token is expired. Optionally you can force a refresh of the access token via the refresh token by utilizing the forceRefresh parameter on AcquireTokenSilentAsync
Lastly, I am going to quote this answer on SO since it gives a nice insight about MSAL and tokens
Just to make a small clarification, MSAL doesn't actually issue tokens
or decide a token expiration, but rather ingests an acquires token
from the Azure AD STS.
MSAL will automatically refresh your access token after expiration
when calling AcquireTokenSilentAsync. .... The default token
expirations right now are:
Access Tokens: 1 hour
Refresh Tokens: 90 days, 14 day inactive sliding window
(June 13th '17)
Regardless, is there a "best practice" for how often we should call
AcquireTokenSilentAsync() ? Should we keep track of the expiration
ourselves and call this method to update our bearer authentication
header? Should we be calling AcquireTokenSilentAsync() on every
Request?
The documentation also lists a 'Recommended call pattern' for calling the AcquireTokenSilentAsync. The documentation also mentions that
For both Public client and confidential client applications, MSAL.NET maintains a token cache (or two caches in the case of confidential client applications), and applications should try to get a token from the cache first before any other means.
Based on examples I've seen, including the recommended call pattern from the documentation, I would argue you could simply call AcquireTokenSilentAsyncand catch the MsalUiRequiredException as an indication that the token has expired and the user has to log in again.
I can't see how the GraphServiceClient (tangent topic, I know) using the DelegateAuthenticationProvider will do anything helpful WRT refreshing. Do we need to extend that class and perform our own refresh when the token is nearing expiration? I feel like this would/should be already in the SDK.
If I understand the DelegateAuthenticationProvider correctly, what it does is modify the requestMessage before we pass it to Graph. All we got to do is provide our access token with an authorization header for the request. We already know that when we fetch our access token, it is valid, so we can just add it.
new DelegateAuthenticationProvider(async (requestMessage) =>
{
ConfidentialClientApplication cca = new ConfidentialClientApplication(_ClientId, _Authority, _RedirectUri, new ClientCredential(_ClientSecret), _UserTokenSessionCache.GetTokenCache(identifier, httpContext), _ApplicationTokenCache.GetTokenCache());
AuthenticationResult result = await cca.AcquireTokenSilentAsync();
requestMessage.Headers.Add("Authorization", result.CreateAuthorizationHeader());
//OR
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", result.AccessToken);
});
(There is no difference between either way of setting the headers)
I've been down this path and this does the trick for me. I highly advise reading their documentation, because it does gives a good insight in how to implement MSAL.Net.
I haven't had time yet to play around with the token durations yet. Nor the behavior if no refresh token is provided (if that's even possible)
I hope this helps!
Mentioning one thing missed above, quoting my answer to Get refresh token with Azure AD V2.0 (MSAL) and Asp .Net Core 2.0
For context, OAuth 2.0 code grant flow mentions the following steps:
authorization, which returns auth_code
using auth_code, to fetch access_token (usually valid for 1 hr) and refresh_token
access_token is used to gain access to relevant resources
after access_token expires, refresh_token is used to get new access_token
MSAL.NET abstracts this concept of refresh_token via TokenCache.
There is an option to serialize TokenCache. See Token cache serialization in MSAL.NET. This is how to preserve sign-in info b/w desktop application sessions, and avoid those sign-in windows.
AcquireTokenSilentAsync is the process by which refresh_token is used to get new access_token, but, this is internally done. See AcquireTokenSilentAsync using a cached token for more details and other access patterns.
Hope this clarifies on why TokenCache is the 'new' refresh_token in MSAL.NET, and TokenCache is what you would need to serialize and save. There are libraries like Microsoft.Identity.Client.Extensions.Msal that aid in this.
#AlWeber/ #Raziel, the following pattern would apply for PublicClientApplication:
on startup, to deserialization and load TokenCache (which has refresh_token), try acquire access_token silently.
if that fails, use interactive UI to fetch token.
save and re-use the AuthenticationResult, which has AccessToken and ExpiresOn. Redo acquire access_token silently (bit expensive if you are an API user, hence caching of result), once you are close to ExpiresOn property (personally, I set 30 min before expiry).
is there a "best practice" for how often we should call AcquireTokenSilentAsync() ? Should we keep track of the expiration ourselves and call this method to update our bearer authentication header? Should we be calling AcquireTokenSilentAsync() on every Request? (doubtful)
I don't think this is a good idea. As mentioned, this call is still a bit expensive. Alternative, is to store AuthenticationResult in-memory, re-use it, and go to silent acquire workflow only close to ExpiresOn property.
I am looking for the best approach to work with the IdentityServer4 autorization code flow.
My apps system is quite ordinary: I have an MVC client, a WebAPI and the IS. I also use AJAX to request the API from the client side. So I need the access token on the client side to put it into the authorization header.
Is it good idea to store access token in the cookies?
Do I need self-contained or reference token (it is about security, I suppose)?
What is the best approach to renew when it was expired?
I thought about the two strategies:
Update access token when the first 401 status code was recieved. Can be the problem cause I send more than 1 query to the API and I need to synchronized them and recall the first one (to get result);
Every time before API calling call the MVC client method with GetTokenAsync, check the expire time and get or update and get access token. Seems cheating, cause I need to call the MVC client every time when I want to call the API.
Could you help me to find the best way?
"Is it good idea to store access token in the cookies?"
No, not with the authorization code flow. If you are using an MVC web application you should find a way to store tokens in some kind of datastore away from the browser. All the MVC application should administer is a cookie to access future MVC endpoints (that will make subsequent calls to Identity Server with the appropriate access token in the datastore).
"Do I need self-contained or reference token (it is about security, I suppose)?"
That's all up to you and what you think is best for your use cases. If you'd like to see the information in the access token and skip the extra backend call for validation then use reference tokens. Strategy 2 requires you to use self-contained tokens so that you can check the expiry.
"Could you help me to find the best way?
I don't know if I can give the "best" way, but I'd probably go with strategy 2 and use self-contained tokens.
EDIT: If you wanted to use "axios , to get data from the API" then I would suggest using the implicit flow which has no concept of a refresh token. In this case, leaving it in the cookie should be OK.
I have an angular2 app that has a Facebook login feature. When the user authenticates themself, I then send this accessToken to the server.
The server program is with Springboot and I make use of spring social.
I want to check to see if this user is authorized. So I call:
facebook.getToken() returns the access token generated on the client side. When I call facebook.isAuthorized() it returns true...As expected, because I am sending real data.
Although if I send bogus data such as:
(The token in this case is fabricated by me) to the same API endpoint
facebook.isAuthorized returns true. This is unexpected because in this case I am fabricating an accessToken.
The spring-social dependency is this:
Why does isAuthorize return true for a real access token, as well as a fake one? How can I check to see if a user of my angular2 app has authenticated themselves through Facebook on the server side?
Implementation of isAuthorized() for FacebookTemplate can be found at https://github.com/spring-projects/spring-social/blob/a6bf2626ee8ac81765c416029ca033affc94fc6c/spring-social-core/src/main/java/org/springframework/social/oauth2/AbstractOAuth2ApiBinding.java#L87.
With this source its quite obvious that isAuthorized() only checks if there is any access token provided.
To validate your token you can run any request which need authorization (e.g. userOperations().getUserPermissions()) and check for InvalidAuthorizationException or you can find some inspirations in how to verify facebook access token?.