I use this repo to implement authentication and authorization with cookie on the Blazor Server.
Suppose that I'd like to retrieve the current logged-in user in the DeleteHotelRoomAsync
method in HotelRoomService.cs to log the information of the user who deleted a room.
public async Task<int> DeleteHotelRoomAsync(int roomId)
{
var roomDetails = await _dbContext.HotelRooms.FindAsync(roomId);
if (roomDetails == null)
{
return 0;
}
_dbContext.HotelRooms.Remove(roomDetails);
//ToDo
//_dbContext.DbLog.Add(userId,roomId);
return await _dbContext.SaveChangesAsync();
}
I can't use of AuthenticationStateProvider as it is there or there, becuase of cookie based system and so the AuthenticationStateProvider is null in below code.
I used HttpContextAccessor, and I could retrieve the authenticated userId as below, however, I couldn't use HttpContextAccessor because of Microsoft recommendations.
public class GetUserId:IGetUserId
{
public IHttpContextAccessor _contextAccessor;
private readonly AuthenticationStateProvider _authenticationStateProvider;
public GetUserId(IHttpContextAccessor contextAccessor,AuthenticationStateProvider authenticationStateProvider)
{
_contextAccessor = contextAccessor;
_authenticationStateProvider = authenticationStateProvider;
}
public string Get()
{
var userId = _contextAccessor.HttpContext.User.Claims.First().Value;
return userId;
}
}
So is there any safe ways to retrieve authenticated user info (e.g. userId) in a .cs file to log it into database logs for user audit log?