.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 方法中。提供登录用户的登录路径,以检查/验证用户是否有效。

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方法中添加UseAuthenticationUseAuthorization 扩展方法。

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 = "[email protected]", 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 = 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, "[email protected]"),
                 };

                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. 将新文件夹添加到名称为UserViews文件夹中。
  2. 添加UserLoginUser文件夹中,并将以下代码行添加到其中,以进行用户登录:

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-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的身份验证。我们还创建了一个用户登录表单,以将用户登录到我们的应用程序以访问有用的信息。请找到附加的代码以更好地理解。

 

发布了69 篇原创文章 · 获赞 133 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/mzl87/article/details/104130747