我已经在本地存储中拥有令牌,并准备好发送到控制器或方法具有“授权”属性的Web API,这是 Blazor客户端,我该如何发送令牌?
var token = Storage["token"];
await http.GetJsonAsync<string[]>("/api/authorizedController");
我该如何获取api上的令牌? 它会自动发生还是必须做些事情?
[Authorize]
[Route("api/[controller]")]
答案 0 :(得分:2)
我在几个地方找到了关于stackoverflow的答案,我只是不知道如何查找,我所要做的就是添加这一行代码
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
看起来像这样
var token = Storage["token"];
http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
await http.GetJsonAsync<string[]>("/api/AutorizedController");
答案 1 :(得分:2)
配合,您还需要服务器上的代码来验证每个请求的请求标头中的承载令牌。
尝试一下:
[Route("api/[controller]")]
[Authorize]
public class AutorizedController: Controller
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityCore<IdentityUser>()
.AddEntityFrameworkStores<StoreContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(cfg =>
{
cfg.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = _config["Security:Tokens:Issuer"],
ValidateAudience = true,
ValidAudience = _config["Security:Tokens:Audience"],
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Security:Tokens:Key"])),
};
});
services.AddDbContext<StoreContext>();
services.AddMvc();
}