如何将不记名令牌添加到 HTTP 请求的标头? [英] How do I add a Bearer Token to the header of a HTTP request?
问题描述
我无法弄清楚如何设置授权标头,以授权为键,以不记名令牌为值.
I am having trouble figuring out how to set authorization headers with authorization as the key and a bearer token as the value.
我已经完成了一个内置身份验证的 Web API.我已经在邮递员上进行了测试,一切正常.问题出在邮递员身上,我将令牌副本通过它复制到一个新的键和值,在该站点中,我不确定如何在 Blazor 项目中更改这些值.
I have completed a web API with authentication built into it. i have tested it on postman and it all works. the problem is on post man i take the token copy past it to a new key and value, in the site i am not sure how to change those values in a Blazor project.
当在 http://testapi.com/api/token/输入获取 API 时a>{username}/{password} API 发回一个代码,我需要获取该代码并将其放入标头中.
When entering a Get to the API at http://testapi.com/api/token/{username}/{password} the API sends back a code i need to take that code and put it in the header.
登录.razor
@page "/"
@inject HttpClient Http
<h1>Hello, world!</h1>
Welcome To The New Site
<EditForm Model="@use" OnValidSubmit="@HandleValidSubmit" OnInvalidSubmit="@HandleInvalidSubmit" Context="EditFormContext">
<DataAnnotationsValidator />
<DxFormLayout>
<DxFormLayoutItem Caption="Username:" ColSpanMd="6">
<Template>
<DxTextBox @bind-Text="@use.username" />
</Template>
</DxFormLayoutItem>
<DxFormLayoutItem Caption="Password:" ColSpanMd="6">
<Template>
<DxTextBox @bind-Text="@use.password" />
</Template>
</DxFormLayoutItem>
<DxFormLayoutItem ColSpanMd="12">
<Template>
<ValidationSummary />
</Template>
</DxFormLayoutItem>
<DxFormLayoutItem ColSpanMd="12">
<Template>
<button type="submit">Submit</button>
</Template>
</DxFormLayoutItem>
</DxFormLayout>
</EditForm>
@code {
User[] token;
User use = new User();
async void HandleValidSubmit()
{
token = await Http.GetJsonAsync<User[]>("http://testapi.com/api/token/" + use.username + "/" + use.password);
if (token != null)
{
await SaveToken();
await SetAuthorizationHeader();
Console.WriteLine("OnValidSubmit");
}
}
private void HandleInvalidSubmit()
{
Console.WriteLine("OnInvalidSubmit");
}
private async Task SaveToken()
{
}
private async Task SetAuthorizationHeader()
{
}
class User
{
public string username { get; set; }
public string password { get; set; }
}
}
推荐答案
如果您使用的是服务器端 Blazor @Pascal R. 答案应该会让您走上正确的道路.对于客户端 Blazor:
If you are using a server side Blazor @Pascal R. answer should bring you to the right path. For client side Blazor:
- 将令牌保存到您的应用的全局可访问存储中.像本地存储或级联值
- 每次需要进行经过身份验证的 ws 调用时,都会从存储中获取令牌并将其添加为标头.
要将令牌保存在本地存储中,我建议使用:Blazored 本地存储.
To save the token in local storage I recommend using: Blazored Local storage.
这篇关于如何将不记名令牌添加到 HTTP 请求的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!