用mvc來實現如下Cookie-Base的認證和受權的方式html
新建一個web MVC的項目web
在個人電腦的路徑:D:\MyDemos\jesseapi
Ctrl+鼠標右鍵打開 CMD窗體建立一個項目cookie
dotnet new mvc --name MvcCookieAuthSamplemvc
默認帶這Home的Controllerapp
新建AdminController,把HomeController的內容賦值過去,進行修改,只保留一個Index的Action就能夠了。url
views下面建立Admin文件夾在下面建立Index.cshtmlspa
賦值About.cshtml的內容進去簡單修改一下code
dotnet run 執行htm
打開地址訪問admin
https://localhost:5001/admin
在admin加上驗證
注意這裏的命名空間是:
using Microsoft.AspNetCore.Authorization;
引入Cookies的命名空間在VSCode中會報錯。注意這裏的命名空間的名稱
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies;
AddAuthentication裏面要傳一個Scheme
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme);
CookieAuthenticationDefaults.AuthenticationScheme其實是一個字符串的常量
這個常量實際上就是常量:Cookies
把Cookie添加進來。
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
而後咱們要在mvc以前,把這個middleware也添加進來。
不然咱們的認證受權是不會生效的
app.UseAuthentication();
dotnet run 運行程序
這個時候咱們打開地址:https://localhost:5001/admin/index
就會自動給咱們跳轉到:
https://localhost:5001/Account/Login?ReturnUrl=%2Fadmin%2Findex
也就是咱們如今無法訪問admin這個頁面了。
接下來咱們來模擬登陸的過程
Controllers下新建:
AccountController.cs
SignInAsync第二個參數需呀傳入CliamsPrincipal
Cliams在這個命名空間下面:
using System.Security.Claims;
新建Claim的List
var cliams=new List<Claim>{ new Claim(ClaimTypes.Name,"wjw"), new Claim(ClaimTypes.Role,"admin") };
基於Cliams新建了Identity。ClaimsIdentity的第二個參數必定要給個authenticationType,不然咱們的登錄就沒有辦法識別
在作一個LogOut的Action
修改成返回爲ok,這樣就是api了
dotnet watch run
咱們先訪問如下admin頁面 ,訪問不到
https://localhost:5001/admin
會自動跳轉到:
https://localhost:5001/Account/Login?ReturnUrl=%2Fadmin
咱們直接修改連接地址爲:
https://localhost:5001/Account/Login
去訪問,這樣就實現了登錄了。
而後咱們再次訪問admin頁面就能夠訪問到了
https://localhost:5001/admin
爲了防止和默認的跳轉的頁面的url相同了。咱們把Login修改成MakeLogin
咱們先訪問:退出
https://localhost:5001/Account/loginout
而後在訪問admin
https://localhost:5001/admin
這樣就訪問不到了。
會自動跳轉到:
https://localhost:5001/Account/Login?ReturnUrl=%2Fadmin
咱們訪問:執行登錄的操做
https://localhost:5001/Account/MakeLogin
會把咱們的cookie設置好
再次訪問admin的頁面,這樣就能成功訪問到了。
https://localhost:5001/Admin
退出的操做
https://localhost:5001/Account/Loginout
修改默認跳轉的頁面地址:
訪問:https://localhost:5001/admin
會自動跳轉到:這樣就實現了自動登錄
https://localhost:5001/Account/MakeLogin?ReturnUrl=%2Fadmin
咱們再次訪問admin就能夠成功登錄了。