目录

介绍

先决条件

创建Web应用程序的步骤

集成Cookie身份验证

Startup.cs文件的代码更改

将User.cs文件添加到Model文件夹

使用新的操作方法更新HomeController

用名称登录添加新控制器

更新_Layout.cshtml页面

运行您的应用程序

总结


  • 下载演示

介绍

身份验证是根据系统或用户的身份确定或给予其个人访问权限的过程。.NET Core中有多个选项可以进行身份​​验证。本文演示了如何在.NET Core 3.0中添加基于cookie的身份验证。

使用.NET Core 3.0,您可以直接使用基于cookie的身份验证,而无需添加新的其他NuGet程序包。

先决条件

  • 从此处安装.NET Core 3.0.0或更高版本的SDK 。从此处安装最新版本的Visual Studio 2019社区版。

创建Web应用程序的步骤

1、转到Visual Studio 2019,然后从选项列表中选择创建新项目选项:

2、选择后,将打开一个新窗口以选择项目模板。

3、选择“ASP.NET Core Web应用程序”,然后单击“下一步按钮。

4、将打开一个新屏幕,以配置新项目。根据您的要求提供项目名称位置解决方案名称。按创建按钮。

5、单击“创建按钮后,将打开一个新屏幕以配置与项目相关的信息,例如您要为Web应用程序创建哪种环境?.NET Framework.NET Core从下拉列表中选择.NET CoreASP.NET Core版本。然后,从列表中选择Web应用程序(模型-视图-控制器)选项,然后按创建按钮创建一个项目。(ps:我用的core3.1,最好包配置https去掉试试,否则后期登录打开显示405错误)

现在,我们的项目将以.NET Core环境的基本结构打开。您可以在解决方案资源管理器中观察到,其中将包含ControllersModelsViews文件夹,其中包含“Startup.cs”以及其他文件,如下图所示:

6、运行您的应用程序,以检查创建的Web应用程序是否运行正常。默认情况下,它将打开您的项目的主页(Home控制器的Index页)。

集成Cookie身份验证

  1. [Authorize]:特性有助于验证用户是否访问控制器(用户信息)
  2. Claim:包含与用户相关的信息,这些信息将存储到Cookie中
  3. ClaimsIdentity:传递AuthenticationType和claim列表
  4. ClaimsPrincipal:接受一组 ClaimsIdentity
  5. SignInAsync:传递ClaimsPrinciple给它作为参数,最后,此方法将在浏览器中创建一个cookie

Startup.cs文件的代码更改

a、打开“Startup.cs”文件,然后将AddAuthentication 服务添加到ConfigureServices 方法中。提供登录用户的登录路径,以检查/验证用户是否有效。

public void ConfigureServices(IServiceCollection services){services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", config =>{config.Cookie.Name = "UserLoginCookie";config.LoginPath = "/Login/UserLogin";});services.AddControllersWithViews();}

b、在“Startup.cs”的 Configure方法中添加UseAuthentication和UseAuthorization 扩展方法。

UseAuthentication:帮助我们检查“您是谁?”

UseAuthorization:有助于检查“是否允许您访问信息?”

c、Startup.cs文件中的完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;namespace CookieAuthenticationDemo
{public class Startup{public Startup(IConfiguration configuration){Configuration = configuration;}public IConfiguration Configuration { get; }// This method gets called by the runtime.// Use this method to add services to the container.public void ConfigureServices(IServiceCollection services){services.AddAuthentication("CookieAuthentication").AddCookie("CookieAuthentication", config =>{config.Cookie.Name = "UserLoginCookie";config.LoginPath = "/Login/UserLogin";});services.AddControllersWithViews();}// This method gets called by the runtime.// Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");// The default HSTS value is 30 days.// You may want to change this for production scenarios,// see https://aka.ms/aspnetcore-hsts.app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();// who are you?app.UseAuthentication();// are you allowed?app.UseAuthorization();app.UseEndpoints(endpoints =>{endpoints.MapControllerRoute(name: "default",pattern: "{controller=Home}/{action=Index}/{id?}");});}}
}

将User.cs文件添加到Model文件夹

使用名称Users将新类添加到Models文件夹中,并将以下代码行放入其中:

using System.Collections.Generic;namespace CookieAuthenticationDemo.Models
{public class Users{public int Id { get; set; }public string UserName { get; set; }public string Name { get; set; }public string EmailId { get; set; }public string Password { get; set; }public IEnumerable<Users> GetUsers(){return new List<Users>() { new Users{ Id = 101, UserName = "anet", Name = "Anet",EmailId = "anet@test.com", Password = "anet123" } };}}
}

使用新的操作方法更新HomeController

HomeController 是Visual Studio在创建新项目时创建的默认控制器。

a、向HomeController中添加新的操作方法以获取具有Authorize特性的用户列表。

using CookieAuthenticationDemo.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;namespace CookieAuthenticationDemo.Controllers
{public class HomeController : Controller{public IActionResult Index(){return View();}[Authorize]public ActionResult Users(){var uses = new Users();return View(uses.GetUsers());}}
}

b、为用户添加视图:(ps:我创建的demo直接在控制器中添加的)

  1. 转到Views文件夹,然后选择Home文件夹
  2. 右键单击Home文件夹以选择添加选项,然后选择视图
  3. 将打开一个窗口弹出窗口以添加视图。
  4. 提供“视图名称为“User,选择“模板为“,选择“使用布局页面,然后按“添加按钮。新的Users.cshtml文件将创建到Home文件夹中。请参考下图添加视图:

将以下代码行放入其中以显示用户列表:

@model IEnumerable<CookieAuthenticationDemo.Models.Users>@{ViewData["Title"] = "Users";
}<h1>Users</h1>
<table class="table"><thead><tr><th>@Html.DisplayNameFor(model => model.Id)</th><th>@Html.DisplayNameFor(model => model.UserName)</th><th>@Html.DisplayNameFor(model => model.Name)</th><th>@Html.DisplayNameFor(model => model.EmailId)</th><th></th></tr></thead><tbody>
@foreach (var item in Model) {<tr><td>@Html.DisplayFor(modelItem => item.Id)</td><td>@Html.DisplayFor(modelItem => item.UserName)</td><td>@Html.DisplayFor(modelItem => item.Name)</td><td>@Html.DisplayFor(modelItem => item.EmailId)</td></tr>
}</tbody>
</table>

用名称登录添加新控制器

A、右键单击controllers文件夹

B、选择添加,然后选择控制器,然后选择MVC空控制器,然后单击添加按钮。

C、将名称为Login的控制器添加为“LoginController ”

D、将以下代码添加到该控制器中:

using CookieAuthenticationDemo.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;namespace CookieAuthenticationDemo.Controllers
{public class LoginController : Controller{[HttpGet]public ActionResult UserLogin(){return View();}[HttpPost]public ActionResult UserLogin([Bind] Users user){// username = anetvar users = new Users();var allUsers = users.GetUsers().FirstOrDefault();if (users.GetUsers().Any(u => u.UserName == user.UserName )){var userClaims = new List<Claim>(){new Claim(ClaimTypes.Name, user.UserName),new Claim(ClaimTypes.Email, "anet@test.com"),};var grandmaIdentity =new ClaimsIdentity(userClaims, "User Identity");var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });HttpContext.SignInAsync(userPrincipal);return RedirectToAction("Index", "Home");}return View(user);}}
}

E、添加UserLogin.cshtml(UserLogin view)页面:(ps:我创建的demo直接在控制器中添加的)

  1. 将新文件夹添加到名称为User的Views文件夹中。
  2. 添加UserLogin到“User文件夹中,并将以下代码行添加到其中,以进行用户登录:

UserLogin.cshtml代码:

@model CookieAuthenticationDemo.Models.Users  @{  ViewData["Title"] = "User Login";  }  <hr />  <div class="row">  <div class="col-md-4">  <form asp-action="UserLogin">  <h2>User Login</h2>  <div asp-validation-summary="ModelOnly" class="text-danger"></div>  <div class="form-group">  <label asp-for="UserName" class="control-label"></label>  <input asp-for="UserName" class="form-control" />  <span asp-validation-for="UserName" class="text-danger"></span>  </div>  <div class="form-group">  <label asp-for="Password" class="control-label"></label>  <input type="password" asp-for="Password" class="form-control" />  <span asp-validation-for="Password" class="text-danger"></span>  </div>  <div class="form-group">  <input type="submit" value="Login" class="btn btn-default btn-primary" />  </div>  </form>  </div>  </div>

更新_Layout.cshtml页面

更新_Layout.cshtml页面以添加新的标签/超链接以获取用户列表。

_Layout.cshtml代码如下:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8" /><meta name="viewport"content="width=device-width, initial-scale=1.0" /><title>@ViewData["Title"] - CookieAuthenticationDemo</title><link rel="stylesheet"href="~/lib/bootstrap/dist/css/bootstrap.min.css" /><link rel="stylesheet" href="~/css/site.css" />
</head>
<body><header><nav class="navbar navbar-expand-smnavbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"><div class="container"><a class="navbar-brand" asp-area=""asp-controller="Home"asp-action="Index">CookieAuthenticationDemo</a><button class="navbar-toggler" type="button"data-toggle="collapse"data-target=".navbar-collapse"aria-controls="navbarSupportedContent"aria-expanded="false" aria-label="Toggle navigation"><span class="navbar-toggler-icon"></span></button><div class="navbar-collapsecollapse d-sm-inline-flex flex-sm-row-reverse"><ul class="navbar-nav flex-grow-1"><li class="nav-item"><a class="nav-link text-dark"asp-area="" asp-controller="Home"asp-action="Index">Home</a></li><li class="nav-item"><a class="nav-link text-dark"asp-area="" asp-controller="Home"asp-action="Users">Users</a></li></ul></div></div></nav></header><div class="container"><main role="main" class="pb-3">@RenderBody()</main></div><footer class="border-top footer text-muted"><div class="container">© 2020 - CookieAuthenticationDemo - <a asp-area=""asp-controller="Home" asp-action="Privacy">Privacy</a></div></footer><script src="~/lib/jquery/dist/jquery.min.js"></script><script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script><script src="~/js/site.js" asp-append-version="true"></script>@RenderSection("Scripts", required: false)
</body>
</html>

运行您的应用程序

成功运行应用程序后,应用程序的输出应类似于以下屏幕:

单击“用户选项卡以获取用户列表,它将打开一个登录页面以登录用户。

问题:为什么会要求登录?

:[Authorize]特性限制访问未经授权的请求的数据/信息,并重定向到登录页面以检查用户是否有效。在本例中,我们已在HomeController的“用户”操作方法上添加了此属性。(ps:因为用的https,所以这个登录打不开,去掉UserLogin上的HttpPost特性后可用看到,显示优点怪异)

提供用户名和密码进行登录。登录后,它将在浏览器中创建一个cookie,如下所示:

再次单击“用户选项卡,现在您无需查找登录屏幕即可找到用户列表的最终结果。

要测试基于cookie的身份验证,可以从浏览器中删除创建的cookie,然后单击“用户选项卡。它将要求再次登录。

总结

在本文中,我讨论了如何在.NET Core 3.0中添加基于cookie的身份验证。我们还创建了一个用户登录表单,以将用户登录到我们的应用程序以访问有用的信息。请找到附加的代码以更好地理解。

.NET Core 3.0中的Cookie身份验证相关推荐

  1. asp.net core中使用cookie身份验证

    背景 ASP.NET Core Identity 是一个完整的全功能身份验证提供程序,用于创建和维护登录名. 但是, cookie 不能使用基于的身份验证提供程序 ASP.NET Core Ident ...

  2. 使用内存数据库的.NET Core 3.0中基于身份(Identity-Based)的身份验证

    目录 介绍 背景 先决条件 创建Web应用程序的步骤 第1步 第2步 第3步 第4步 第5步 第6步 运行您的应用程序 总结 下载源9.5 MB 介绍 身份验证是根据系统或用户的身份确定或给予其个人访 ...

  3. 在ASP.NET Core 2.0中创建Web API

    目录 介绍 先决条件 软件 技能 使用代码 第01步 - 创建项目 第02步 - 安装Nuget包 步骤03 - 添加模型 步骤04 - 添加控制器 步骤05 - 设置依赖注入 步骤06 - 运行We ...

  4. 避免在 ASP.NET Core 3.0 中为启动类注入服务

    本篇是如何升级到ASP.NET Core 3.0系列文章的第二篇. Part 1 - 将.NET Standard 2.0 类库转换为.NET Core 3.0 类库 Part 2 - IHostin ...

  5. .NET Core 3.0中的新功能和增强功能

    目录 介绍 主要变化 Windows桌面支持 本机可执行文件 JSON API 更好的垃​​圾收集器 性能改进 Docker增强 ARM64支持 物联网支持 密码学 与.NET Core 2.2的AP ...

  6. ASP.NET Core 3.0中使用动态控制器路由

    原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...

  7. .NET Core 3.0中的数据库驱动框架System.Data

    虽然没有得到很多关注,但System.Data对于.NET中任何关系型数据库的访问都至关重要.因为其前身是ActiveX Data Objects,所以它也被称为ADO.NET.System.Data ...

  8. .NET Core 3.0 中的新变化

    译者:楚人Leo 译文:http://www.cnblogs.com/leolion/p/10585834.html 原文:https://msdn.microsoft.com/en-us/magaz ...

  9. IHostingEnvironment VS IHostEnvironment - .NET Core 3.0中的废弃类型

    原文:https://andrewlock.net/ihostingenvironment-vs-ihost-environment-obsolete-types-in-net-core-3/ 作者: ...

最新文章

  1. 遂宁2017届零诊16题(仅想说明网传答案的不正确)
  2. 自动化运维之PSSH
  3. ffmpeg为AVPacket添加解码头信息
  4. 建模步骤_【设计课堂】游戏手柄建模,看这14个步骤图就够了!
  5. 通过configSource提高web.config配置灵活性
  6. Python《使用Selenium实现自动化操作》
  7. linux内存管理详解,Linux内存管理图文讲解.pdf
  8. 比较下OceanBase的选举协议和Raft的选举协议的区别
  9. jpa 定义中间表实体_JPA系列之-带你快速掌握JPA
  10. excel导入成html页面上的表格
  11. Hadoop中Yarnrunner里面submit Job以及AM生成 至Job处理过程源码解析
  12. Linux 命令之 nohup 后台运行程序,tail 实时查看文件内容
  13. 关于mongodb的学习与探索二
  14. 高程(三)--- Date
  15. 2021世界量子计算机排名,2021 QS世界大学学科排名如期出炉啦!
  16. Eclipse启动时f出现ail to create Java Virtual Machine问题的解决
  17. 整数补码加减法运算法则
  18. 笔记本系统转移到固态硬盘
  19. Infor SCE 小计
  20. VoLTE用户码号和卡

热门文章

  1. python读yaml的库_Python读取YAML文件过程详解
  2. c语言400行小游戏,400行代码编C语言控制台界版2048游戏,编写疯子一样的C语言代码...
  3. ubuntu 9.04 更新源_ubuntu更换中国源
  4. python书籍pdf文档密码-Python玩转PDF的各种骚操作
  5. 做春节海报没有思路?传统节日年味十足,PSD分层模板,给你灵感!
  6. 设计师交流分享社区|灵感并非凭空得来,积累在集设网
  7. 商务建筑空间场景合成海报
  8. python 线程通信 会涉及到拷贝吗_Python如何实现线程间通信
  9. CUDA C程序中的函数类型
  10. Linux内核 eBPF基础:BCC (BPF Compiler Collection)