[英].Net Core 2 JWT, Angular 2 Authorization through roles does not work
[英]JWT authorization with roles in Identity Core
我無法理解Identity Core
Roles
我的AccountController
如下所示,我在GenerateJWTToken
方法的聲明中添加了Roles
:
[HttpPost("Login")]
public async Task<object> Login([FromBody] LoginBindingModel model)
{
var result = await this.signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);
if (result.Succeeded)
{
var appUser = this.userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);
return await GenerateJwtToken(model.UserName, appUser);
}
throw new ApplicationException("INVALID_LOGIN_ATTEMPT");
}
[HttpPost("Register")]
public async Task<object> Register([FromBody] RegistrationBindingModel model)
{
var user = new ApplicationUser
{
UserName = model.UserName,
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName
};
var result = await this.userManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await this.signInManager.SignInAsync(user, false);
return await this.GenerateJwtToken(model.UserName, user);
}
throw new ApplicationException("UNKNOWN_ERROR");
}
private async Task<object> GenerateJwtToken(string userName, IdentityUser user)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, userName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(ClaimTypes.NameIdentifier, user.Id),
new Claim(ClaimTypes.Role, Role.Viewer.ToString()),
new Claim(ClaimTypes.Role, Role.Developer.ToString()),
new Claim(ClaimTypes.Role, Role.Manager.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.configuration["JwtKey"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.Now.AddDays(Convert.ToDouble(this.configuration["JwtExpireDays"]));
var token = new JwtSecurityToken(
this.configuration["JwtIssuer"],
this.configuration["JwtIssuer"],
claims,
expires: expires,
signingCredentials: creds);
return new JwtSecurityTokenHandler().WriteToken(token);
}
通過此代碼,我的令牌可以與[Authorize]
控制器的屬性完美配合。
我的問題是,在哪個步驟role
向我的注冊user
添加role
以使用(例如) [Authorize("Admin")]
? 如何將role
保存到數據庫?
[Route("api/[controller]")]
[Authorize] //in this form it works ok, but how to add roles to it with JWT Token?
//how to register user to role and get this role to JWT Token?
[ApiController]
public class DefaultController : ControllerBase
我的ApplicationUser
:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Roles
枚舉:
public enum Role
{
Viewer,
Developer,
Manager
}
如何將有關用戶角色的信息保存到身份數據庫,並在登錄時如何使該角色正常工作的[Authorize]
屬性?
編輯:
我想要做的是將Roles
存儲在用戶的枚舉中。 我想將用戶注冊為Developer
, Manager
等。我相信我可以通過ApplicationUser
並添加Role
屬性,但是從中我無法通過屬性[Authorization(role)]
獲得授權
您無需使用IdentityUser和身份數據庫,而使用的是JWT。 創建具有定義的Roles
屬性的User
模型,然后簡單地將其持久保存在數據庫中。 喜歡:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Role Role { get; set; }
}
public enum Role
{
Viewer,
Developer,
Manager
}
令牌:
var user = // ...
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(your_seccret_key);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.FirstName),
new Claim(ClaimTypes.Name, user.LastName),
new Claim(ClaimTypes.Role, user.Role)
}),
Expires = DateTime.UtcNow.AddDays(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
user.Token = tokenHandler.WriteToken(token);
控制器方法:
[Authorize(Roles = Role.Developer)]
[HttpGet("GetSomethongForAuthorizedOnly")]
public async Task<object> GetSomething()
{
// .... todo
}
您可以將內置的角色管理與ASP.NET Identity結合使用。 由於您使用的是ASP.NET Core 2.1,因此您可以首先參考以下鏈接來啟用身份系統中的角色:
https://stackoverflow.com/a/54069826/5751404
啟用角色后,您可以注冊角色/用戶,然后向用戶添加角色,例如:
private async Task CreateUserRoles()
{
IdentityResult roleResult;
//Adding Admin Role
var roleCheck = await _roleManager.RoleExistsAsync("Admin");
if (!roleCheck)
{
IdentityRole adminRole = new IdentityRole("Admin");
//create the roles and seed them to the database
roleResult = await _roleManager.CreateAsync(adminRole);
_roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "edit.post")).Wait();
_roleManager.AddClaimAsync(adminRole, new Claim(ClaimTypes.AuthorizationDecision, "delete.post")).Wait();
ApplicationUser user = new ApplicationUser {
UserName = "YourEmail", Email = "YourEmail",
};
_userManager.CreateAsync(user, "YourPassword").Wait();
await _userManager.AddToRoleAsync(user, "Admin");
}
}
這樣,當該用戶登錄到您的應用程序時,您可以在ClaimsPrincipal中找到role
聲明,並且可以與帶有角色的Authorize
屬性一起使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.