简体   繁体   中英

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. but I have registered refit in the program.cs

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

do I have to create a DelegatingHandler for this?

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

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