Understanding MVC5 UserClaim Table - c#

I have been doing a lot of research but none resulted in helping me understand what is the point of UserClaim Table.
When you create a MVC5 project, there are some default tables created upon your database being registered. I understand the purpose of all of them except UserClaim.
From my understanding, User Claims are basically key pair values about the user. For example if I want to have a FavouriteBook field, I can add that field to the user table and access it. Actually I already have something like that built in. Each of my users have "Custom URL" And so I have created a claim in the following way:
public class User : IdentityUser
{
public string CustomUrl { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("CustomUrl", CustomUrl));
return userIdentity;
}
}
public static class UsersCustomUrl
{
public static string GetCustomUrl(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("CustomUrl");
return (claim != null) ? claim.Value : string.Empty;
}
}
Above basically allows me to access the CustomUrl by simply calling User.Identity.GetCustomUrl()
The above code won't write to the UserClaims table as the value exists in the Users Table. So what is the point of this table?
I am speculating that maybe I should add CustomUrl to UserClaims and somehow bind that to identity and that may what it is for? I would love to know the answer!

Claims are really useful in cases where you present multiple ways in which your users can register / sign on with your website... in particular, I'm talking about third-party authentication with organisations such as Google, Facebook and Twitter.
After a user has authenticated themselves through their chosen third party, that third party will disclose a set of claims to you, a set of information that describes the user in a way that you can identify them.
What information the claims will contain varies from provider to provider. For example, Google will share the users email address, their first name, their last name but compare that to Twitter... Twitter doesn't share any of that, you receive the identifier of their Twitter account along with their access tokens.
Claims based authentication provides a simple method to facilitate all this information, whilst the alternative may very well have meant creating tables in your database for each individual provider you worked with.

Related

ASP.NET core Web API: Authorization based on permissions from database

I am looking for a solution/suggestion that helps me creating permission based access to web api endpoints/controller actions.
Role based access is not suitable becuase I don't have fixed rules that I could use in code like Role("Admin") oder Role("Controller").
Claim based permissions is also not feasable because each user/client can have different permissions on each business object/entity (e.g. Read/Write-access to own tickets and read access to all ticket of his/her company or if its a technician of my company full access to all tickets of all customers. So each user would have 10s or even hundrets of claims which I would have to evaluate at each access of my API.
It is some kind of multi tenancy in just on database and the tenants are our customers with some kind of "master tenant" that has access to all of the tenant data.
I think that something like Visual Guard would satisfy my needs but it is pretty expensive and they don't support net core for now and their documentation seems pretty outdated.
I don't need a usable solution at once but some hints and tricks how I could achieve that would very much be apprieciated because I am looking and searching for some time now.
Details on "database permissions":
What I mean is in my frontend (Winforms app) I want to establish a security system where I can create and assign roles to users and in those roles is defined which actions a user can execute and which CRUD operations he/she can do on specific business objects. Each role can have n users and each role can have n permissions. Each permission on itself declares for exmaple Create:false, Read:true, Write:true and Delete:false. If a permission for a specific business object is not found CRUDs on that BO is denied totally.
So whenever an action in my API is called I have to check if that user and his/her rule allows him to do that specific action based on rules and permissions in my database.
Details an application structure:
Frontend will be a Winforms app which calls the API in the background by OData. I don't want to rely solely on security in the Winforms app because the API will be accessible from the internet and I can't be sure if a user would not try to access the api with his credentials just to see what is possblie without the "frontend filter". So the permissions lie in the API and if a user tries to access s.t. in the frontend app the app itself "asks" the API if that is possible.
Later on I want to create mobile clients that also use the Odata Web API.
The relevant API in asp.net core are:
IAuthorizationService
AuthorizationPolicy
IAuhtorizationRequirement
IAuthorizationHandler
The authorization pattern you are looking for is called Resource-based authorization
https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-2.2
Basically, you can define AuthorizationPolicy, and apply it to a instance of a resource:
var ticket = _ticketRepository.Find(ticketID);
var authorizationResult = await _authorizationService
.AuthorizeAsync(User, ticket, "EditTicketPolicy");
In the authorization handler, you can check if the user is the owner of the resource.
public class ResourceOwnerRequirement : IAuthorizationRequirement
{
}
public class ResourceOwnerHandler
: AuthorizationHandler<ResourceOwnerRequirement, MyBusinessObject>
//: AuthorizationHandler<ResourceOwnerRequirement> use this overload to handle all types of resources...
{
protected override Task HandleRequirementAsync(
AuthorizationHandlerContext context,
ResourceOwnerRequirement requirement,
MyBusinessObject resource)
{
int createdByUserId = resource.CreatedBy;
Claim userIdClaim = ((ClaimsIdentity)context.User.Identity).FindFirst("UserId");
if (int.TryParse(userIdClaim.Value, out int userId)
&& createdByUserId == userId)
{
context.Succeed(requirement);
}
}
}
//admin can do anything
public class AdminRequirementHandler : IAuthorizationHandler
{
public Task HandleAsync(AuthorizationHandlerContext context)
{
if (context.User.Claims.Any(c => c.Type == "Role" && c.Value == "Administator"))
{
while (context.PendingRequirements.Any())
{
context.Succeed(context.PendingRequirements.First());
}
}
return Task.CompletedTask;
}
}
BTW, this still can be called claims or role based authorization. Users with specific role can edit their own tickets, but users with admin role also other tickets. The difference is that you apply authorization to a resource, not just action
EDIT:

C# IUserStore implementation GetPasswordHash

By default, MVC 5 Single Page Application uses EntityFramework to store users and passwords for authentication.
In my scenario, I must use an existing homemade AuthenticationService.
I decided to create a custom IUserStore. I then must implement the GetPasswordHashASync to validate credentials.
Our architect considers this as a security breach but I do not agree with this. I then would like to get your opinion about this.
What is the difference between getting the PasswordHash for the database of another service on the same server node. In my opinion, I dont this it is a security breach...
Here's some code to demonstrate how it works.
The user logs in with his credentials so it calls the Login Method of my AccountController. Then, it calls the UserManager FindUserAsync:
var user = await UserManager.FindAsync(model.Email, model.Password);
Since I create my own IUserStore, I call our service (WFC) like this:
if (client.IsUsernameExists(userName, remoteInfo, out messages))
{
user = new ApplicationUser() { Email = userName, Username = userName};
}
Under the hood it then calls the GetPasswordHashAsync. My implementation then call our service again:
passwordHash = client.GetPasswordHash(user.Username, RemoteInfo, out messages);
Any thoughts?
The interface you are looking to implement is the IUserPasswordStore. Nothing wrong with that.
This is the correct way of implementing the IdentityStores of OWIN (and probably other authentication frameworks).
I've implemented my own UserStore for a MongoDB implementation of OWIN. Here is my implementation of the IUserPasswordStore
public Task SetPasswordHashAsync(TUser user, string passwordHash)
{
user.PasswordHash = passwordHash;
return Task.FromResult(0);
}
public Task<string> GetPasswordHashAsync(TUser user)
{
return Task.FromResult(user.PasswordHash);
}
The password hash is stored in the DB, so when you pull the user from the DB, it has a property which is the hash. So the appropriate implementation for GetPasswordHashAsync, is to return the hash from the user object.

Dynamic User Claims in ASP.NET Identity EF

I'm working on an authentication system that uses ASP.NET Identity with Entity Framework, and I want to have a few claims that are computed values instead of being hardcoded into the claims table.
When a user logs in, how can I add dynamic claims to that login session without actually adding them to the claims table?
For example, I may want to store each user's DOB, but I want add IsBirthday as a claim if the login date matches the user's DOB. I don't want to have to store a "IsBirthday" claim for each user since it changes daily for everyone.
In my code, I use this to log in:
var signInResult = await SignInManager.PasswordSignInAsync(username, password, false, false);
After this is called I can reference the ClaimsPrincipal, but the Claims property is an IEnumerable, not a List, so I can't add to it.
EDIT: I should also mention I am using the Microsoft.AspNet.Identity.Owin libraries.
OK, everyone, I did a bit of digging into the classes provided in ASP.NET Identity and found the one I needed to override. The SignInManager class has a CreateUserIdentityAsync method that does exactly what I was wanting. The following code added the IsBirthday claim to my identity but didn't store it in the database.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public override async Task<System.Security.Claims.ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
var identity = await base.CreateUserIdentityAsync(user);
identity.AddClaim(new System.Security.Claims.Claim("IsBirthday", user.DOB.GetShortDateString() == DateTime.Now.GetShortDateString()));
return identity;
}
// ... EXCLUDING OTHER STUFF LIKE CONSTRUCTOR AND OWIN FACTORY METHODS ...
}

How to pass current context to an object c#

I am creating an application where I first login with my user account. This user account could be windows or self managed account in my own application database.
Now I want to authorize the logged in user before accessing any business objects of my application. Objects are mapped with database tables so eventually I want to authorize user first, whether to give data back to user or not.
After logging in I store user credentials globally as an object of UserCredential class. But I don't want to pass this credentials to each object when I am creating it.
Is there any way to check/reach the application context (including UserCredential object I stored globally) for each business objects automatically which I am creating further?
I want to achieve this in C#. Code example is much appreciated.
You should take a look at the PrincipalPermissionAttribute class, here is the MSDN documentation:
PrincipalPermissionAttribute class MSDN documentation
The PrincipalPermissionAttribute throws a SecurityException when the Thread.CurrentPrincipal does not match the security assertion.
Examples:
User's name is GDroid:
[PrincipalPermission(SecurityAction.Demand, Name = "GDroid")]
public void YourBusinessMethod()
{
// Do something
}
User belongs to Admin role:
[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
public void YourBusinessMethod()
{
// Do something
}
User is authenticated:
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public void YourBusinessMethod()
{
// Do something
}

What is GenericIdentity?

Can anyone briefly explain what is the use of GenericIdentity and where to use it.
GenericIdentity and GenericPrincipal are the simplest way of describing a user as a "principal". This can be used for implementation-unaware security checking in an application - i.e. if the user logs in as "Fred" with the "User" and "Admin" permissions:
string[] roles = { "User", "Admin" };
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity("Fred"), roles);
You might do this at the point of client login to a winform, or there are specific points to do this in WCF, ASP.NET, etc.
Then later code, without having to know how those permissions are handled, can check that permission - either via IsInRole, or declaratively:
[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
void SomeAdminFunction() { }
Some useful utility code here is null-safe wrappers around principal/identity:
public static string GetUsername() {
IPrincipal principal = Thread.CurrentPrincipal;
IIdentity identity = principal == null ? null : principal.Identity;
return identity == null ? null : identity.Name;
}
public static bool IsInRole(string role) {
IPrincipal principal = Thread.CurrentPrincipal;
return principal == null ? false : principal.IsInRole(role);
}
Then you might have some audit code in your DAL:
row.UpdatedBy = MyUtilityClass.GetUsername();
GenericPrincipal is useful for the simple cases of a plain username and set of known roles.
More sophisticated principal implementations might, for example, do "on demand" access checking - i.e. until you ask for the "Foo" role it doesn't know - it then finds out (by talking to a web-service, database, active-directory, etc) and caches the result for future access. This is useful when the list of potential roles is large, and the number of roles typically queried in reality is small.
You can also use a principal to store extra identity information that is only needed in certain contexts - for example, a security token. Callers might test the principal with as to see if it supports the extra data.
Using "principal" is useful because your logic processing code can talk about identity, without having to know whether this is winforms, ASP.NET, WCF, a windows service, etc - it is abstract. Additionally, some 3rd party code will also talk to the principal.
As another example - I wrote some example code here that shows how to use the principal to control access to winform controls via the designer (via an IExtenderProvider - which puts extra entries into the property grid in VS).
You can use GenericIdentity as a concrete implementation of Identity where you want to supply the details yourself, programmatically, about the current user. Pretty good if you have identified and authenticated the user yourself, through other channels.
GenericIdentity class can be used in conjunction with the GenericPrincipal class to create an authorization scheme that exists independent of a Windows domain.
GenericIdentity myIdentity = new GenericIdentity("MyUser");
Check out
http://msdn.microsoft.com/en-us/library/system.security.principal.genericidentity.aspx
You will find some examples up there. It represents a generic user.
Authentication and profile perissions.
GenericIdentity Class:-
The GenericIdentity class implements the IIdentity interface. It represents the identity of the user based on a custom authentication method defined by the application.
GenericPrincipal class:-
The GenericPrincipal class implements the IPrincipal interface. It represents users and roles that exist independent of Windows users and their roles. Essentially, the generic principal is a simple solution for application authentication and authorization.

Categories