在ASP.NET Core 2.0中使用CookieAuthentication
在ASP.NET Core中关于Security有两个容易混淆的概念一个是Authentication(认证),一个是Authorization(授权)。而前者是确定用户是谁的过程,后者是围绕着他们允许做什么,今天的主题就是关于在ASP.NET Core 2.0中如何使用CookieAuthentication认证。
在ASP.NET Core 2.0中使用CookieAuthentication跟在1.0中有些不同,需要在ConfigureServices和Configure中分别设置,前者我们叫注册服务,后者我们叫注册中间
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie();
// 不允许匿名访问
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
// 使用Authentication中间件,这里关于认证只有一个中间件,具体的认证策略将在服务中注册
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
在配置服务方法中我们使用Cookie认证所以AddCookie(),没有任何参数,系统会为某些属性指定默认值
public static class CookieAuthenticationDefaults
{
/// <summary>
/// The default value used for CookieAuthenticationOptions.AuthenticationScheme
/// </summary>
public const string AuthenticationScheme = "Cookies";
/// <summary>
/// The prefix used to provide a default CookieAuthenticationOptions.CookieName
/// </summary>
public static readonly string CookiePrefix = ".AspNetCore.";
/// <summary>
/// The default value used by CookieAuthenticationMiddleware for the
/// CookieAuthenticationOptions.LoginPath
/// </summary>
public static readonly PathString LoginPath = new PathString("/Account/Login");
/// <summary>
/// The default value used by CookieAuthenticationMiddleware for the
/// CookieAuthenticationOptions.LogoutPath
/// </summary>
public static readonly PathString LogoutPath = new PathString("/Account/Logout");
/// <summary>
/// The default value used by CookieAuthenticationMiddleware for the
/// CookieAuthenticationOptions.AccessDeniedPath
/// </summary>
public static readonly PathString AccessDeniedPath = new PathString("/Account/AccessDenied");
/// <summary>
/// The default value of the CookieAuthenticationOptions.ReturnUrlParameter
/// </summary>
public static readonly string ReturnUrlParameter = "ReturnUrl";
}
根据微软的命名规范在ConfigureServices统一使用Add***,在Configure统一使用Use***
登陆代码
public async Task<IActionResult> LoginDo()
{
var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bidianqing") }, CookieAuthenticationDefaults.AuthenticationScheme));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user, new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.Now.Add(TimeSpan.FromDays(180))
});
return Redirect("/");
}
登出代码
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/");
}
在ASP.NET Core 2.0中使用CookieAuthentication的更多相关文章
- ASP.NET Core 1.0 中的依赖项管理
var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...
- 在ASP.NET Core 1.0中如何发送邮件
(此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...
- ASP.NET Core 1.0 中使用 Swagger 生成文档
github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...
- 用ASP.NET Core 1.0中实现邮件发送功能
准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...
- 如何在ASP.NET Core 2.0中使用Razor页面
如何在ASP.NET Core 2.0中使用Razor页面 DotNetCore2017-11-22 14:49 问题 如何在ASP.NET Core 2.0中使用Razor页面 解 创建一个空的项 ...
- ASP.NET Core 3.0中使用动态控制器路由
原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...
- asp.net core 3.0 中使用 swagger
asp.net core 3.0 中使用 swagger Intro 上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口 ...
- 探索 ASP.Net Core 3.0系列三:ASP.Net Core 3.0中的Service provider validation
前言:在本文中,我将描述ASP.NET Core 3.0中新的“validate on build”功能. 这可以用来检测您的DI service provider是否配置错误. 具体而言,该功能可检 ...
- 在Asp.Net Core 3.0中如何使用 Newtonsoft.Json 库序列化数据
在.Net Core 3.0中 内置了一套Json序列化/反序列化方案,默认可以不再依赖,不再支持 Newtonsoft.Json. 但是.NET Core 3.0 System.Text.Jso ...
随机推荐
- STM32W108无线射频模块通用IO接口应用实例
STM32W108无线射频模块通用IO接口应用实例 本实例编写STM32W108的GPIO測试程序,通过控制GPIO引脚,实现对LED灯的控制. 开发环境与硬件说明 硬件:STM32W108无线开发板 ...
- 你懂AI吗(1)
那场载入史册的战争之后,AI成为地球的主人已经快一个世纪了. 随着见证这场战争的那一代人基本消失,除了几个要堵上人类的尊严,颠覆AI的邪恶统治的组织外,现在的人基本已经习惯了这个AI统治的世界. AI ...
- 机器学习 - pycharm, tensorflow集成篇
继续上篇的pyspark集成后,我们再来看看当今热的不得了的tensorflow是如何继承进pycharm环境的 参考: http://blog.csdn.net/include1224/articl ...
- 17082 两个有序数序列中找第k小(优先做)
17082 两个有序数序列中找第k小(优先做) 时间限制:1000MS 内存限制:65535K提交次数:0 通过次数:0 题型: 编程题 语言: G++;GCC;VC Description 已 ...
- 关键字中mysql数据库查询条件带中文无结果解决办法
package keyword; import java.io.UnsupportedEncodingException; import java.sql.Connection; import jav ...
- 云计算之路-阿里云上-2017年最错误的选择: 生产环境使用 docker swarm
2017年12月29日 10:18 ~ 11:00 左右,由于整个 docker swarm 集群宕机,造成我们迁移至 .net core 跑在 docker swram 上的所有站点无法正常访问,由 ...
- Linux 学习记录 三(Vim 文书编辑器).
所有的Unix Like系统都会内建vi文书编辑器,其他的文书编辑器不一定存在,vim是vi的升级版,具有程序编辑的能力,可以主动的以字体颜色辨别语法的正确性,方便程序设计.vim 里 ...
- bzoj 1835: [ZJOI2010]base 基站选址
Description 有N个村庄坐落在一条直线上,第i(i>1)个村庄距离第1个村庄的距离为Di.需要在这些村庄中建立不超过K个通讯基站,在第i个村庄建立基站的费用为Ci.如果在距离第i个村庄 ...
- Java设计模式总汇一
PS:首先我们要带着问题读文章 什么是设计模式 为什么要用设计模式 使用设计模式有什么好处 设计模式是一套被反复使用的.多数人知晓的.经过分类编目的.代码设计经验的总结.使用设计模式是为了重用代码.让 ...
- SpringMVC处理multipart请求.
一.简述 multipart格式的数据会将一个表单拆分为多个部分(part),每个部分对应一个输入域.在一般的表单输入域中,它所对应的部分中会放置文本型数据,但是如果上传文件的话,它所对应的部分可以是 ...