[英]Blazor get request with jwt token
I want to send an authorized get request from my blazor wasm app.我想从我的 blazor wasm 应用程序发送授权获取请求。 The request when issued from postman works fine,my code is as follows:
从 postman 发出的请求工作正常,我的代码如下:
Program.cs:程序.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: 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它返回401未授权,api controller装饰有[Authorize]属性,令牌生成并正常返回,使用postman中生成的相同令牌工作正常
The correct way to add the authorization header is following:添加授权 header 的正确方法如下:
Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authToken);
Or:或者:
Http.DefaultRequestHeaders.Add("Authorization", $"Bearer {authToken}");
Also GetItemAsStringAsync
is messing up the token. GetItemAsStringAsync
也弄乱了令牌。 Use GetItemAsync<string>
instead:请改用
GetItemAsync<string>
:
string authToken = await LocalStorage.GetItemAsync<string>("authToken");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.