在我的项目中,使用没有Asp.net身份的身份 我正在做登录部分, 我想使用[Authorize(Role =“ ...”)]但我不知道该怎么做。
请帮助我使用它
StartUp.cs:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.ExpireTimeSpan = TimeSpan.FromMinutes(5000);
});
登录操作
if (ModelState.IsValid)
{
User user = new User();
user = _iuser.LoginUser(login.Mobile, login.Password);
if (user != null)
{
if (user.IsActive)
{
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),
new Claim(ClaimTypes.Name,user.Mobile)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
var properties = new AuthenticationProperties()
{
IsPersistent = login.IsRemember
};
HttpContext.SignInAsync(principal, properties);
return RedirectToAction("Index", "Profile");
}
else
{
return RedirectToAction(nameof(Active));
}
用户类别:
public class User
{
[Key]
public int Id { get; set; }
public int RoleId { get; set; }
public string Mobile { get; set; }
public string Password { get; set; }
public string Code { get; set; }
public bool IsActive { get; set; }
[ForeignKey("RoleId")]
public virtual Role Role { get; set; }
}
角色类别:
public class Role
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
ApplicationDbContext:
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
}
提示: 我正在使用ASP.NET CORE 2.2和Entity Frame Work Core 2.2
答案 0 :(得分:0)