任务34:Cookie-based认证明现

任务34:Cookie-based认证明现

 用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;

 

 

 

引入认证和受权Startup.cs内

引入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就能够成功登录了。

相关文章
相关标签/搜索