I have a Blazor Server app where I managed to get the authentication with Azure AD to work, but I am unable to retrieve the Azure AD token. I have the following:
_Host.cshtml:
@{
Layout = null;
var tokens = new InitialApplicationState
{
AccessToken = await HttpContext.GetTokenAsync("access_token"),
RefreshToken = await HttpContext.GetTokenAsync("refresh_token")
};
}
<component type="typeof(App)" param-InitialState="tokens" render-mode="ServerPrerendered" />
Startup.cs:
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));
services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
options.ResponseType = OpenIdConnectResponseType.Code;
options.SaveTokens = true;
options.Scope.Add("User.Read");
});
services.AddControllersWithViews()
.AddMicrosoftIdentityUI();
services.AddAuthorization(options =>
{
options.FallbackPolicy = options.DefaultPolicy;
});
services.AddScoped<TokenProvider>();
TokenProvider.cs:
public class TokenProvider
{
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
}
InitialApplicationState.cs:
public class InitialApplicationState
{
public string AccessToken { get; set; }
public string RefreshToken { get; set; }
}
GradingApiService.cs:
public class GradingApiService : IGradingApiService
{
private readonly HttpClient _httpClient;
private readonly IConfiguration _configuration;
private readonly TokenProvider _tokenProvider;
public GradingApiService(HttpClient httpClient, IConfiguration configuration, TokenProvider tokenProvider)
{
_httpClient = httpClient;
_configuration = configuration;
_tokenProvider = tokenProvider;
}
public async Task<Gradings> GetRiskAppetiteGradingByQuoteID()
{
try
{
var token = _tokenProvider.AccessToken;
var request = new HttpRequestMessage(HttpMethod.Get,
"https://grading-api-func-uks-tst.azurewebsites.net/api/Gradings/a0999a23-b275-4993-a959-6185cd769c0a");
request.Headers.Add("Authorization", $"Bearer {token}");
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsAsync<Gradings>();
}
catch
{
return new Gradings();
}
}
}
So whenever I retrieve the token I obtain a null value. Could you help me to understand what's wrong with this?
Many thanks in advance.