Inside some web api controllers, I would like to access the User as indicated in this answer: https://stackoverflow.com/a/12705062/538962
sample code from answer...
[Authorize]
public List<Product> GetProductsFromId()
{
string username = User.Identity.Name;
return _productService.GetProductsFromUsername(username);
}
The asp_net membership tables in my scenario are on a different database server than then the database server the application runs on. The database for the application has its own Users table with an IDENTITY column
as the Primary Key
on the Users table, and then other tables that include a CreatedByUserID
and UpdatedByUserID
columns are integers
based off the IDENTITY column
in the users table.
The issue is that if CRUD type operations depend on the user being updated in tables as an INTEGER
, just accessing the username alone is not sufficient; we still have to get to that username's corresponding UserID
.
This could be done with another join to the Users table, but this seems a bit kludgy. What would be the best way to go about handling this issue?
From the perspective of ASP.NET Web API, using membership provider and the out-of-box FormsAuthentication is already kludgy, so why not the join? :) Anyways, assuming your web API is consumed by only the web clients and FA is cool, you can use the UserData of the FA ticket to put in the user ID. That way, you don't need to get the ID by hitting your DB every time. But you will need to create the ticket yourself and not let the default out-of-box implementation do that for you. Then, in the PostAuthenticateRequest event, you can read the user ID from the ticket and set it in the identity. Of course, you need to create your own custom identity for this with an ID property or if you are on .NET 4.5, you can use FormsIdentity itself but you can use the NameIdentifier claim to store the ID, perhaps. Check this out - ASP.NET MVC - Set custom IIdentity or IPrincipal.