英文:
Consuming Web API secured with JWT authentication from ASP.NET Core MVC application
问题
我想了解如何从一个ASP.NET Core MVC Web应用程序中消耗一个使用JWT令牌身份验证保护的ASP.NET Core Web API - 谢谢。
查找了一些文章,但都是通过Postman进行消耗并外部传递JWT令牌。
英文:
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
答案1
得分: 0
Here is the translated code:
例如,我们在MVC控制器中有一个这样的方法,我们可以使用它来生成正确的JWT令牌。
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);
}
然后,我们需要将令牌添加到请求头部,当我们发送HTTP请求时。根据官方文档,我们需要在Program.cs中添加HttpClient:builder.Services.AddHttpClient();
,然后我们可以使用以下代码调用API:
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 ;
}
英文:
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 ;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论