AdminController中添加引用:
using Microsoft.AspNetCore.Authorization;
Index添加[Authorize]权限要求:
[Authorize]public IActionResult Index(){ return View();}
StartUp.cs中添加引用:
using Microsoft.AspNetCore.Authentication;using Microsoft.AspNetCore.Authentication.Cookies;
StartUp.cs ConfigureServices中添加常量:
public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(); services.AddMvc();}
添加中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseAuthentication(); }
此时,访问Admin页面,自动跳转至Account/Login?ReturnUrl=%2FAdmin
添加AccountController.cs控制器,编写MakeLogin和Logout。此时访问Account/MakeLogin后,访问Admin能正常访问。
public class AccountController : Controller { public IActionResult MakeLogin() { var claims = new List{ new Claim(ClaimTypes.Name,"liumuu"), new Claim(ClaimTypes.Role,"admin") }; var claimIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimIdentity)); return Ok(); } public IActionResult Logout() { HttpContext.SignOutAsync(); return Ok(); } }
可自定义默认选项:
public void ConfigureServices(IServiceCollection services){ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; }); services.AddMvc();}
新建ViewModel:
public class RegisterViewModel { public string Email { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } }
public class LoginViewModel { [Required] [DataType(DataType.EmailAddress)] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } }
@model RegisterViewModel@{ ViewData["Title"] = "Register";}Register
@model LoginViewModel@{ ViewData["Title"] = "Login";}Login
创建Models:ApplicationUser.cs和ApplicationRole.cs:
public class ApplicationUser : IdentityUser { }
public class ApplicationRole : IdentityRole { }
数据连接:ApplicationDbContext.cs:
public class ApplicationDbContext : IdentityDbContext{ public ApplicationDbContext(DbContextOptions options) : base(options) { } }
appsettings.json中添加数据链接:
{ "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } }, "GetConnectionString": { "Default": "Data Source = .; Database = database; User ID = sa; Password = 123" }}
StartUp.cs中添加数据引用、密码设置等:
public void ConfigureServices(IServiceCollection services) { services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString("Default")); }); services.AddIdentity () .AddEntityFrameworkStores () .AddDefaultTokenProviders(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/Account/Login"; }); services.Configure (options => { options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; }); services.AddMvc(); }
编辑AccountController.cs:
private UserManager_userManager;private SignInManager _signInManager;public AccountController(UserManager userManager, SignInManager signInManager){ _userManager = userManager; _signInManager = signInManager;}
[HttpPost]public async TaskRegister(RegisterViewModel registerViewModel) { var identityUser = new ApplicationUser { Email = registerViewModel.Email, UserName = registerViewModel.Email, NormalizedUserName = registerViewModel.Email }; var identityResult = await _userManager.CreateAsync(identityUser, registerViewModel.Password); if (identityResult.Succeeded) { return RedirectToAction("Index", "Home"); } return View();}