Longinos Ruvalcaba
Longinos Ruvalcaba

Reputation: 135

Blazor jwt from client to server

I already have the token in local storage and ready to send to the web api where the controller or the method has en Authorize attribute this es the Blazor client, How do I send the token ?

        var token = Storage["token"];
     await http.GetJsonAsync<string[]>("/api/authorizedController");

And how do I recive the token on the api ? Does it happens automatically or do I have to do somehting ?

    [Authorize]
[Route("api/[controller]")]

Upvotes: 2

Views: 902

Answers (2)

enet
enet

Reputation: 45586

Mate, you also need code on the server to validate the bearer token in your request header on each request.

Try this:

[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();
    }

Upvotes: 2

Longinos Ruvalcaba
Longinos Ruvalcaba

Reputation: 135

I found the answer here on stackoverflow in several places I just did not know how to look for it all I needed to do was to add this line of code

http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

and it looked like this all together

var token = Storage["token"];
    http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    await http.GetJsonAsync<string[]>("/api/AutorizedController");

Upvotes: 2

Related Questions