ASP.NET Core Authentication系列(二)实现认证、登录和注销
前言
在上一篇文章介绍ASP.NET Core Authentication的三个重要概念,分别是Claim, ClaimsIdentity, ClaimsPrincipal,以及claims-base authentication是怎么工作的。
这篇文章来介绍一下如何基于claims-base authentication来实现认证、登录和注销功能的。源代码从这里下载。
认证票据
认证是一个确定发送请求的访问者身份的过程,与认证相关的还有另外两个基本操作:登录和注销。
ASP.NET Core应用的认证实现在一个名为AuthenticationMiddleware的中间件中,该中间件在处理分发给它的请求时会按照指定的 认证方案(Authentication Scheme) 从请求中提取能够验证用户真实身份的数据,我们一般将该数据称为 安全令牌(Security Token) 。ASP.NET Core应用下的安全令牌被称为 认证票据(Authentication Ticket) ,所以ASP.NET Core应用采用基于票据的认证方式。
AuthenticationMiddleware中间件的整个认证过程涉及下图的三种操作:认证票据的颁发、检验和撤销。

ASP.NET Core应用的认证系统旨在构建一个标准的模型来完成针对请求的认证以及与之相关的登录和注销操作。接下来我们就通过一个简单的实例来演示如何在一个ASP.NET Core应用中实现认证、登录和注销的功能。
基于Cookie的认证
大多数Web应用采用的是Cookie来保存认证票据,因此我们采用基于Cookie的认证方案。
配置
在Startup.ConfigureServices方法里,添加AuthenticationMiddleware中间件:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
然后在Startup.Configure方法里,调用UseAuthentication和UseAuthorization来设置HttpContext.User属性以及允许请求经过AuthenticationMiddleware,并且要在UseEndpoints之前调用:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
// ...
}
登录
接下来实现登录方法,常见是使用“用户名+密码”,这里使用一个静态字典来模拟用户表。
public class AccountController : Controller
{
// ....
private static Dictionary<string, string> _accounts;
static AccountController()
{
_accounts = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
_accounts.Add("Foo", "password");
_accounts.Add("Bar", "password");
_accounts.Add("Baz", "password");
}
[HttpGet]
public IActionResult Login()
{
LoginModel model = new LoginModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> Login(LoginModel model)
{
if (_accounts.TryGetValue(model.UserName, out var pwd) && pwd == model.Password)
{
var claimsIdentity = new ClaimsIdentity(
new Claim[] { new Claim(ClaimTypes.Name, model.UserName) }, "Basic");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
return Redirect("/");
}
else
{
model.ErrorMessage = "Invalid user name or password!";
return await Task.Run(() => View(model));
}
}
// ....
}
这段代码的关键在于下面三行代码:
- 创建ClaimType为Name,值为用户名的Claim。
- 创建ClaimsIdentity,注意AuthorizeType="Basic"。
- 创建ClaimsPrincipal。
- 调用HttpContext.SignInAsync登录,其中认证方案为CookieAuthenticationDefaults.AuthenticationScheme,与配置时一致。
var claimsIdentity = new ClaimsIdentity(
new Claim[] { new Claim(ClaimTypes.Name, model.UserName) }, "Basic");
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
认证
需要授权访问的功能要验证登录状态,如果没有登录则不允许访问,使用方法很简单,只需要在Action上加上特性[Authorize]:
[Authorize]
public IActionResult Index()
{
return View();
}
未登录会跳转到/Account/Login(默认设置,可修改),避免未授权访问。
注销
用户注释,即将具有认证票据的Cookie设置为过期,直接调用HttpContext.SignOutAsync,注意认证方案要与配置和登录的一致:CookieAuthenticationDefaults.AuthenticationScheme
public class AccountController : Controller
{
// ....
public async Task<IActionResult> Logout()
{
_logger.LogInformation("User {Name} logged out at {Time}.",
User.Identity.Name, DateTime.UtcNow);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
// ....
}
参考资料
- Exploring the cookie authentication middleware in ASP.NET Core
- 用最简单的方式在ASP.NET Core应用中实现认证、登录和注销
- Use cookie authentication without ASP.NET Core Identity
ASP.NET Core Authentication系列(二)实现认证、登录和注销的更多相关文章
- ASP.NET Core Authentication系列(四)基于Cookie实现多应用间单点登录(SSO)
前言 本系列前三篇文章分别从ASP.NET Core认证的三个重要概念,到如何实现最简单的登录.注销和认证,再到如何配置Cookie 选项,来介绍如何使用ASP.NET Core认证.感兴趣的可以了解 ...
- ASP.NET Core Authentication系列(一)理解Claim, ClaimsIdentity, ClaimsPrincipal
前言 首先我们来看一下在ASP.NET时代,Authentication是如何使用的.下面介绍的是System.Web.Security.FormsAuthentication: // 登录 Syst ...
- ASP.NET Core部署系列二:发布到CentOS上
前言: 在上一节中,通过一系列的步骤,已经将项目部署到IIS上,虽然遇到了一些问题,但最终解决并成功运行了.而在这一节中,将尝试通过linux系统的环境下,部署项目,实现Net Core跨平台的亮点. ...
- ASP.NET Core Authentication系列(三)Cookie选项
前言 在本系列第一篇文章介绍了ASP.NET时代如何认证,并且介绍了如何通过web.config文件来配置Auth Cookie的选项. 第二篇文章介绍了如何使用Cookie认证,本文介绍几个常见的C ...
- 理解ASP.NET Core - 基于JwtBearer的身份认证(Authentication)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 在开始之前,如果你还不了解基于Cookie的身份认证,那么建议你先阅读<基于Cookie ...
- 理解ASP.NET Core - 基于Cookie的身份认证(Authentication)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 概述 通常,身份认证(Authentication)和授权(Authorization)都会放 ...
- 跟我学: 使用 fireasy 搭建 asp.net core 项目系列之二 —— 准备
==== 目录 ==== 跟我学: 使用 fireasy 搭建 asp.net core 项目系列之一 —— 开篇 跟我学: 使用 fireasy 搭建 asp.net core 项目系列之二 —— ...
- 【ASP.NET Core】运行原理[3]:认证
本节将分析Authentication 源代码参考.NET Core 2.0.0 HttpAbstractions Security 目录 认证 AddAuthentication IAuthenti ...
- 关于ASP.Net Core Web及API身份认证的解决方案
6月15日,在端午节前的最后一个工作日,想起有段日子没有写过文章了,倒有些荒疏了.今借夏日蒸蒸之气,偷得浮生半日悠闲.闲话就说到这里吧,提前祝大家端午愉快(屈原听了该不高兴了:))!.NetCore自 ...
随机推荐
- 你在开发过程中使用Git Rebase还是Git Merge?
摘要:在git里面经常的一个争论是到底用rebase还是用merge? 1. 痛苦吗?代码历史中的迷失羔羊 我们先来看一个真实的代码提交历史图形化截图: 图片源自 https://storage.kr ...
- 分页查询对象Page
1 public class Page { 2 //当前页码 3 private Integer pageNo = 1; 4 //每页显示条数 5 private Integer pageSize = ...
- 【CF1425A】 Arena of Greed题解
原题链接 简要翻译: Mr.Chanek与另一个人玩一个取硬币游戏,他先手.玩家在自己的回合内可以取走硬币堆中的一个.如果硬币堆里有偶数个硬币,玩家也可以选择取走硬币总数的一半.两名玩家都是绝对聪明的 ...
- Python-类属性查询协议-__getattr__ __getattribute__
__getattr__ 查找不到类属性的时候调用 class BeiMenChuiXue: def __init__(self, name): self.name = name def __getat ...
- Focal loss论文解析
Focal loss是目标检测领域的一篇十分经典的论文,它通过改造损失函数提升了一阶段目标检测的性能,背后关于类别不平衡的学习的思想值得我们深入地去探索和学习.正负样本失衡不仅仅在目标检测算法中会出现 ...
- 《C++ primer plus》第3章练习题
注:有的题设条件自己改动了一下,比如英寸英尺改成米和厘米,部分题目自己加了点额外要求. 1.要求用户输入身高(m),用下划线提示用户输入,将身高转化成"米"加"厘米&qu ...
- 玩转 SpringBoot2.x 之整合 thumbnailator 图片处理
1.序 在实际项目中,有时为了响应速度,难免会对一些高清图片进行一些处理,比如图片压缩之类的,而其中压缩可能就是最为常见的.最近,阿淼就被要求实现这个功能,原因是客户那边嫌速度过慢.借此机会,阿淼今儿 ...
- 达梦产品技术支持培训-day2-DM8常用SQL
(本文只作为随笔或个人笔记,非官方文档,请勿作他用,谢谢) DM8数据库的SQL兼容性很高,和Oracle差距不大,以下是个人认为比较关键的部分. 1.关键动词 create --新建 drop -- ...
- ASP。NET MVC (NetCore 2.0)用于处理实体框架、DbContexts和对象的通用控制器和视图
下载source - 1.5 MB 介绍 本文的源代码已更新到NetCore 2.0 ASP.净MVC项目. 当我们开始开发一个ASP.在Microsoft Visual Studio中,我们发现通过 ...
- 二进制部署Redis-5.07
Redis简介 Redis是一个开源(BSD许可),内存存储的数据结构服务器,可用作数据库,高速缓存和消息队列代理. 它支持字符串.哈希表.列表.集合.有序集合,位图,hyperloglogs等数据类 ...