简体   繁体   中英

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:

https://chrissainty.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.

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.

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

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