[SOLVED] Blazor get request with jwt token

Issue

This Content is from Stack Overflow. Question asked by Mhamad Tabikh

I want to send an authorized get request from my blazor wasm app.
The request when issued from postman works fine,my code is as follows :

Program.cs:

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddOptions();
builder.Services.AddAuthorizationCore();
builder.Services.AddScoped<AuthenticationStateProvider, PortalAuthStateProvider>();
builder.Services.AddMudServices();

await builder.Build().RunAsync();

MyPage.razor :

protected override async Task OnInitializedAsync(){
string authToken = await LocalStorage.GetItemAsStringAsync("authToken"); //returned normally
Http.DefaultRequestHeaders.Add("Bearer", authToken);
var result = await Http.GetFromJsonAsync<ApplicationDto[]>("api/Applications");
}

it returns 401 unauthorized,the api controller is decorated with [Authorize] attribute,the token is generated and returned normally,using the same generated token in postman works fine



Solution

The correct way to add the authorization header is following:

Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);

Or:

Http.DefaultRequestHeaders.Add("Authorization", $"Bearer {authToken}");

Also GetItemAsStringAsync is messing up the token. Use GetItemAsync<string> instead:

string authToken = await LocalStorage.GetItemAsync<string>("authToken");


This Question was asked in StackOverflow by Dsg951 and Answered by Dimitris Maragkos It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?