上一篇提到 [ASP.NET MVC][Owin] 用最简单 Cookie 认证方式,
这次改换 ASP.NET Core 的 Microsoft.AspNetCore.Authentication.Cookies 练习最简单的 Cookie 认证与授权,
- 在 project.json 的 dependencies 加入
"Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"
并记得每次加完要进行套件还原(Visual Studio 会自动套件还原),自己写命令则到项目目录下,用 Command Line 输入 dotnet restore 手动还原
- 在 Startup 类的 Configuration 加上使用 CookieAuthentication 的方式
app.UseCookieAuthentication(new CookieAuthenticationOptions() { AuthenticationScheme = "MyCookieMiddlewareInstance", LoginPath = new PathString("/Test/Index/"), AutomaticAuthenticate = true, AutomaticChallenge = true });
CookieAuthenticationOption 的属性可参考官网说明,在最下方会提供参考连结
-
最简单的登入范例,很重要的是 ClaimsIdentity 构造函数第二个参数是 authenticationType 一定要填,不然验证没有作用 Http Response Hreaders 也不会有 Set-Cookie
public async Task
Login() { var claims = new List () { new Claim(ClaimTypes.Name, "Herry"), new Claim(ClaimTypes.Role, "Users") }; var claimsIdentity = new ClaimsIdentity(claims, "myTest"); var principal = new ClaimsPrincipal(claimsIdentity); await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal); return Ok(); } - 想授权哪个 Controller 或 Action 的方式一样没变,例如
[Authorize] public IActionResult Index() { return View(); }
参考文章
Using Cookie Middleware without ASP.NET Core Identity
原文:大专栏 [ASP.NET Core] 最简单 Cookie 认证与授权的范例