Reputation: 573
I have an API which is registered as a service principal in Azure AD. I'm trying to obtain an access token from a client application and pass that to the API.
As part of the HttpClient request I've added this code (from Microsoft docs):
var accessToken = await tokenCredential.GetTokenAsync(
new TokenRequestContext(scopes: new string[] { ResourceId + "/.default" }) { }
);
This works, however it will only work for 24 hours, at which point I have to restart the app services to make it work again. I'm guessing this is because the token has expired and has not retrieved a new one.
I've read somewhere that if the above code is used, expiration and cache for the token needs to be handled manually.
How should I be retrieving these tokens using Azure.Identity
?
Upvotes: 3
Views: 4249
Reputation: 573
This turned out to be service lifetime issue and a dodgy implementation of HttpClient. After switching to IHttpClientFactory, issues now appear to be resolved.
Upvotes: 1
Reputation: 16086
According to your code snippet, it seems that you're using client credential flow to generate access token (you set the scope as xx/.default), so I think you can add Azure.Identity
package and using code below to generate access token. Just calling this method to generate token before you wanna calling the api. Code sample extracts from here.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using WebApplication1.Models;
using Microsoft.Identity.Client;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public async Task<string> gettokenAsync() {
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create("azure_ad_app_client_id_here")
.WithClientSecret("client_secret_here")
.WithAuthority(new Uri("https://login.microsoftonline.com/tenant_name.onmicrosoft.com"))
.Build();
AuthenticationResult result = null;
//e.g. https://graph.microsoft.com/.default
string[] scopes = new string[] { "xxxx/.default" };
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
string accesstoken = result.AccessToken;
return accesstoken;
}
}
}
Upvotes: 0