简体   繁体   English

Blazor WASM 和改装令牌

[英]Blazor WASM and Refit token

I am using refit in my blazor wasm application, I want to set the token in AuthorizationHeaderValueGetter, the api to which I connect is not written in .net.我在我的 blazor wasm 应用程序中使用 refit,我想在 AuthorizationHeaderValueGetter 中设置令牌,我连接的 api 没有写在 Z2D50972FCECD376129545507F106208 中。 but I have registered refit in the program.cs但我已经在 program.cs 中注册了改装

builder.Services.AddRefitClient<IApi>(settings).ConfigureHttpClient(c =>
    {
        c.BaseAddress = new Uri("Address");
    })

do I have to create a DelegatingHandler for this?我必须为此创建一个 DelegatingHandler 吗?

public class AuthHeaderHandler : DelegatingHandler
    {
        private readonly ILocalStorageService _localStorageService;

        public AuthHeaderHandler(ILocalStorageService localStorageService)
        {
            _localStorageService = localStorageService;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var auth = request.Headers.Authorization;

            if (auth != null)
            {
                if (await _localStorageService.ContainKeyAsync("Token"))
                {
                    string token = await _localStorageService.GetItemAsync<string>("Token");
                    request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
                }
            }

            return await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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