Asp.Net Core role system without Identity - c#

How can i add role system without identity? I need to member and admin roles.
Login code:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginDTO.StrUserID)
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(principal);
Startup.cs
services.AddAuthorization(opt =>
{
opt.AddPolicy("Admin", policy => policy.RequireClaim(ClaimTypes.Name));
});

How can i add role system without identity? I need to member and admin roles.
As far as I know, if you used asp.net core cookie authentication , there is no need to build a role system.
We could write the codes in your login logic to check the user role from database.
Then we could add role by adding the ClaimTypes.Role Claim. Then we could use [Authorize(Roles ="Admin")] attribute to let only admin role user access.
More details, you could refer to below codes:
//Here build the logic to get the user role from database, then create a new role claim to add the user role.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "TestA"),
new Claim(ClaimTypes.Role, "Admin"),
};
var userIdentity = new ClaimsIdentity(claims, "login");
ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
HttpContext.SignInAsync(principal);
On the controller:
[Authorize(Roles ="Admin")]
public class AdminController : Controller

Related

How include roleclaim to accesstoken?

I secure my API with identityserver4 and asp.net identity. The identity database has tables roles and roleclaims. For my security model I need roles with her roleclaim. I include role to access token, but I don't understand how to include roleclaim.
//Example of API with roles
new ApiResource("api1", "My API")
{
UserClaims = new []{ "name", "role" }
}
I answered here how to include roles in the access tokens. If you want to additionally include role claims, you will need to use RoleManager.
public async Task GetProfileDataAsync(ProfileDataRequestContext context)
{
context.IssuedClaims.AddRange(context.Subject.Claims);
var user = await _userManager.GetUserAsync(context.Subject);
var roles = await _userManager.GetRolesAsync(user);
foreach (var role in roles)
{
var roleClaims = await RoleManager.GetClaimsAsync(role);
context.IssuedClaims.Add(new Claim(JwtClaimTypes.Role, role)); //Adds "role" claim
context.IssuedClaims.AddRange(roleClaims); //Adds other role claims
}
}

Owin claims - Add multiple ClaimTypes.Role

I have an application in which users can be assigned the following roles:
SuperAdmin
Admin
User
One user may have assigned two or more roles, eg. both SuperAdmin and User. My application uses claims, and therefore i want to authenticate user roles through claims too. like:
[Authorize(Roles="Admin")]
Unfortunately, i dont know how i can add multiple roles to my ClaimTypes.Role. I have the following code:
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Role, "User", "Admin", "SuperAdmin")
},
"ApplicationCookie");
As you can see, i tried to add more roles for the sake of illustrating, but obviously its done in a wrong way, and therefore doesn't work.
Any help is therefore much appreciated.
A claims identity can have multiple claims with the same ClaimType. That will make it possible to use the HasClaim method for checking if a specific user role is present.
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name, name),
new Claim(ClaimTypes.Email, email),
new Claim(ClaimTypes.Role, "User"),
new Claim(ClaimTypes.Role, "Admin"),
new Claim(ClaimTypes.Role,"SuperAdmin")
},
"ApplicationCookie");
#Parameswar Rao explained well but in case of dynamic roles
For example a user object already has property role of type list like
then using localfunctions
ClaimsIdentity getClaimsIdentity()
{
return new ClaimsIdentity(
getClaims()
);
Claim[] getClaims()
{
List<Claim> claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, user.UserName));
foreach (var item in user.Roles)
{
claims.Add(new Claim(ClaimTypes.Role, item));
}
return claims.ToArray();
}
}
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = getClaimsIdentity()
}

Custom RoleProvider in ASP.NET Core with Identity?

In past MVC versions I was able to do
<roleManager enabled="true" defaultProvider="...." ...
in to the web.config to get a custom role provider, but that doesn't seem to be the case anymore.
Essentially what I want to do is:
The user logs in.
On success, get roles for user from external source.
Apply roles to user to be used in code.
Match user roles to roles in custom RoleProvider
How do I do this in ASP.NET Core?
If you're using simple cookie-based authentication instead of the Identity framework, you can add your roles as claims and they will be picked up by User.IsInRole(...), [Authorize(Roles = "...")], etc.
private async Task SignIn(string username)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, username)
};
// TODO: get roles from external source
claims.Add(new Claim(ClaimTypes.Role, "Admin"));
claims.Add(new Claim(ClaimTypes.Role, "Moderator"));
var identity = new ClaimsIdentity(
claims,
CookieAuthenticationDefaults.AuthenticationScheme,
ClaimTypes.Name,
ClaimTypes.Role
);
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(identity),
new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTime.UtcNow.AddMonths(1)
}
);
}

How to add claims during user registration

I'm using ASP.NET MVC 5 project with identity 2.1.0 and VS2013 U4. I want to add claims to user during registration in order to be stored in db. These claims represent user custom properties.
As I created a web page for administrator to create/edit/delete users, I'm still using create method from AccountController to create a user, but I don't want to login that user. How can I add those claims to the user ?
You probably already have a UserManager class. You can use that one to create users and to add claims.
As an example in a controller:
// gather some context stuff
var context = this.Request.GetContext();
// gather the user manager
var usermanager = context.Get<ApplicationUserManager>();
// add a country claim (given you have the userId)
usermanager.AddClaim("userid", new Claim(ClaimTypes.Country, "Germany"));
In order for this to work you need to implement your own UserManager and link it with the OWIN context (in the example it's ApplicationUserManager which basically is class ApplicationUserManager : UserManager<ApplicationUser> { } with only a small amount of configuration added). A bit of reading is available here: https://msdn.microsoft.com/en-us/library/dn613290%28v=vs.108%29.aspx
you can use Like
private void SignInAsync(User User)
{
var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, User.Employee.Name));
claims.Add(new Claim(ClaimTypes.Email, User.Employee.EmailId));
claims.Add(new Claim(ClaimTypes.Role, User.RoleId.ToString()));
var id = new ClaimsIdentity(claims,
DefaultAuthenticationTypes.ApplicationCookie);
var claimsPrincipal = new ClaimsPrincipal(id);
// Set current principal
Thread.CurrentPrincipal = claimsPrincipal;
var ctx = Request.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(id);
}
after login pass the User table value in this function
SignInAsync(result);
you can get clam value like
var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
// Get the claims values
string UserRoleValue = identity.Claims.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value).SingleOrDefault();
You can, in fact, create claims at the same time you create the user account.
Just add the claims to the user object before you call CreateAsync on the user manager.
var identityUser = new IdentityUser
{
UserName = username,
Email = email,
// etc...
Claims = { new IdentityUserClaim { ClaimType = "SomeClaimType", ClaimValue = "SomeClaimValue"} }
};
var identityResult = await _userManager.CreateAsync(identityUser, password);
This will create the user and associate the claims with the user as one logical operation with persistence.

OWIN/Identity Framework

I have a class library with a SignIn method with a lot of logic in order for a member to sign in. The problem that I am facing is that I add a claim of "Fullname" to the identity and it works fine, but as soon as the user log's off and logs in again the claim is gone.
If I inspect the users identity the claim is available on the second log in until the RedirectToAction method is hit, then all the custom claims are no longer in the users identity. This includes the Fullname and Role claims.
var roles = _dbsme.sp_GetAllRoles(user.Id);
ClaimsIdentity identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationProperties authenticationProperties1 = new AuthenticationProperties();
authenticationProperties1.IsPersistent = false;
AuthenticationProperties authenticationProperties2 = authenticationProperties1;
identity.AddClaim(new Claim("FullName", user.Firstname + " " + user.Surname));
foreach (string role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
AuthenticationManager.SignIn(authenticationProperties2, identity);
signInStatus = SignInStatus.Success;
You should be adding claims via the UserManager in order to have them persisted (if you use ASP.NET Identity 2 with EF).
userManager.AddClaim(userId, new Claim(claimType,claimValue));
Please note that if you add the claims on a user that is currently logged-in you need to sign that user in again (to put the new information in the cookie).

Categories