How to Implement Token Refresh with Microsoft.Datasync.Client Similar to Microsoft.Azure.Mobile.Client Approach #904
-
I was using the below code for assigning new token with Microsoft.Azure.Mobile.Client How I can do something similar in Microsoft.Datasync.Client var objToken = new JObject { { "access_token", Settings.Current?.User?.Token } }; |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
You need to pass an AuthenticationProvider to the DataSyncClient constructor or add your own handler to the HttpPipeline. There is a generic provider that you can use to pass a function that constructs a token https://github.com/Azure/azure-mobile-apps/blob/f3b2be698983eec25953b1f34e5aa81bb2f9d7f9/sdk/dotnet/src/Microsoft.Datasync.Client/Authentication/GenericAuthenticationProvider.cs |
Beta Was this translation helpful? Give feedback.
-
GenericAuthenticationProvider can be used to handle custom authentication, How I can use it for refresh, since it is already initialised? Is there any recommended approach for handling token refresh with DatasyncClient? Are you suggesting extending HttpMessageHandler and overriding the SendAsync method to check the token's expiration, refresh it as necessary, and then proceed with the request? |
Beta Was this translation helpful? Give feedback.
The GenericAuthenticationProvider uses a caching algorithm. When the token is just about to expire, it asks for another one. Underneath, it is a DelegatingHandler that adds the current token to the request as an Authorization header.
What you SHOULD do is understand the AuthenticationProvider (the GenericAuthenticationProvider inherits from this) and do "whatever your authentication mechanism requires" to get a token and keep it fresh. For 90+% of cases, the GenericAuthenticationProvider is enough, but it's definitely not "all cases" and for those where you want to specifically do something else, there is a skeleton for you to use as the basis for your own authentication provider.