JWT登录身份验证Web API调用

时间:2020-10-29 19:03:21

标签: c# entity-framework api jwt

我有一个使用JWT令牌对用户进行身份验证的MVC Web应用程序。它调用身份验证/登录API来生成和检索令牌。调用API时,“ response.IsSuccessStatusCode”成功,状态为200。但是“ User.Identity.IsAuthenticated” obj仍然为false,然后在尝试导航时出现4001错误,我得到了http错误401状态。

using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:44395/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                HttpContent content = new StringContent(jsonString, Encoding.UTF8, "application/json");
                
                var response = await client.PostAsJsonAsync("api/Authentication/Authenticate", values);
                if (response.IsSuccessStatusCode)
                {
                    
                    Users user = await response.Content.ReadAsAsync<Users>();
                    //JWT jwt = JsonConvert.DeserializeObject<JWT>(user);
                    HttpContext.Session.SetString("token", user.Token);

                    var tokenStr = GenerateJsonWebToken(values);
                   

                    CurrentUser.UserId = user.UserId;
                    CurrentUser.FirstName = user.FirstName;
                    CurrentUser.LastName = user.LastName;
                    
                    if(User.Identity.IsAuthenticated)
                    {

                    }

                    return RedirectToAction("Profile", "Profile");
                }

4001 error

0 个答案:

没有答案