© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
24 replies
WillowBear

❔ What is the appropriate way to confirm User ID for API

Hi folks,

I'm creating a WebApi to go alongside my front-end. Each call to my controller and related service has the
[Authorize]
[Authorize]
attribute so I know that a user has to be authorized before accessing the data.

My query is regarding the retrieval of the UserID to get the user-specific data from my database.

This is what I have currently:

cs 
[Authorize]
public class CategoryService : ICategoryService
{
    private readonly DataDbContext        _context;
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    private readonly string? _userId;

    public CategoryService(DataDbContext context, IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _httpContextAccessor = httpContextAccessor;
        
        _userId = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    
    public async Task<List<CategoryDTO>> GetAll()
    {
        return await _context.Categories.Where( c => c.UserId == _userId ).Select( c => new CategoryDTO()
            {
            Id = c.Id,
            Name = c.Name
            } ).ToListAsync();
    }
cs 
[Authorize]
public class CategoryService : ICategoryService
{
    private readonly DataDbContext        _context;
    private readonly IHttpContextAccessor _httpContextAccessor;
    
    private readonly string? _userId;

    public CategoryService(DataDbContext context, IHttpContextAccessor httpContextAccessor)
    {
        _context = context;
        _httpContextAccessor = httpContextAccessor;
        
        _userId = _httpContextAccessor.HttpContext?.User.FindFirstValue(ClaimTypes.NameIdentifier);
    }
    
    public async Task<List<CategoryDTO>> GetAll()
    {
        return await _context.Categories.Where( c => c.UserId == _userId ).Select( c => new CategoryDTO()
            {
            Id = c.Id,
            Name = c.Name
            } ).ToListAsync();
    }


Is this an acceptable and importantly safe way to do it? I'm fairly new to Authorization/Authentication so trying to create a portflio worthy project without any glaringly obvious security flaws.

TIA
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

What return method is appropriate for controller actions for SPA frontend?
C#CC# / help
2y ago
What is the best way to return errors in api controllers?
C#CC# / help
2y ago
✅ What is the best way to learn c/c#?
C#CC# / help
3y ago
✅ What is the best way to store basic C#?
C#CC# / help
3y ago