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自 ...
随机推荐
- 编辑 编译 乱码 透彻 讲解 keil vscode notepad++
1. 2.此时VSCODE内的改文件是乱码现象,进行如下操作,选择 通过编码重新打开, 选择GB 2312即可.(GB2312是兼容ANSI编码的) 详细解释一下: KEIL内是ANSI编码,VSCO ...
- 022 01 Android 零基础入门 01 Java基础语法 03 Java运算符 02 算术运算符
022 01 Android 零基础入门 01 Java基础语法 03 Java运算符 02 算术运算符 本文知识点:Java中的算术运算符 算术运算符介绍 算术运算符代码示例 注意字符串连接问题和整 ...
- 006 01 Android 零基础入门 01 Java基础语法 01 Java初识 06 使用Eclipse开发Java程序
006 01 Android 零基础入门 01 Java基础语法 01 Java初识 06 使用Eclipse开发Java程序 Eclipse下创建程序 创建程序分为以下几个步骤: 1.首先是创建一个 ...
- Jupyter 绘图怎么显示中文
1. 简单加2行代码即可. import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = [u'SimHei'] plt.rcPa ...
- python中的filter、map、reduce、apply用法总结
1. filter 功能: filter的功能是过滤掉序列中不符合函数条件的元素,当序列中要删减的元素可以用某些函数描述时,就应该想起filter函数. 调用: filter(function,seq ...
- 谈谈InnoDB中的B+树索引
索引类似于书的目录,他是帮助我们从大量数据中快速定位某一条或者某个范围数据的一种数据结构.有序数组,搜索树都可以被用作索引.MySQL中有三大索引,分别是B+树索引.Hash索引.全文索引.B+树索引 ...
- Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(一)
标题 Spring Boot+Spring Security+JWT 实现 RESTful Api 认证(一) 技术 Spring Boot 2.Spring Security 5.JWT 运行环境 ...
- 2019年CSP-J初赛试题(普及组)试题详解
https://www.jianshu.com/p/9e58f455c1ee https://blog.csdn.net/weixin_39104847/article/details/1086711 ...
- 题解:POI2012 Salaries
题解:POI2012 Salaries Description The Byteotian Software Corporation (BSC) has \(n\) employees. In BSC ...
- 树状数组(BIT)—— 一篇就够了
树状数组(BIT)-- 一篇就够了 前言.内容梗概 本文旨在讲解: 树状数组的原理(起源,原理,模板代码与需要注意的一些知识点) 树状数组的优势,缺点,与比较(eg:线段树) 树状数组的经典例题及其技 ...