.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);

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

相关推荐
吹牛不交税2 天前
.netcore项目部署在ubuntu22.04虚拟机的docker中的过程记录
docker·容器·.netcore
weixin_421994786 天前
基于 .NET 9.0 的高性能轻量级令牌桶限流服务
.net·.netcore·令牌桶
weixin_421994786 天前
MVC 模式初探
mvc·.net·.netcore
weixin_421994787 天前
互联网与 Web 应用简介
.net·.netcore
全栈小59 天前
【C#】合理使用DeepSeek相关AI应用为我们提供强有力的开发工具,在.net core 6.0框架下使用JsonNode动态解析json字符串,如何正确使用单问号和双问号做好空值处理
人工智能·c#·json·.netcore·deepseek
时光追逐者11 天前
C#/.NET/.NET Core优秀项目和框架2026年1月简报
c#·.net·.netcore
大尚来也13 天前
双库协同,各取所长:.NET Core 中 PostgreSQL 与 SQLite 的优雅融合实战
postgresql·sqlite·.netcore
吹牛不交税13 天前
admin.net-v2 框架使用笔记-netcore8.0/10.0版
vue.js·.netcore
张3蜂17 天前
java springboot2.0 api ;.netcore8 api ;python GunicornAPI ,哪种更强?请从多个维度,对比分析
java·python·.netcore
切糕师学AI17 天前
.NET Core Web 中的健康检查端点(Health Check Endpoint)
前端·kubernetes·.netcore