簡體   English   中英

如何在HTTP請求的標頭中添加承載令牌?

[英]How do I add a Bearer Token to the header of a HTTP request?

我在弄清楚如何設置以授權作為密鑰和以承載令牌為值的授權標頭方面遇到麻煩。

我已經完成了內置身份驗證的Web API。 我已經在郵遞員上對其進行了測試,並且一切正常。 問題出在郵遞員上,我將令牌副本通過它傳遞到新的鍵和值,在站點中,我不確定如何在Blazor項目中更改這些值。

http://testapi.com/api/token/ {username} / {password}輸入Get to the API時,API會發回一個代碼,我需要將該代碼放入標頭中。

login.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; }
    }
}

我使用API​​ / IdentityServer4 / Blazor(服務器端)進行了類似的設置。 也許您可以使用我在這個stackoverflow問題中發布的一些代碼。

如果您使用的是服務器端Blazor @PascalR。答案應該可以帶您進入正確的路徑。 對於客戶端Blazor:

  1. 將令牌保存到您應用的全局可訪問存儲中。 像本地存儲或級聯值
  2. 每次您需要進行經過身份驗證的ws調用時,都會從存儲中獲取令牌並將其添加為標頭。

要將令牌保存在本地存儲中,我建議使用: Blazored Local storage

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM