简体   繁体   中英

Blazor get request with jwt token

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM