思路:在startup中的configservice设置cookie鉴权,在config方法中use鉴权,然后添加两个页面,一个登录页面,一个用户信息页面(登陆后才能访问,没有登录则返回失败或者需要登录)
1:添加一个cookie鉴权的方法
1 public class CookieAuthConfig 2 { 3 public static void ConfigureServices(IServiceCollection services) 4 { 5 //使用cookie鉴权 6 services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) 7 .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => 8 { 9 options.LoginPath = "/Auth/Login"; 10 options.AccessDeniedPath = "/Auth/Login"; 11 }); 12 } 13 14 public static void Configure(IApplicationBuilder app, IWebHostEnvironment env) 15 { 16 17 app.UseAuthentication(); 18 } 19 }
2:在startup.cs中的配置和使用方法中引用cookie鉴权的方法
1 public void ConfigureServices(IServiceCollection services) 2 { 3 CookieAuthConfig.ConfigureServices(services); 4 5 } 6 7 public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 8 { 9 CookieAuthConfig.ConfigureServices(app,env); 10 }
3:controll里面的设置:
1 public class AuthController : Controller 2 { 3 4 ///表示要授权才能访问对于的info页面 5 6 [Authorize] 7 public IActionResult Info() 8 { 9 10 return View(); 11 } 12 13 14 /// <summary> 15 /// 使用cookie方式存储用户信息 16 /// </summary> 17 /// <param name="username"></param> 18 /// <param name="password"></param> 19 /// <returns></returns> 20 public async Task<IActionResult> Login(string username, string password) 21 { 22 if ("liping".Equals(username) && "123456".Equals(password)) 23 { 24 ClaimsIdentity identity = new ClaimsIdentity("lipingtest"); 25 identity.AddClaim(new Claim(ClaimTypes.Name, username)); 26 identity.AddClaim(new Claim(ClaimTypes.Email, "[email protected]")); 27 identity.AddClaim(new Claim(ClaimTypes.Role, "Admin")); 28 identity.AddClaim(new Claim(ClaimTypes.Country, "China")); 29 30 //写入cookie 31 await base.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, 32 new ClaimsPrincipal(identity), 33 new AuthenticationProperties 34 { 35 ExpiresUtc = System.DateTimeOffset.UtcNow.AddMinutes(30), 36 }); 37 38 39 return new JsonResult(new 40 { 41 Status = true, 42 MSg = "登录成功" 43 }); 44 } 45 else 46 { 47 await System.Threading.Tasks.Task.CompletedTask; 48 return new JsonResult(new 49 { 50 Status = false, 51 MSg = "登录失败" 52 }); 53 54 } 55 56 57 } 58 59 60 61 public async Task<IActionResult> Logout() 62 { 63 //退出 64 await base.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); 65 66 return new JsonResult(new 67 { 68 Status = true, 69 MSg = "退出成功" 70 }); 71 } 72 73 74 75 }
标签:core,return,public,cookie,new,net,鉴权,identity From: https://www.cnblogs.com/hanliping/p/18369548