I would like to understand how to consume an ASP.NET Core Web API secured with JWT token authentication from the an ASP.NET Core MVC web application - thanks.
Searched a couple of articles but all are consuming through Postman and externally passing JWT tokens
For example, we have a method like this in the MVC controller and we can use it to generate a correct jwt token.
private string generateJwt() {
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, "user_name"),
new Claim(JwtRegisteredClaimNames.Email, "user_email"),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("role","admin"),
new Claim(ClaimTypes.NameIdentifier,"admin")
};
var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(120),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
Then we need to add the token into the request header to when we send a http request. Following the official document, we need to add HttpClient in Program.cs: builder.Services.AddHttpClient();
then we can call the api with code like this:
private readonly IHttpClientFactory _httpClientFactory;
public HelloController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public async Task<string> GetAsync() {
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,"https://localhost:7212/WeatherForecast")
{
Headers =
{
{ HeaderNames.Authorization, "Bearer "+ accessToken}
}
};
var httpClient = _httpClientFactory.CreateClient();
var response = await httpClient.SendAsync(httpRequestMessage);
var res = "";
if (response.StatusCode == HttpStatusCode.OK)
{
res = await response.Content.ReadAsStringAsync();
}
return "hello" + res ;
}