请求标头中没有承载令牌

时间:2020-10-22 11:07:26

标签: asp.net-core .net-core blazor blazor-client-side blazor-webassembly

使用Blazor 3.2,我需要在请求标头中自动发送安全令牌,不使用身份,在服务器上为用户提供自定义表格,从登录控制器获取令牌并将其保存到本地存储中

public class JWTAuthenticationStateProvider : AuthenticationStateProvider, ILoginService
    {
        private readonly IJSRuntime js;
        private readonly HttpClient httpClient;
        private readonly string TOKENKEY = "TOKENKEY";
        private AuthenticationState Anonymous => new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity()));

        public JWTAuthenticationStateProvider(IJSRuntime js, HttpClient httpClient)
        {
            this.js = js;
            this.httpClient = httpClient;
        }
        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var token = await js.GetFromLocalStorage(TOKENKEY);
            if (string.IsNullOrEmpty(token))
            {
                return Anonymous;
            }
            return BuildAuthenticationState(token);
        }

        public AuthenticationState BuildAuthenticationState(string token)
        {
     
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(ParseClaimsFromJwt(token), "jwt")));
        }



        public async Task Login(string token)
        {
            await js.SetInLocalStorage(TOKENKEY, token);
            var authState = BuildAuthenticationState(token);
            NotifyAuthenticationStateChanged(Task.FromResult(authState));
        }

        public async Task Logout()
        {
            await js.RemoveItem(TOKENKEY);
            httpClient.DefaultRequestHeaders.Authorization = null;
            NotifyAuthenticationStateChanged(Task.FromResult(Anonymous));
        }
    }

对于我使用的请求:

public interface IHttpService
    {...
        Task<HttpResponseWrapper<object>> Post<T>(string url, T data);
      ...       
    }
    public class HttpService : IHttpService
    {
        private readonly HttpClient httpClient;
        private JsonSerializerOptions DefaultJsonSerializerOptions =>
             new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };

        public HttpService(HttpClient _httpClient)
        {
            httpClient = _httpClient;
        }


    .......   

        public async Task<HttpResponseWrapper<object>> Post<T>(string url, T data)
        {
            var dataJson = JsonSerializer.Serialize(data);
            var stringContent = new StringContent(dataJson, Encoding.UTF8, "application/json");
            var response = await httpClient.PostAsync(url, stringContent);
            return new HttpResponseWrapper<object>(null, response.IsSuccessStatusCode, response);
        }

.........

public class HttpResponseWrapper<T>
    { 
        public HttpResponseWrapper(T response, bool succes, HttpResponseMessage httpResponseMessage)
        {
            Response = response;
            Success = succes;
            HttpResponseMessage = httpResponseMessage;
        }
        public T Response { get; set; }
        public bool Success { get; set; }
        public HttpResponseMessage HttpResponseMessage { get; set; }

        public async Task<string> GetBody()
        {
            return await HttpResponseMessage.Content.ReadAsStringAsync();
        }
    }

当我向服务器发送请求时:

 var res = await httpService.Post<QueryObject, ResObject>($"{url}/get", query);

我得到401(未经授权),在开发工具中我在请求中没有看到Bearer令牌

标头::权限:本地主机:44341:方法:POST:路径: / api / datar / get:scheme:https accept:/ accept-encoding:gzip, 放气,br接受语言:en-US,en; q = 0.9缓存控制:无缓存 内容长度:123内容类型:application / json;字符集= utf-8 cookie:.AspNet.Consent =是; .AspNetCore.Session = CfDJ8KV1S2nC4ehItE9KmaCETAilfhhNr%2BP3SQORWHzxbFYQLddeekAftj05md7N%2BWYjU1LxdcIBY4XW9muw13u2q2clwdsmQHLb2DqCKkQW%2FbcquzDPKYbcAtcuJEJ2OpOz75zgMYhRmL47zGhNvmhhHXbEEKGnQwpAk8gnAe6bF6XC 来源:https:// localhost:44341编译指示:无缓存引荐来源: https:// localhost:44341 / sch sec-fetch-dest:空sec-fetch-mode:cors sec-fetch-site:同源用户代理:Mozilla / 5.0(Windows NT 10.0; Win64; x64)AppleWebKit / 537.36(KHTML,例如Gecko)Chrome / 86.0.4240.80 Safari / 537.36 OPR / 72.0.3815.148

0 个答案:

没有答案