I'm trying to retrieve an Azure AD token from my Blazor server website, so I can add this as an Authorization header in a downstream API service. I was able to setup AAD authentication in the website (which works perfectly fine), but I'm unable to retrieve an access token, which needs to be added as an authorization header in my downstream API calls.
I'm using Blazor server (so not WebAssembly) in .NET core 3.1
This is my current setup, but the access token is always null and can't seem to fix it. Any help is greatly appreciated!
Startup.cs
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddCookie();
services.Configure<OpenIdConnectOptions>(AzureADDefaults.AuthenticationScheme, options =>
{
options.SaveTokens = true;
});
_Host.cshtml
I added a code block and try to retrieve the accessToken from the HttpContext. Then I can propagate the value to my controllers using a CascadingValue object in my app.razor However, the access_token is always empty. The "User.Identity.IsAuthenticated" is true, so it is entering my if statement.
@{
string accessToken = null;
if (User.Identity.IsAuthenticated)
{
accessToken = await HttpContext.GetTokenAsync("access_token");
// accessToken is always empty :(
}
}
What am I missing here? Most of the articles I could find about this was for Blazor WebAssembly
Side note: Not sure if this is relevant for this, but in my controllers, I'm able to get the ClaimsPrincipal object. But I don't think I'm able to get a bearer token from that object (but thought it was worth mentioning here).
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;