准備工作
新建MVC項目,然后用VSCode打開
dotnet new mvc --name MvcCookieAuthSample
在Controllers文件夾下新建AdminController.cs

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using MvcCookieAuthSample.Models; namespace MvcCookieAuthSample.Controllers { public class AdminController : Controller { public IActionResult Index() { return View(); } } }
在Views文件夾下新建Admin文件夾,並在Admin文件夾下新建Index.cshtml

@{ ViewData["Title"] = "Admin"; } <h2>@ViewData["Title"]</h2> <p>Admin Page</p>
運行結果:
Cookie-based認證實現
在AdminController中添加引用
using Microsoft.AspNetCore.Authorization;
然后我們可以給AdminController添加 [Authorize] 標簽
接下來我們需要把認證和授權引用進來,我們使用的是cookie的認證方式,所以在Startup.cs中添加認證的引用。
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies;
然后在Startup方法中進行cookie的依賴注入
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options=>{//自定義登陸地址,不配置的話則默認為http://localhost:5000/Account/Login options.LoginPath="/Account/MyLogin"; });
然后我們要在Configure方法中把cookie中間件也添加進來,否則認證授權是不會生效的
app.UseAuthentication();
這時候我們再運行一下:
發現已經自動跳轉到登陸地址了。
模擬登陸
我們暫時不做登陸的,只是模擬一下登陸,首先我們創建一個AccountController.cs
然后添加引用
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication.Cookies; using System.Security.Claims;
添加兩個API用於登陸和登出
//登陸 public IActionResult MakeLogin() { var claims=new List<Claim>(){ new Claim(ClaimTypes.Name,"wangyuting"), new Claim(ClaimTypes.Role,"admin") }; //必須要加CookieAuthenticationDefaults.AuthenticationScheme,不然無法解析 var claimsIdentity=new ClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme); HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,new ClaimsPrincipal(claimsIdentity)); return Ok(); } //登出 public IActionResult Logout() { HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Ok(); }
訪問http://localhost:5000/admin會跳轉到http://localhost:5000/Account/MyLogin?ReturnUrl=%2Fadmin頁面
然后我們訪問http://localhost:5000/Account/MakeLogin模擬登陸,然后再訪問http://localhost:5000/admin
最后訪問http://localhost:5000/Account/logout登出,然后再訪問http://localhost:5000/admin發現又跳轉到我們自定義的登陸頁面。