从ASP.NET Core MVC应用程序中使用JWT身份验证访问受保护的Web API。

huangapple go评论59阅读模式
英文:

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[&quot;Jwt:Key&quot;]));
     var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

     var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, &quot;user_name&quot;),
                new Claim(JwtRegisteredClaimNames.Email, &quot;user_email&quot;),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(&quot;role&quot;,&quot;admin&quot;),
                new Claim(ClaimTypes.NameIdentifier,&quot;admin&quot;)
            };

     var token = new JwtSecurityToken(_config[&quot;Jwt:Issuer&quot;],
                _config[&quot;Jwt:Issuer&quot;],
                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&lt;string&gt; GetAsync() {
      var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get,&quot;https://localhost:7212/WeatherForecast&quot;)
      {
           Headers =
           {
               { HeaderNames.Authorization, &quot;Bearer &quot;+ accessToken}
           }
      };

      var httpClient = _httpClientFactory.CreateClient();
      var response = await httpClient.SendAsync(httpRequestMessage);
      var res = &quot;&quot;;
      if (response.StatusCode == HttpStatusCode.OK)
      {
           res = await response.Content.ReadAsStringAsync();
      }
      return &quot;hello&quot; + res ;
}

huangapple
  • 本文由 发表于 2023年5月17日 12:17:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76268525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定