如何在 ASP.NET CORE 中将 Bearer 令牌添加到请求中

发布于 2025-01-11 21:39:48 字数 3449 浏览 0 评论 0原文

我有一个由 Bearer 令牌保护的 API,可在 mvc 项目中使用。我正在使用 ClientFactory 调用 mvc 中的 API。我从 WeatherForecast [HttpGet] 方法获取生成的令牌,并使用它来访问授权的 PlayerController 方法。它在 Postman 中工作正常,但是当我尝试在 mvc 中访问 PlayerController 时,在运行调试器时它显示未经授权的响应!

这是在 mvc 项目中获取和使用生成的令牌的操作

        private async Task<JWTToken> CreateToken()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/weatherforecast");
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);
            var token = await response.Content.ReadAsStringAsync();
            HttpContext.Session.SetString("JwToken", token);
            return JsonConvert.DeserializeObject<JWTToken>(token);

        }
        public async Task<IActionResult> GetAllPlayers()
        {
            JWTToken token = null;
            var strToken = HttpContext.Session.GetString("JwToken");
            if (string.IsNullOrWhiteSpace(strToken))
            {
                token = await CreateToken();
            }
            else
            {
                token = JsonConvert.DeserializeObject<JWTToken>(strToken);
            }
            if (token == null || string.IsNullOrWhiteSpace(token.token) || token.expireAt <= DateTime.UtcNow)
            {
                token = await CreateToken();
            }
            List<Player> players = new List<Player>();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/api/player");
            var client = _clientFactory.CreateClient();
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiString = await response.Content.ReadAsStringAsync();
                players = JsonConvert.DeserializeObject<List<Player>>(apiString);

            }
            return View(players);
        }

这是 WeatherForecast 控制器中的 CreateToken 方法

[HttpGet]
    

public ActionResult<string> Get()
    {
        var rng = new Random();
        var weathers = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        });
        return Ok(new {
            expireAt = DateTime.UtcNow.AddMinutes(15), token = CreateToken()
        });
    }
    public string CreateToken()
    {
        var key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(_configuration
            .GetSection("AppSettings:Token").Value));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
        var token = new JwtSecurityToken(
            claims: new List<Claim>
            {
                new Claim("firstName", "Ahmad"),
                new Claim("lastName", "Zooghii")
            },
            signingCredentials: creds,
            expires: DateTime.UtcNow.AddMinutes(15)
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

I have an API secured by Bearer token to be consumed in a mvc project. I'm using ClientFactory to call the API in mvc. I get the generated token from WeatherForecast [HttpGet] method and use it to to access the Authorized PlayerController methods. It works fine in Postman, But when I try to access PlayerController in mvc, On running a debugger It shows Unauthorized response!

Here is the action to get and use the generated token in mvc project

        private async Task<JWTToken> CreateToken()
        {
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/weatherforecast");
            var client = _clientFactory.CreateClient();
            HttpResponseMessage response = await client.SendAsync(request);
            var token = await response.Content.ReadAsStringAsync();
            HttpContext.Session.SetString("JwToken", token);
            return JsonConvert.DeserializeObject<JWTToken>(token);

        }
        public async Task<IActionResult> GetAllPlayers()
        {
            JWTToken token = null;
            var strToken = HttpContext.Session.GetString("JwToken");
            if (string.IsNullOrWhiteSpace(strToken))
            {
                token = await CreateToken();
            }
            else
            {
                token = JsonConvert.DeserializeObject<JWTToken>(strToken);
            }
            if (token == null || string.IsNullOrWhiteSpace(token.token) || token.expireAt <= DateTime.UtcNow)
            {
                token = await CreateToken();
            }
            List<Player> players = new List<Player>();
            var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:42045/api/player");
            var client = _clientFactory.CreateClient();
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.token);
            HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                var apiString = await response.Content.ReadAsStringAsync();
                players = JsonConvert.DeserializeObject<List<Player>>(apiString);

            }
            return View(players);
        }

Here is CreateToken method in WeatherForecast controller

[HttpGet]
    

public ActionResult<string> Get()
    {
        var rng = new Random();
        var weathers = Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        });
        return Ok(new {
            expireAt = DateTime.UtcNow.AddMinutes(15), token = CreateToken()
        });
    }
    public string CreateToken()
    {
        var key = new SymmetricSecurityKey(System.Text.Encoding.ASCII.GetBytes(_configuration
            .GetSection("AppSettings:Token").Value));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature);
        var token = new JwtSecurityToken(
            claims: new List<Claim>
            {
                new Claim("firstName", "Ahmad"),
                new Claim("lastName", "Zooghii")
            },
            signingCredentials: creds,
            expires: DateTime.UtcNow.AddMinutes(15)
            );
        return new JwtSecurityTokenHandler().WriteToken(token);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下客 2025-01-18 21:39:48

在startup.cs中添加 services.AddHttpClient();

并在控制器中添加此代码:

private readonly IHttpClientFactory _httpClientFactory;

public HomeController(IHttpClientFactory httpClientFactory)
{
    _httpClientFactory = httpClientFactory;
}

public async Task<IActionResult> IndexAsync()
{
    var httpClient = _httpClientFactory.CreateClient();
    var token = "your_token";
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage response = await httpClient.GetAsync("your_url");
    return View();
}

在此处输入图像描述

================== ====科尔斯策略========================

在startup.cs中添加以下代码 -> ConfigureServices 方法

services.AddCors(options =>
{
    options.AddPolicy(name: "mypolicy",
                      builder =>
                      {
                          builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
                      });
});

在startup.cs中添加app.UseCors("mypolicy"); -> app.UseRouting(); 行后面的 Configure 方法。

add services.AddHttpClient(); in startup.cs

And this code in controller:

private readonly IHttpClientFactory _httpClientFactory;

public HomeController(IHttpClientFactory httpClientFactory)
{
    _httpClientFactory = httpClientFactory;
}

public async Task<IActionResult> IndexAsync()
{
    var httpClient = _httpClientFactory.CreateClient();
    var token = "your_token";
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    HttpResponseMessage response = await httpClient.GetAsync("your_url");
    return View();
}

enter image description here

======================Cors policy========================

add below code in startup.cs -> ConfigureServices method

services.AddCors(options =>
{
    options.AddPolicy(name: "mypolicy",
                      builder =>
                      {
                          builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
                      });
});

add app.UseCors("mypolicy"); in startup.cs -> Configure method behind app.UseRouting(); line.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文