Blazor get request with jwt token

Viewed 48

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

1 Answers

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");
Related