简体   繁体   English

ASP.NET 核心 JWT 令牌无法通过 HttpClient 工作

[英]ASP.NET Core JWT Token not working via HttpClient

I'm new to JWT authentication and I've configured my ASP.NET Core 3 API for token authentication using the tutorial here:我是 JWT 身份验证的新手,我已经使用此处的教程配置了我的 ASP.NET Core 3 API 进行令牌身份验证:

https://chrissainty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/ https://chrissinty.com/securing-your-blazor-apps-authentication-with-clientside-blazor-using-webapi-aspnet-core-identity/

I've added the [Authorize] attribute to the controller, and using Postman I can login and get a token, and use the token via Postman to retrieve the data from the controller - all works as expected to here. I've added the [Authorize] attribute to the controller, and using Postman I can login and get a token, and use the token via Postman to retrieve the data from the controller - all works as expected to here.

My issue is when I login using the C# HttpClient via a Xamarin app, and then I use the the token that is sent back I get a 401 error accessing the controller either via Postman or HttpClient . My issue is when I login using the C# HttpClient via a Xamarin app, and then I use the the token that is sent back I get a 401 error accessing the controller either via Postman or HttpClient .

The code I'm using is as follows:我正在使用的代码如下:

var client = new HttpClient();

var model = new JwtLoginModel()
            {
                Email = email,
                Password = password,
                RememberMe = false
            };

var json = JsonConvert.SerializeObject(model);

HttpContent httpContent = new StringContent(json);
var response = await client.PostAsync(Constants.BaseApiAddress + "api/Login", new StringContent(json, Encoding.UTF8, "application/json"));

var content = await response.Content.ReadAsStringAsync();
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(content);
var accessToken = jwtDynamic.Value<string>("token");

Using the returned accessToken via Postman (and HttpClient ), both return a 401 error.使用通过 Postman (和HttpClient )返回的accessToken ,两者都返回 401 错误。

Can anyone suggest what I'm doing wrong?谁能建议我做错了什么?

Thanks all for the help谢谢大家的帮助

In the end I decided it was easier to go with Identity Server 4 implementation which is working perfectly最后,我决定使用运行良好的 Identity Server 4 实现 go 更容易

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

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