.Net Core — Cookie 身份验证

目录

[步骤 1:创建登录视图模型](#步骤 1:创建登录视图模型)

[步骤 2:创建视图](#步骤 2:创建视图)

[步骤 3:更新 _Layout(用于导航栏)](#步骤 3:更新 _Layout(用于导航栏))

[步骤 4:更新控制器](#步骤 4:更新控制器)

[步骤 5:更新 Program.cs](#步骤 5:更新 Program.cs)

[补充说明:在其他课程中使用 cookie](#补充说明:在其他课程中使用 cookie)


如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

在本教程中,我们将学习如何使用 cookie 在我们的应用程序中进行身份验证。

步骤 1:创建登录视图模型

using System.ComponentModel.DataAnnotations;

namespace BlogApp.Models {

public class LoginViewModel {

Required

EmailAddress

Display(Name = "Email" )

public string? Email { get ; set ; }

Required

DataType(DataType.Password)

Display(Name = "Password" )

public string? Password { get ; set ; }

}

}

步骤 2:创建视图

@model LoginViewModel

<div class="row">

<div class="col-12">

<div class="bg-white p-4">

<h1>Login</h1>

<form asp-controller="User" asp-action="Login" method="post">

<div asp-validation-summary="ModelOnly" class="text-danger"></div>

<div class="mb-3">

<label asp-for="Email" class="form-label"></label>

<input asp-for="Email" class="form-control">

<span asp-validation-for="Email" class="text-danger"></span>

</div>

<div class="mb-3">

<label asp-for="Password" class="form-label"></label>

<input asp-for="Password" class="form-control">

<span asp-validation-for="Password" class="text-danger"></span>

</div>

<button type="submit" class="btn btn-primary">Login</button>

</form>

</div>

</div>

</div>

步骤 3:更新 _Layout(用于导航栏)

<ul class="navbar-nav ms-auto">

@if(User.Identity!.IsAuthenticated){

<li class="nav-item">

<a href="#" class="nav-link">@User.Identity.Name</a>

</li>

<li class="nav-item">

<a href="/logout" class="nav-link">Logout</a>

</li>

}

else{

<li class="nav-item">

<a href="/login" class="nav-link">Login</a>

</li>

}

</ul>

步骤 4:更新控制器

HttpPost

public async Task<IActionResult> Login(LoginViewModel model){

try{

if(!ModelState.IsValid){

ModelState.AddModelError("", "Invalid Credentials");

return View(model);

}

var user = _userRepository.Users.FirstOrDefault(o => o.Email == model.Email && o.Password == model.Password);

if(user == null){

ModelState.AddModelError("", "Invalid Credentials");

return View(model);

}

// COOKIE

var claims = new List<Claim>();

claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()));

claims.Add(new Claim(ClaimTypes.Name, user.UserName ?? ""));

claims.Add(new Claim(ClaimTypes.GivenName, user.Name ?? ""));

claims.Add(new Claim(ClaimTypes.Role, "User"));

var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); // delete old cookie if exist

await HttpContext.SignInAsync( // add new cookie

CookieAuthenticationDefaults.AuthenticationScheme,

new ClaimsPrincipal(claimsIdentity),

new AuthenticationProperties{IsPersistent = true} // remember me

);

return RedirectToAction("Index", "Post");

}

catch(Exception e){

ModelState.AddModelError("", e.Message);

return View(model);

}

}

步骤 5:更新 Program.cs

// Cookie Authentication

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

...

// Authentication & Authorization

app.UseRouting();

app.UseAuthentication();

app.UseAuthorization();

var claims = User.Claims;

...

var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

var userName = User.FindFirstValue(ClaimTypes.Name);

如果您喜欢此文章,请收藏、点赞、评论,谢谢,祝您快乐每一天。

相关推荐
van久1 天前
Day19:Service 业务层(企业架构核心)
.netcore
武藤一雄1 天前
WPF中逻辑树(Logical Tree)与可视化树(Visual Tree)到底是什么
microsoft·c#·.net·wpf·.netcore
武藤一雄5 天前
19个核心算法(C#版)
数据结构·windows·算法·c#·排序算法·.net·.netcore
van久6 天前
Day17:EF Core 增删改 + 事务
.netcore
MoFe17 天前
【.net core】【watercloud】处理rabbitmq类初始化时获取系统已注入的数据库连接问题(调用已注入服务)
数据库·rabbitmq·.netcore
PyHaVolask10 天前
Python 爬虫进阶:反爬识别机制与登录态维持
python爬虫·cookie·session·requests·反爬机制·登录态
MoFe111 天前
【.net core】【RabbitMq】rabbitmq在.net core中的简单使用
分布式·rabbitmq·.netcore
van久12 天前
Day15:EF Core 入门 + CodeFirst(就业核心版)
.netcore
叫我黎大侠12 天前
.NET 实战:调用千问视觉模型实现 OCR(车票识别完整教程)
阿里云·ai·c#·ocr·asp.net·.net·.netcore
van久12 天前
Day15-4:【日志】中间件和过滤器 的对比选择
.netcore