C
C#15mo ago
fasadin

✅ Decorate class (controller) with item from httpcontext

In httpContextAccessor.HttpContext?.Items["User"] I am storing Id of user that performs calls. The way I am retrieving it
public GroupController(IHttpContextAccessor httpContextAccessor)
{
_profileId = (Guid)(httpContextAccessor.HttpContext?.Items["User"] ?? throw new ArgumentException("Invalid token"));
}
public GroupController(IHttpContextAccessor httpContextAccessor)
{
_profileId = (Guid)(httpContextAccessor.HttpContext?.Items["User"] ?? throw new ArgumentException("Invalid token"));
}
I have two questions. 1) I don't want to in constructor always build profileId I would prefer that it would be injected into constructor itself or injected into method. How to achieve this? For example something like this
[Authorize]
[HttpGet("groups")]
public async Task<IActionResult> GetGroupsByProfile(Guid profileId, CancellationToken cancellationToken)
[Authorize]
[HttpGet("groups")]
public async Task<IActionResult> GetGroupsByProfile(Guid profileId, CancellationToken cancellationToken)
2) Is there a better approach of finding out what user (id) it's performing request? The way I set this information is following: I have Middleware that performs call to another service
var response = await _httpClient.PostAsync($"authentication/authenticate?token={token}", new StringContent(""));
var response = await _httpClient.PostAsync($"authentication/authenticate?token={token}", new StringContent(""));
later I deserialize response
var userPayload = JsonSerializer.Deserialize<UserResponse>(responseContent, options)
var userPayload = JsonSerializer.Deserialize<UserResponse>(responseContent, options)
and for final part I am adding UserId to httpContext
context.Items["User"] = userPayload.Id;
context.Items["User"] = userPayload.Id;
9 Replies
Anton
Anton15mo ago
1. You can with binders, but don't. You already have the HttpContext. Just get it normally in the method. Make a helper method if you need to. 2. Store it in the claims and use the authentication system
fasadin
fasadin15mo ago
why should I do it with binders? Could you give some link to read about it :)? I am already getting it in constructor, and it's one liner so I don't think helper it's needed What it's difference between claims and Items? I need to have access to HttpContext anyway for claims
Anton
Anton15mo ago
Doing it in the constructor is fine as long as you don't need to await for claims read on authentication I'm saying you should not use binders, they're just confusing when used for this purpose if you want to refactor the id extraction, define an extension method for HttpContext, problem solved Or make a service that extracts it, if you need it to be a bit more flexible
fasadin
fasadin15mo ago
oh sorry. I thought I wrote why I shouldn't do it with binders 🙂 I did read it right in first place but just curious why not to what is advantage using claim instead of adding things to Items ? because in the end: - you need to access IHttpContextAccessor and read it from it - you need to define behaviors for given entry
Anton
Anton15mo ago
authentication I've already mentioned it 2 times already you use a standard system for this you only need IHttpContextAccessor if you move that logic into a service otherwise you already have the access to HttpContext in the controller The benefit is that the client would send it to you with the token you won't have to make further calls for it you can just send it to the client when you generate the authentication token
fasadin
fasadin15mo ago
I didn't want that on request userId it's provided. I preferred getting that userId based on Token and then on token I do create claims
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString())
}
),
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.UniqueName, user.Id.ToString())
}
),
but anyway, that's offtopic. There are binders, or just accesting it through IHttpContextAccessor there is no other way around it 😉 thanks for helping out ❤️ 🙂
Anton
Anton15mo ago
why not? if you're the one who generates the token, it's the simplest way imo
fasadin
fasadin15mo ago
because I don't want to expose any data that can be used by malicious intent. The less information the better 😅 but it's embedded into token, so maybe indeed I should just make claims and pair those together as it is exposed
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.