Ya tengo el token en el almacenamiento local y estoy listo para enviarlo a la API web donde el controlador o el método tienen un atributo de Autorización, esto es, el cliente Blazor. ¿Cómo envío el token?
var token = Storage["token"];
await http.GetJsonAsync<string[]>("/api/authorizedController");
¿Y cómo recibo el token en la api? ¿Ocurre automáticamente o tengo que hacer algo?
[Authorize]
[Route("api/[controller]")]
Mate, también necesita un código en el servidor para validar el token de portador en el encabezado de su solicitud en cada solicitud.
Prueba esto:
[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();
}