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)
}
);
}
Related
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
How do I add the new claims in such a way that they persist through requests until the cookie expires?
I am using OWIN middle ware, on-premises authentication to authenticate the users logging into the system.
The sign-in part is successful, and I added Roles to the user claims provided by the ws-federation to help authorize the user for certain action methods.
At the time of login, in the controller, I have written the following to add the roles:
string[] roles = { "Role1", "Role2" };
var identity = new ClaimsIdentity(User.Identity);
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
var authenticationManager = HttpContext.GetOwinContext().Authentication;
authenticationManager.AuthenticationResponseGrant = new AuthenticationResponseGrant
(new ClaimsPrincipal(identity),
new AuthenticationProperties { IsPersistent = true });
But when I check the claims at the next request, I don't see the role claims.
After successful authentication I believe you added custom claims (normally to some event handler once successfully authenticated). Now in order to persist that information in subsequent request you need to use CookieAuthentication middle ware before your authentication owin in pipeline.
How it works :
Upon successful authentication first time and addition of custom claims, claims will be transformed into sort of auth cookie and sent back to client. Subsequent request will carry this auth cookie. CookieAuthentication middle ware on finding auth cookie will set your Thread.CurrentPriciple with claims obtained from cookie.
During first time request when cookie middle ware does see any auth cookie, it passes request to next middle ware in pipe line (Authentication owin in your case) to challenge user for login.
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationType = "Cookies",
AuthenticationMode= AuthenticationMode.Active,
CookieName="XXXXX",
CookieDomain= _cookiedomain,
/* you can go with default cookie encryption also */
TicketDataFormat = new TicketDataFormat(_x509DataProtector),
SlidingExpiration = true,
CookieSecure = CookieSecureOption.Always,
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = _clientID,
Authority = _authority,
RedirectUri = _redirectUri,
UseTokenLifetime = false,
Notifications = new OpenIdConnectAuthenticationNotifications
{
SecurityTokenValidated = SecurityTokenValidated,
AuthenticationFailed = (context) =>
{
/* your logic to handle failure*/
}
},
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
ValidIssuers = _validIssuers,
ValidateIssuer = _isValidIssuers,
}
});
EDIT: (Additional information)
Pretty much the exact code as above works for ws federation also, with the same logic and everything.
SecurityTokenValidated = notification =>
{
ClaimsIdentity identity = notification.AuthenticationTicket.Identity;
string[] roles = { "Role1", "Role2" };
foreach (var role in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
return Task.FromResult(0);
}
You need to use the same AuthenticationType that you used in Startup.ConfigureAuth. For example:
In Startup.ConfigureAuth:
app.UseCookieAuthentication(new CookieAuthenticationOptions {
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
//....
});
And in your login code (provided in the question):
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);
Or make sure that the User.Identity has the same AuthenticationType, and you're good to use that like you did:
var identity = new ClaimsIdentity(User.Identity);
Now the important part is that for the login, you should add the claims before singing the use in, not after. Something like this:
HttpContext.GetOwinContext().Authentication.SignIn(identity);
You can add the claims after signing in, but you will be modifying the cookie right after it is created, which is not efficient. If in some other code you need to modify the claims, then you can use something similar to your code, but you must get the context from Current:
HttpContext.Current.GetOwinContext().Authentication.AuthenticationResponseGrant =
new AuthenticationResponseGrant(new ClaimsPrincipal(identity),
new AuthenticationProperties { IsPersistent = true });
So you can fix your code by simply adding Current like above, but that's not efficient for the login code and it is better to pass the claims to the SignIn function.
you can do the following in WEB API C # (SOAP),(STORED PROCEDURES)
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
LoginModel model = new LoginModel();
//validate user credentials and obtain user roles (return List Roles)
//validar las credenciales de usuario y obtener roles de usuario
var user = model.User = _serviceUsuario.ObtenerUsuario(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "El nombre de usuario o la contraseƱa no son correctos.cod 01");
return;
}
var stringRoles = user.Roles.Replace(" ", "");//It depends on how you bring them from your DB
string[] roles = stringRoles.Split(',');//It depends on how you bring them from your DB
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach(var Rol in roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, Rol));
}
identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
identity.AddClaim(new Claim(ClaimTypes.Email, user.Correo));
identity.AddClaim(new Claim(ClaimTypes.MobilePhone, user.Celular));
identity.AddClaim(new Claim("FullName", user.FullName));//new ClaimTypes
identity.AddClaim(new Claim("Empresa", user.Empresa));//new ClaimTypes
identity.AddClaim(new Claim("ConnectionStringsName", user.ConnectionStringsName));//new ClaimTypes
//add user information for the client
var properties = new AuthenticationProperties(new Dictionary<string, string>
{
{ "userName",user.NombreUsuario },
{ "FullName",user.FullName },
{ "EmpresaName",user.Empresa }
});
//end
var ticket = new AuthenticationTicket(identity, properties);
context.Validated(ticket);
}
Im trying to setup Token authentication with cookie authentication on same time in my application.
I created a MVC project in asp.net core 2.0, with individual user accounts to auth. Setup roles to the users too.
If i follow this tutorial of Shawn Wildermuth Two-AuthorizationSchemes-in-ASP-NET-Core-2
Everything works fine to get the Token of the registered user. But if i use the Role attribute on authorize [Authorize(Roles="Admin")] im getting a 403 response.
I think that is because the Token is not receiving the Role on auth.
How to setup this? Is any way to pass the Roles on the Token process?
To generate the token he is using this piece of code:
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> GenerateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) {
var user = await _userManager.FindByEmailAsync(model.Email);
if (user != null)
{
var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
if (result.Succeeded)
{
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_config["Tokens:Issuer"],
_config["Tokens:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
} }
return BadRequest("Could not create token"); }
You guys have any idea?
Thanks
If you add the following using and code, that should help.
using System.Security.Claims;
...
var userRoles = await _userManager.GetRolesAsync(user);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
}.Union(userRoles.Select(m => new Claim(ClaimTypes.Role, m)));
You can see the Union that adds the roles in with the type of ClaimTypes.Role, this will enable them to be used in the AuthorizeAttribute
HTH
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()
}
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).