目录
身份验证是根据系统或用户的身份确定或给予其个人访问权限的过程。.NET Core中有多个选项可以进行身份??验证。本文演示了如何在.NET Core 3.0中添加基于cookie的身份验证。
使用.NET Core 3.0,您可以直接使用基于cookie的身份验证,而无需添加新的其他NuGet程序包。
1、转到Visual Studio 2019,然后从选项列表中选择创建新项目选项:
2、选择后,将打开一个新窗口以选择项目模板。
3、选择“ASP.NET Core Web应用程序”,然后单击“下一步”按钮。
4、将打开一个新屏幕,以配置新项目。根据您的要求提供项目名称,位置,解决方案名称。按创建按钮。
5、单击“创建”按钮后,将打开一个新屏幕以配置与项目相关的信息,例如您要为Web应用程序创建哪种环境?.NET Framework或.NET Core。从下拉列表中选择.NET Core和ASP.NET Core版本。然后,从列表中选择Web应用程序(模型-视图-控制器)选项,然后按创建按钮创建一个项目。(ps:我用的core3.1,最好包配置https去掉试试,否则后期登录打开显示405错误)
现在,我们的项目将以.NET Core环境的基本结构打开。您可以在解决方案资源管理器中观察到,其中将包含Controllers,Models和Views文件夹,其中包含“Startup.cs”以及其他文件,如下图所示:
6、运行您的应用程序,以检查创建的Web应用程序是否运行正常。默认情况下,它将打开您的项目的主页(Home控制器的Index页)。
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?}");
- });
- }
- }
- }
使用名称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 是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直接在控制器中添加的)
将以下代码行放入其中以显示用户列表:
- @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 = anet
- var 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直接在控制器中添加的)
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的代码如下:
- <!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-sm
- navbar-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-collapse
- collapse 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的身份验证。我们还创建了一个用户登录表单,以将用户登录到我们的应用程序以访问有用的信息。请找到附加的代码以更好地理解。
原文:https://www.cnblogs.com/lonelyxmas/p/12879969.html