如何在 ASP.NET CORE 中将 Bearer 令牌添加到请求中
我有一个由 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在startup.cs中添加
services.AddHttpClient();
并在控制器中添加此代码:
================== ====科尔斯策略========================
在startup.cs中添加以下代码 ->
ConfigureServices
方法在startup.cs中添加
app.UseCors("mypolicy");
->app.UseRouting();
行后面的Configure
方法。add
services.AddHttpClient();
in startup.csAnd this code in controller:
======================Cors policy========================
add below code in startup.cs ->
ConfigureServices
methodadd
app.UseCors("mypolicy");
in startup.cs ->Configure
method behindapp.UseRouting();
line.