您当前的位置: 首页 >  .net

寒冰屋

暂无认证

  • 0浏览

    0关注

    2286博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

.NET Core 3.0中的Cookie身份验证

寒冰屋 发布时间:2020-02-07 13:25:39 ,浏览量:0

目录

介绍

先决条件

创建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 Core和ASP.NET Core版本。然后,从列表中选择Web应用程序(模型-视图-控制器)选项,然后按创建按钮创建一个项目。(ps:我用的core3.1,最好包配置https去掉试试,否则后期登录打开显示405错误)

现在,我们的项目将以.NET Core环境的基本结构打开。您可以在解决方案资源管理器中观察到,其中将包含Controllers,Models和Views文件夹,其中包含“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 GetUsers()
        {
            return new List() { 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

@{
    ViewData["Title"] = "Users";
}

Users

    
        
            
                @Html.DisplayNameFor(model => model.Id)
            
            
                @Html.DisplayNameFor(model => model.UserName)
            
            
                @Html.DisplayNameFor(model => model.Name)
            
            
                @Html.DisplayNameFor(model => model.EmailId)
            
            
        
    
    
@foreach (var item in Model) {
        
            
                @Html.DisplayFor(modelItem => item.Id)
            
            
                @Html.DisplayFor(modelItem => item.UserName)
            
            
                @Html.DisplayFor(modelItem => item.Name)
            
            
                @Html.DisplayFor(modelItem => item.EmailId)
            
        
}
    
用名称登录添加新控制器

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()
                {
                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";  
	}  
	  
	  
	
User Login
更新_Layout.cshtml页面

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

_Layout.cshtml的代码如下:




    
    
    @ViewData["Title"] - CookieAuthenticationDemo
    
    


    
        
            
CookieAuthenticationDemo
  • Home
  • Users
@RenderBody()
© 2020 - CookieAuthenticationDemo - Privacy
@RenderSection("Scripts", required: false)
运行您的应用程序

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

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

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

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

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

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

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

总结

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

 

关注
打赏
1665926880
查看更多评论
立即登录/注册

微信扫码登录

0.0501s