配置

在 Startup.ConfigureServices 方法中,创建具有 AddAuthentication 和 AddCookie 方法的身份验证中间件服务:

services.AddAuthentication(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(); options.LoginPath = "/Account/Login";
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
});

AuthenticationScheme 传递到 AddAuthentication 设置应用程序的默认身份验证方案。 如果有多个 cookie 身份验证实例,并且你想要使用特定方案进行授权,AuthenticationScheme 会很有用。 将 AuthenticationScheme 设置为CookieAuthenticationDefaults。 AuthenticationScheme为方案提供值 "cookie"。 可以提供任何用于区分方案的字符串值。
应用的身份验证方案不同于应用的 cookie 身份验证方案。 如果未向 AddCookie提供 cookie 身份验证方案,则使用 CookieAuthenticationDefaults.AuthenticationScheme ("Cookie")。
默认情况下,身份验证 cookie 的 IsEssential 属性设置为 true。 当站点访问者未同意数据收集时,允许使用身份验证 cookie。

在 Startup.Configure中,调用 UseAuthentication 和 UseAuthorization 设置 HttpContext.User 属性,并为请求运行授权中间件。 调用 UseEndpoints之前调用 UseAuthentication 和 UseAuthorization 方法:

app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
  endpoints.MapControllers();
  endpoints.MapRazorPages();
});

登录

若要创建保存用户信息的 cookie,请构造一个 ClaimsPrincipal。 将对用户信息进行序列化并将其存储在 cookie 中。
使用任何所需的 Claim创建 ClaimsIdentity,并调用 SignInAsync 以登录用户:

var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.Email),
new Claim("FullName", user.FullName),
new Claim(ClaimTypes.Role, "Administrator"),
}; var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme); var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed. //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie. //IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based. //IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued. //RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
}; await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);

SignInAsync 创建加密的 cookie,并将其添加到当前响应中。 如果未指定 AuthenticationScheme,则使用默认方案。
ASP.NET Core 的数据保护系统用于加密。 对于托管在多台计算机上的应用程序、跨应用程序或使用 web 场进行负载平衡,请将数据保护配置为使用相同的密钥环和应用程序标识符。

注销

若要注销当前用户并删除其 cookie,请调用 SignOutAsync:

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

如果 CookieAuthenticationDefaults.AuthenticationScheme (或 "Cookie")不用作方案(例如 "ContosoCookie"),请提供配置身份验证提供程序时所使用的方案。 否则,将使用默认方案。

asp.net core中使用cookie身份验证的更多相关文章

  1. ASP.NET CORE中使用Cookie身份认证

    大家在使用ASP.NET的时候一定都用过FormsAuthentication做登录用户的身份认证,FormsAuthentication的核心就是Cookie,ASP.NET会将用户名存储在Cook ...

  2. 在ASP.NET Core 中使用Cookie中间件

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  3. 在ASP.NET Core 中使用Cookie中间件 (.net core 1.x适用)

    在ASP.NET Core 中使用Cookie中间件 ASP.NET Core 提供了Cookie中间件来序列化用户主题到一个加密的Cookie中并且在后来的请求中校验这个Cookie,再现用户并且分 ...

  4. asp.net core 3.1多种身份验证方案,cookie和jwt混合认证授权

    开发了一个公司内部系统,使用asp.net core 3.1.在开发用户认证授权使用的是简单的cookie认证方式,然后开发好了要写几个接口给其它系统调用数据.并且只是几个简单的接口不准备再重新部署一 ...

  5. 坎坷路:ASP.NET Core 1.0 Identity 身份验证(中集)

    上一篇:<坎坷路:ASP.NET 5 Identity 身份验证(上集)> ASP.NET Core 1.0 什么鬼?它是 ASP.NET vNext,也是 ASP.NET 5,以后也可能 ...

  6. ASP.NET Core 项目简单实现身份验证及鉴权

    ASP.NET Core 身份验证及鉴权 目录 项目准备 身份验证 定义基本类型和接口 编写验证处理器 实现用户身份验证 权限鉴定 思路 编写过滤器类及相关接口 实现属性注入 实现用户权限鉴定 测试 ...

  7. 在asp.net core中使用cookie认证

    以admin控制器为要认证的控制器举例 1.对控制器设置权限特性 //a 认证命名空间 using Microsoft.AspNetCore.Authorization; using Microsof ...

  8. 在 ASP.NET Core 中使用 FluentValidation 进行验证

    目录 从 NuGet 安装 FluentValidation 争对 Resource类 建立 FluentValidation 在Startup中对写好的验证进行注册 从 NuGet 安装 Fluen ...

  9. 从零搭建一个IdentityServer——聊聊Asp.net core中的身份验证与授权

    OpenIDConnect是一个身份验证服务,而Oauth2.0是一个授权框架,在前面几篇文章里通过IdentityServer4实现了基于Oauth2.0的客户端证书(Client_Credenti ...

随机推荐

  1. MVC WebApi 返回字符串

    [HttpGet] public HttpResponseMessage GetWebConfigValue(string key) { var response = Request.CreateRe ...

  2. PAT(甲级)2019年春季考试

    7-1 Sexy Primes 判断素数 一个点没过17/20分 错因:输出i-6写成了输出i,当时写的很乱,可以参考其他人的写法 #include<bits/stdc++.h> usin ...

  3. TC297B - 外设头文件解析(以IO为例)

    打开例程,目录树下的Includes中包含了各个片上资源对应的头文件,这些头文件定义了相应外设的寄存器地址(寄存器是内置于各个 IP 外设中,是一种用于配置外设功能的存储器,就是一种内存,并且有相对应 ...

  4. AutoLayout的那些事儿

    转自:http://www.cocoachina.com/ios/20160530/16522.html 本文投稿文章,作者:MangoMade(简书) AutoLayout非常强大也非常易用,可读性 ...

  5. yarn 与 npm 比较

    一.首先需要了解的命令 npm install === yarn —— install 安装是默认行为. npm install taco --save === yarn add taco —— ta ...

  6. Flask蓝图遇到的问题

    欢迎加入python学习交流群 667279387 最近在使用flask开发一个业余学习项目,由于之前都是"小打小闹",整个程序都是放在一个文件夹里面的,也没有注意这个问题.这次项 ...

  7. 2019CCPC秦皇岛 F Forest Program

    队友过的:https://blog.csdn.net/liufengwei1/article/details/101632506 Forest Program Time Limit: 2000/100 ...

  8. LightOJ1199 Partition Game

    Alice and Bob are playing a strange game. The rules of the game are: Initially there are n piles. A ...

  9. 2017 CCPC秦皇岛 H题 Prime set

    Given an array of  integers , we say a set  is a prime set of the given array, if  and  is prime. Ba ...

  10. CodeForces-Round235D

      链接:http://codeforces.com/contest/401/problem/D 题意:给出一个数字num和m,问通过重新排列num中的各位数字中有多少个数(mod m)=0,直接枚举 ...