首页 > Web开发 > 详细

.NET Core 3.0中的Cookie身份验证

时间:2020-05-13 09:23:45      阅读:103      评论:0      收藏:0      [点我收藏+]
原文:.NET Core 3.0中的Cookie身份验证

目录

介绍

先决条件

创建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:传递AuthenticationTypeclaim列表 
  4. ClaimsPrincipal:接受一组 ClaimsIdentity
  5. SignInAsync:传递ClaimsPrinciple给它作为参数,最后,此方法将在浏览器中创建一个cookie

Startup.cs文件的代码更改

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

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. services.AddAuthentication("CookieAuthentication")
  4. .AddCookie("CookieAuthentication", config =>
  5. {
  6. config.Cookie.Name = "UserLoginCookie";
  7. config.LoginPath = "/Login/UserLogin";
  8. });
  9. services.AddControllersWithViews();
  10. }

b、在Startup.cs Configure方法中添加UseAuthenticationUseAuthorization 扩展方法。

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

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

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

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.AspNetCore.HttpsPolicy;
  8. using Microsoft.Extensions.Configuration;
  9. using Microsoft.Extensions.DependencyInjection;
  10. using Microsoft.Extensions.Hosting;
  11. namespace CookieAuthenticationDemo
  12. {
  13. public class Startup
  14. {
  15. public Startup(IConfiguration configuration)
  16. {
  17. Configuration = configuration;
  18. }
  19. public IConfiguration Configuration { get; }
  20. // This method gets called by the runtime.
  21. // Use this method to add services to the container.
  22. public void ConfigureServices(IServiceCollection services)
  23. {
  24. services.AddAuthentication("CookieAuthentication")
  25. .AddCookie("CookieAuthentication", config =>
  26. {
  27. config.Cookie.Name = "UserLoginCookie";
  28. config.LoginPath = "/Login/UserLogin";
  29. });
  30. services.AddControllersWithViews();
  31. }
  32. // This method gets called by the runtime.
  33. // Use this method to configure the HTTP request pipeline.
  34. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  35. {
  36. if (env.IsDevelopment())
  37. {
  38. app.UseDeveloperExceptionPage();
  39. }
  40. else
  41. {
  42. app.UseExceptionHandler("/Home/Error");
  43. // The default HSTS value is 30 days.
  44. // You may want to change this for production scenarios,
  45. // see https://aka.ms/aspnetcore-hsts.
  46. app.UseHsts();
  47. }
  48. app.UseHttpsRedirection();
  49. app.UseStaticFiles();
  50. app.UseRouting();
  51. // who are you?
  52. app.UseAuthentication();
  53. // are you allowed?
  54. app.UseAuthorization();
  55. app.UseEndpoints(endpoints =>
  56. {
  57. endpoints.MapControllerRoute(
  58. name: "default",
  59. pattern: "{controller=Home}/{action=Index}/{id?}");
  60. });
  61. }
  62. }
  63. }

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

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

  1. using System.Collections.Generic;
  2. namespace CookieAuthenticationDemo.Models
  3. {
  4. public class Users
  5. {
  6. public int Id { get; set; }
  7. public string UserName { get; set; }
  8. public string Name { get; set; }
  9. public string EmailId { get; set; }
  10. public string Password { get; set; }
  11. public IEnumerable<Users> GetUsers()
  12. {
  13. return new List<Users>() { new Users
  14. { Id = 101, UserName = "anet", Name = "Anet",
  15. EmailId = "anet@test.com", Password = "anet123" } };
  16. }
  17. }
  18. }

使用新的操作方法更新HomeController

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

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

  1. using CookieAuthenticationDemo.Models;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. namespace CookieAuthenticationDemo.Controllers
  5. {
  6. public class HomeController : Controller
  7. {
  8. public IActionResult Index()
  9. {
  10. return View();
  11. }
  12. [Authorize]
  13. public ActionResult Users()
  14. {
  15. var uses = new Users();
  16. return View(uses.GetUsers());
  17. }
  18. }
  19. }

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

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

技术分享图片

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

  1. @model IEnumerable<CookieAuthenticationDemo.Models.Users>
  2. @{
  3. ViewData["Title"] = "Users";
  4. }
  5. <h1>Users</h1>
  6. <table class="table">
  7. <thead>
  8. <tr>
  9. <th>
  10. @Html.DisplayNameFor(model => model.Id)
  11. </th>
  12. <th>
  13. @Html.DisplayNameFor(model => model.UserName)
  14. </th>
  15. <th>
  16. @Html.DisplayNameFor(model => model.Name)
  17. </th>
  18. <th>
  19. @Html.DisplayNameFor(model => model.EmailId)
  20. </th>
  21. <th></th>
  22. </tr>
  23. </thead>
  24. <tbody>
  25. @foreach (var item in Model) {
  26. <tr>
  27. <td>
  28. @Html.DisplayFor(modelItem => item.Id)
  29. </td>
  30. <td>
  31. @Html.DisplayFor(modelItem => item.UserName)
  32. </td>
  33. <td>
  34. @Html.DisplayFor(modelItem => item.Name)
  35. </td>
  36. <td>
  37. @Html.DisplayFor(modelItem => item.EmailId)
  38. </td>
  39. </tr>
  40. }
  41. </tbody>
  42. </table>

用名称登录添加新控制器

A、右键单击controllers文件夹

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

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

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

  1. using CookieAuthenticationDemo.Models;
  2. using Microsoft.AspNetCore.Authentication;
  3. using Microsoft.AspNetCore.Mvc;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Security.Claims;
  7. namespace CookieAuthenticationDemo.Controllers
  8. {
  9. public class LoginController : Controller
  10. {
  11. [HttpGet]
  12. public ActionResult UserLogin()
  13. {
  14. return View();
  15. }
  16. [HttpPost]
  17. public ActionResult UserLogin([Bind] Users user)
  18. {
  19. // username = anet
  20. var users = new Users();
  21. var allUsers = users.GetUsers().FirstOrDefault();
  22. if (users.GetUsers().Any(u => u.UserName == user.UserName ))
  23. {
  24. var userClaims = new List<Claim>()
  25. {
  26. new Claim(ClaimTypes.Name, user.UserName),
  27. new Claim(ClaimTypes.Email, "anet@test.com"),
  28. };
  29. var grandmaIdentity =
  30. new ClaimsIdentity(userClaims, "User Identity");
  31. var userPrincipal = new ClaimsPrincipal(new[] { grandmaIdentity });
  32. HttpContext.SignInAsync(userPrincipal);
  33. return RedirectToAction("Index", "Home");
  34. }
  35. return View(user);
  36. }
  37. }
  38. }

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

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

UserLogin.cshtml代码:

  1. @model CookieAuthenticationDemo.Models.Users
  2. @{
  3. ViewData["Title"] = "User Login";
  4. }
  5. <hr />
  6. <div class="row">
  7. <div class="col-md-4">
  8. <form asp-action="UserLogin">
  9. <h2>User Login</h2>
  10. <div asp-validation-summary="ModelOnly" class="text-danger"></div>
  11. <div class="form-group">
  12. <label asp-for="UserName" class="control-label"></label>
  13. <input asp-for="UserName" class="form-control" />
  14. <span asp-validation-for="UserName" class="text-danger"></span>
  15. </div>
  16. <div class="form-group">
  17. <label asp-for="Password" class="control-label"></label>
  18. <input type="password" asp-for="Password"
  19. class="form-control" />
  20. <span asp-validation-for="Password" class="text-danger"></span>
  21. </div>
  22. <div class="form-group">
  23. <input type="submit" value="Login"
  24. class="btn btn-default btn-primary" />
  25. </div>
  26. </form>
  27. </div>
  28. </div>

更新_Layout.cshtml页面

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

_Layout.cshtml代码如下:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport"
  6. content="width=device-width, initial-scale=1.0" />
  7. <title>@ViewData["Title"] - CookieAuthenticationDemo</title>
  8. <link rel="stylesheet"
  9. href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
  10. <link rel="stylesheet" href="~/css/site.css" />
  11. </head>
  12. <body>
  13. <header>
  14. <nav class="navbar navbar-expand-sm
  15. navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
  16. <div class="container">
  17. <a class="navbar-brand" asp-area=""
  18. asp-controller="Home"
  19. asp-action="Index">CookieAuthenticationDemo</a>
  20. <button class="navbar-toggler" type="button"
  21. data-toggle="collapse"
  22. data-target=".navbar-collapse"
  23. aria-controls="navbarSupportedContent"
  24. aria-expanded="false" aria-label="Toggle navigation">
  25. <span class="navbar-toggler-icon"></span>
  26. </button>
  27. <div class="navbar-collapse
  28. collapse d-sm-inline-flex flex-sm-row-reverse">
  29. <ul class="navbar-nav flex-grow-1">
  30. <li class="nav-item">
  31. <a class="nav-link text-dark"
  32. asp-area="" asp-controller="Home"
  33. asp-action="Index">Home</a>
  34. </li>
  35. <li class="nav-item">
  36. <a class="nav-link text-dark"
  37. asp-area="" asp-controller="Home"
  38. asp-action="Users">Users</a>
  39. </li>
  40. </ul>
  41. </div>
  42. </div>
  43. </nav>
  44. </header>
  45. <div class="container">
  46. <main role="main" class="pb-3">
  47. @RenderBody()
  48. </main>
  49. </div>
  50. <footer class="border-top footer text-muted">
  51. <div class="container">
  52. ? 2020 - CookieAuthenticationDemo - <a asp-area=""
  53. asp-controller="Home" asp-action="Privacy">Privacy</a>
  54. </div>
  55. </footer>
  56. <script src="~/lib/jquery/dist/jquery.min.js"></script>
  57. <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
  58. <script src="~/js/site.js" asp-append-version="true"></script>
  59. @RenderSection("Scripts", required: false)
  60. </body>
  61. </html>

运行您的应用程序

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

技术分享图片

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

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

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

技术分享图片

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

技术分享图片

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

技术分享图片

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

总结

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

 

.NET Core 3.0中的Cookie身份验证

原文:https://www.cnblogs.com/lonelyxmas/p/12879969.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!