I have a web API on the backend, and a web app and phone app on the front end. I am using Auth0 for OAuth/OpenId authentication on all three. Both web API and web app are written in ASP .Net Core 1.1 MVC.
Every time I call the web API from the web app, I request an access token from Auth0. So, in every controller action that requires access to my API, I have:
var client = new HttpClient();
var tokenResponse = await client.PostAsync(tokenEndpoint,
new FormUrlEncodedContent(new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials"),
new KeyValuePair<string, string>("client_id", _auth0Settings.ClientId),
new KeyValuePair<string, string>("client_secret", _auth0Settings.ClientSecret),
new KeyValuePair<string, string>("audience", _auth0Settings.ApiIdentifier),
}));
Is this the correct way of doing this? Or should I just perform this once when the web app fires up, and then store the access token in a global variable that I can call from all my controllers?
You should call only once and reuse the token. When the token has expired you should request new token with refresh token. If u do not use refresh tokens u should redirect user to login page to reauthenticate or have some sort of auto-reauthenticate mechanism on web app.