WillowBear
WillowBear
CC#
Created by WillowBear on 6/7/2023 in #help
❔ 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
25 replies