背景

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. project.config.json在设置了编译模式的时候会出现配置,怎么解决

    因为之前为了方便就选了一个页面进行编译,但是想想回到index首页,就编译了一个pages/index/index. 出现了上面这个,当我再选择编译的时候,还是不会变成之前的. 解决方法是 把红框那段 ...

  2. zabbix监控线

    echo mntr | nc 127.0.0.1 2181获取mntr的信息 换成conf将获得conf信息,从中找出需要监控项 conf: clientPort:客户端端口号 dataDir:数据文 ...

  3. windows--zabbix-agent添加主机

        1.首先在 C 盘根目录下创建 zabbix 的文件夹 2.将需要的文件拖到该文件夹内(bin/win64) 3.修改 windows 配置文件(zabbix.agent.win.conf)的 ...

  4. tecplot-计算合速度的一种方法

    原视频下载地址: http://yunpan.cn/cudFwWr8tFsxV  访问密码 75a8

  5. python判断字符串包含关系

    转自---http://blog.csdn.net/yl2isoft/article/details/52079960 1.使用成员操作符 in >>> s='nihao,shiji ...

  6. 免费s账号网站

    下面网址按排序顺序优先使用,数字越小优先级越高 1,https://io.freess.today/ 2,https://free-ss.site/ 3,https://ss.freess.org/ ...

  7. vuejs2从入门到精通视频教程

    https://www.cnblogs.com/web-666/p/8648607.html 一.基础部分 0.课件 1.介绍 2.vue实例 3.模板语法 4.计算属性和观察者 5.Class与St ...

  8. 008 BOM

    一:说明 1.说明 浏览器对象模型 2.顶级对象 浏览器中的顶级对象是window 页面中的顶级对象是document 因此: 变量属于window的,函数也是window的. 就可以使用window ...

  9. 清除input的历史记录

    原始代码: <input class="" type="text"></input> 加上“autocomplete”属性,禁止历史的显 ...

  10. Java基础 import 要在所有的class前面

        JDK :OpenJDK-11      OS :CentOS 7.6.1810      IDE :Eclipse 2019‑03 typesetting :Markdown   code ...