I have a REST API service which needs to validate any kind of user (for example a Windows user) and add a reference to it into a database table for later usage.
To do so, I need to know the current user in Entity Framework Core, because the user is stored as the creator of an entity.
I am trying to abstract the coupling the current user in the SaveChanges
method from the DbContext
where the user is being coupled when an entity is being created.
But how to get the current user in the DbContext
? I am trying to use delegation, but I am stuck in the way the DI needs to register the UserService
which abstracts the user and returns the ID.
CodePudding user response:
I think we may need some more detail, but with what is there at least if You are in a .net web api controllerbase context you have
System.Security.Principal.IIdentity user = User?.Identity;
if (user != null && user.IsAuthenticated)
System.Diagnostics.Debug.WriteLine($"Username: {user.Name}");
It much depends in this sense which claims tings are put in where you will find what and if you use a completely different authentication scheme things could look different :)
CodePudding user response:
If I had an object
public myObj
{
public int myObjID {get; set;}
public string ObjectDetails {get; set;}
# I would add this field
public string UserName {get; set;}
}
Then in a controller action where I would store the object, I would do:
myObj.UserName = User.Identity?.Name ?? "";
The null checking is especially redundant if [Authorize]
has been applied to the controller because there is no way you can land on the action without being authorized and the application requires that you have a user name (at the barest minimum).
If you ever need to find out who did what:
var obj = await db.myObj.where(x=> x.UserName == User.Identity.Name).ToListAsync()
or
var obj = await db.myObj.where(x=> x.UserName == uname).ToListAsync();
where uname
is a method argument or etc.