Reputation: 1545
I have a local API I am running for my project where I hacked together a method to grab profile data of a currently signed in user like so:
[HttpGet("profile"), Authorize]
public async Task<ActionResult> GetProfile()
{
var claim = HttpContext.User.Claims.First(o => o.Type == "id");
var usr = _userVerification.GetUser(int.Parse(claim.Value));
return new OkObjectResult(new GenericAPIResponse<ProfileVM>(new ProfileVM()
{
FirstName = usr.FirstName,
Id = usr.UserId,
LastName = usr.LastName,
Role = (ProfileVM.RoleType)usr.Role
}));
}
In the API project I have configured a JWT auth and am passing a token through the Authorization
header to "sign in". When I do it manually through fiddler everything works fine, but whenever I try calling it from the client app it just never wants to put that header in the request for some unknown reason.
In my client I finally settled for this kind of approach with RestSharp:
if (bearer != null)
client.Authenticator = new JwtAuthenticator(bearer);
...
public async Task<GenericAPIResponse<ProfileVM>> GetUserProfile()
{
var req = new RestRequest("/user/profile");
//req.AddHeader("Authorization", $"Bearer {bearer}"); <- tried that as well but no luck
var res = await client.ExecuteAsync(req);
return JsonConvert.DeserializeObject<GenericAPIResponse<ProfileVM>>(res.Content);
}
Now the problem is I always keep getting a 401 error because the AUTHORIZATION header never gets included in the request. I tired with Refit earlier as well by making a method declaration as such:
Task<GenericAPIResponse<ProfileVM>> GetProfile([Header("Authorization")] string token);
Nothing. It just seems like I can't add an authorization header to my requests no matter what I do, while adding any other X-
header with Refit works just fine.
Here's what the above code with RestSharp results in (copied from Fiddler4):
GET https://localhost:44355/api/user/profile HTTP/1.1
Host: localhost:44355
Accept: application/json, text/json, text/x-json, text/javascript, application/xml, text/xml
User-Agent: RestSharp/106.15.0.0
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
I am officially out of ideas and starting to go in circles. What am I missing here? Can I get some fresh perspective here please?
Upvotes: 0
Views: 1026
Reputation: 13537
A RestRequest
is just an HttpRequest
with a fancy coat of paint, so I always add a bearer token header like this, by adding it to a HttpRequestMessage
object which I hand off to an HttpClient
to process for me.
var request = new HttpRequestMessage(HttpMethod.Get, myFullUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await this.httpClient.SendAsync(request, cancellationToken);
To do this using RestSharp's native functionality, you'd do this.
client.AddDefaultHeader("Authorization", string.Format("Bearer {0}", bearerToken));
The idea is that you authenticate the RestClient
itself, instead of adding the authentication to each Rest request.
Upvotes: 1