- 在Blazor应用程序中,使用HttpClient从WebApi中获取身份验证令牌。
public async Task GetToken()
{
var client = _httpClientFactory.CreateClient();
var disco = await client.GetDiscoveryDocumentAsync(Configuration["ApiUrl"]);
if (disco.IsError)
{
throw new Exception(disco.Error);
}
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = Configuration["ClientId"],
ClientSecret = Configuration["ClientSecret"],
Scope = Configuration["Scope"]
});
if (tokenResponse.IsError)
{
throw new Exception(tokenResponse.Error);
}
return tokenResponse.AccessToken;
}
- 使用身份验证令牌调用WebApi中的受保护资源,并将令牌放在请求头中。
public async Task> GetProducts()
{
var client = _httpClientFactory.CreateClient();
var token = await GetToken();
client.SetBearerToken(token);
var response = await client.GetAsync(Configuration["ApiUrl"] + "/products");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync>();
return products;
}
throw new Exception(response.ReasonPhrase);
}