背景

Asp.Net Core 项目升级至 2.x 版本后,Cookie 验证方式需要进行更新。

升级前:.Net Core 1.x

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Other Options ...
// IMPORTANT: UseCookieAuthentication() MUST before UseMvc()
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "MyCookieMiddlewareInstance",
LoginPath = new PathString("/Home/Index/"),
AccessDeniedPath = new PathString("/Home/AccessDenied/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true,
CookiePath = "/"
}); // Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}

Login

var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Sid, Convert.ToString(user.Gid))
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "AccountLogin"));
var property = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddHours(1) };
await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal, property);
return RedirectToAction(nameof(LoginController.Index), "Candidate");

Logout

HttpContext.Session.Clear();
await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
return RedirectToAction(nameof(HomeController.Index), "Home");

升级后:.Net Core 2.x

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication("MyCookieAuthenticationScheme")
.AddCookie("MyCookieAuthenticationScheme", options => {
options.SlidingExpiration = false;
options.ExpireTimeSpan = TimeSpan.FromHours();
options.Cookie = new CookieBuilder { HttpOnly = true, Name = "MyCookie", Path = "/" };
options.LoginPath = "/Home/Index/";
options.AccessDeniedPath = "/Home/AccessDenied/";
});
services.AddMvc();
// Other Options ...
} public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Other Options ...
app.UseAuthentication();

// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
}

Login

var claims = new List<Claim>
{
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.Name, user.Name),
new Claim(ClaimTypes.Sid, Convert.ToString(user.Gid))
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "AccountLogin"));
await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);
return RedirectToAction(nameof(CandidateController.Index), "Candidate");

Logout

HttpContext.Session.Clear();
await HttpContext.SignOutAsync("MyCookieAuthenticationScheme");
return RedirectToAction(nameof(HomeController.Index), "Home");

参考资料(了解更多细节)

https://www.cnblogs.com/tdfblog/p/aspnet-core-security-authentication-cookie.html

[.Net Core] - 当 .Net Core 版本由 1.x 升级至 2.x 后,Cookie 使用方式变更的更多相关文章

  1. ABP 教程文档 1-1 手把手引进门之 ASP.NET Core & Entity Framework Core(官方教程翻译版 版本3.2.5)

    本文是ABP官方文档翻译版,翻译基于 3.2.5 版本 官方文档分四部分 一. 教程文档 二.ABP 框架 三.zero 模块 四.其他(中文翻译资源) 本篇是第一部分的第一篇. 第一部分分三篇 1- ...

  2. .NET Core 项目指定SDK版本

    一. 版本里的坑 自从 .NET Core 2.1.0版本发布以后,近几个月微软又进行了几次小版本的发布,可见 .NET Core 是一门生命力非常活跃的技术.经过一段时间的实践,目前做 ASP.NE ...

  3. [ASP.NET Core] 建置x86版本 (workaround)

    前言 本篇文章介绍如何建置ASP.NET Core项目的x86版本输出(workaround),为自己留个纪录也希望能帮助到有需要的开发人员. ASP.NET Core官网 步骤 首先到微软官网的「. ...

  4. [转帖].NET Core 项目指定SDK版本

    .NET Core 项目指定SDK版本 https://www.cnblogs.com/stulzq/p/9503121.html 一. 版本里的坑 自从 .NET Core 2.1.0版本发布以后, ...

  5. MacBook下为要运行的.net core 项目指定sdk版本

    安装完.net core 3.0,运行早期版本构建的项目遇到运行错误,查阅官方文档解决问题,特此记录!官方原文如下: SDK 使用最新安装的版本 SDK 命令包括 dotnet new 和 dotne ...

  6. 尝新体验ASP.NET Core 6预览版本中发布的最小Web API(minimal APIS)新特性

    本文首发于<尝新体验ASP.NET Core 6预览版本中发布的最小Web API(minimal APIS)新特性> 概述 .NET开发者们大家好,我是Rector. 几天前(美国时间2 ...

  7. net Core 通过 Ef Core 访问、管理Mysql

    net Core 通过 Ef Core 访问.管理Mysql 本文地址:http://www.cnblogs.com/likeli/p/5910524.html 环境 dotnet Core版本:1. ...

  8. ASP.net core 使用UEditor.Core 实现 ueditor 上传功能

    ASP.net core 使用UEditor.Core 实现 ueditor 上传功能 首先通过nuget 引用UEditor.Core,作者github:https://github.com/bai ...

  9. ASP.NET Core 入门教程 8、ASP.NET Core + Entity Framework Core 数据访问入门

    一.前言 1.本教程主要内容 ASP.NET Core MVC 集成 EF Core 介绍&操作步骤 ASP.NET Core MVC 使用 EF Core + Linq to Entity ...

随机推荐

  1. Ruby on Rails框架(1)-安装全攻略

    序 关于Rails的三句箴言 (1)DRY:Don't Repeat Yourself(不要重复你自己) rails的开发理念,不要用你的代码不停的重复,rails框架给开发者提供了一套非常完善的支持 ...

  2. shell 命令的重命名alias

    1.实现别名:alias ddd="df -Th": 2.删除别名:unalias ddd: 3.显示所有别名命令列表:alias: 4.存放位置:~/.bashrc  (加入该文 ...

  3. 记录vsCode配置node开发环境

    环境:win10,idea:vscode 1:安装Visual Studio Code 下一步下一步.(很早之前就安装了). 2:安装node. http://nodejs.cn/download/  ...

  4. 第K个幸运数(京东2017秋招真题)

    题目 4和7是两个幸运数字,我们定义,十进制表示中,每一位只有4和7两个数的正整数都是幸运数字.前几个幸运数字为:4,7,44,47,74,77,444,447... 现在输入一个数字K,输出第K个幸 ...

  5. python window窗口

    from Tkinter import * root=Tk() root.title('我是root窗口!') L=Label(root,text='我属于root') L.pack() f=Topl ...

  6. 怎么设置cookie,怎么设置cookie以及删除cookie和cookie详解

    在操作cookie之前,先来看一下cookie长什么样. 可以看到,cookie是一个个键值对(“键=值”的形式)加上分号空格隔开组合而成, 形如: "name1=value1; name2 ...

  7. mysql起容器的最精简命令

    亲测有效的 mysql 容器命令: #pull mysql:5.6 docker pull mysql:5.6 #起容器,映射3306端口,配置root用户密码 docker run -di --na ...

  8. 基于spark logicplan的表血缘关系解析实现

    随着公司平台用户数量与表数量的不断增多,各种表之间的数据流向也变得更加复杂,特别是某个任务中会对源表读取并进行一系列复杂的变换后又生成新的数据表,因此需要一套表血缘关系解析机制能清晰地解析出每个任务所 ...

  9. 泡泡一分钟:Project AutoVision - Localization and 3D Scene Perception for an Autonomous Vehicle with a Multi-Camera System

    Project AutoVision - Localization and 3D Scene Perception for an Autonomous Vehicle with a Multi-Cam ...

  10. 【composer】 PHP composer 镜像地址更换

    如果你使用的是 laravel-china.org 得 composer 镜像.那么近期执行更新时候就会报错: 莫慌,这是因为 laravel-china.org 已经停止了对composer得更新. ...