在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的更多相关文章

  1. ASP.NET Core 1.0 中的依赖项管理

    var appInsights=window.appInsights||function(config){ function r(config){t[config]=function(){var i= ...

  2. 在ASP.NET Core 1.0中如何发送邮件

    (此文章同时发表在本人微信公众号"dotNET每日精华文章",欢迎右边二维码来关注.) 题记:目前.NET Core 1.0中并没有提供SMTP相关的类库,那么要如何从ASP.NE ...

  3. ASP.NET Core 1.0 中使用 Swagger 生成文档

    github:https://github.com/domaindrivendev/Ahoy 之前文章有介绍在ASP.NET WebAPI 中使用Swagger生成文档,ASP.NET Core 1. ...

  4. 用ASP.NET Core 1.0中实现邮件发送功能

    准备将一些项目迁移到 asp.net core 先从封装类库入手,在遇到邮件发送类时发现在 asp.net core 1.0中并示提供SMTP相关类库,于是网上一搜发现了MailKit 好东西一定要试 ...

  5. 如何在ASP.NET Core 2.0中使用Razor页面

    如何在ASP.NET Core 2.0中使用Razor页面  DotNetCore2017-11-22 14:49 问题 如何在ASP.NET Core 2.0中使用Razor页面 解 创建一个空的项 ...

  6. ASP.NET Core 3.0中使用动态控制器路由

    原文:Dynamic controller routing in ASP.NET Core 3.0 作者:Filip W 译文:https://www.cnblogs.com/lwqlun/p/114 ...

  7. asp.net core 3.0 中使用 swagger

    asp.net core 3.0 中使用 swagger Intro 上次更新了 asp.net core 3.0 简单的记录了一下 swagger 的使用,那个项目的 api 比较简单,都是匿名接口 ...

  8. 探索 ASP.Net Core 3.0系列三:ASP.Net Core 3.0中的Service provider validation

    前言:在本文中,我将描述ASP.NET Core 3.0中新的“validate on build”功能. 这可以用来检测您的DI service provider是否配置错误. 具体而言,该功能可检 ...

  9. 在Asp.Net Core 3.0中如何使用 Newtonsoft.Json 库序列化数据

    在.Net Core 3.0中 内置了一套Json序列化/反序列化方案,默认可以不再依赖,不再支持   Newtonsoft.Json. 但是.NET Core 3.0 System.Text.Jso ...

随机推荐

  1. hdu5303Delicious Apples

    题意大概就是有n框苹果放在长度为L的环上,每框有ai个苹果.你有一个容量为k的框.要你从0点处出发,随意走.框满了就回到0点把苹果放在那里.继续走直到把苹果都拿完为止.问你最少要走多少路程. 首先贪心 ...

  2. 十一、Spring Boot 集成Shiro和CAS

    1.Shiro 是什么?怎么用? 2.Cas 是什么?怎么用? 3.最好有spring基础 首先看一下下面这张图: 第一个流程是单纯使用Shiro的流程. 第二个流程是单纯使用Cas的流程. 第三个图 ...

  3. Java方法的概念及使用

    方法 将一段逻辑或者功能提取出来,这种提取的形式就是函数 格式 修饰符 返回值类型 函数名(参数列表){ 方法体: return 返回值; } //明确返回值类型---求两个整数的和,确定结果一定是整 ...

  4. TextMesh Pro Emoji Align With Text(表情和文字对齐)

    前言 MMO游戏中需要富文件组件,大体功能包括图文混排,表情,超链接,文字动画等富文本功能,且DC数占用少. 本文选择Unity免费提供的TextMesh Pro 解决方案. 软件环境 Unity3D ...

  5. C#读取XML文件的五个步骤

    //1.创建XmlDocument对象 XmlDocument  xmlDoc=new XmlDocument(); //2.加载源文件 xmlDoc.Load("文件名.xml" ...

  6. 【maven教程】(1)---maven环境配置

    maven环境配置 刚开始学习maven,现在项目需要用到maven,而且他确实很好用,也比较容易上手,我也是主要通过视频学习,在写博客的时候也会总结其它人所写 博客,从简到难,如果你也是初学者那接下 ...

  7. 基于 HTML5 WebGL 的 3D 服务器与客户端的通信

    这个例子的初衷是模拟服务器与客户端的通信,我把整个需求简化变成了今天的这个例子.3D 机房方面的模拟一般都是需要鹰眼来辅助的,这样找产品以及整个空间的概括会比较明确,在这个例子中我也加了,这篇文章就算 ...

  8. SignalR简单Demo

    我们实现一个简单的消息通知的Demo 在NuGet中添加SignalR引用 install-package Microsoft.AspNet.SignalR 然后我们创建一个类来引用Hub类 name ...

  9. qt调用simsimi api实现小黄鸡

    项目地址:https://github.com/racaljk/xiaojianji 好吧我把它命名为小贱鸡.,下面说一说他的实现. 由于官方的simsimi api需要收费,免费试用版有各种限制,所 ...

  10. bzoj 3142: [Hnoi2013]数列

    Description 小T最近在学着买股票,他得到内部消息:F公司的股票将会疯涨.股票每天的价格已知是正整数,并且由于客观上的原因,最多只能为N.在疯涨的K天中小T观察到:除第一天外每天的股价都比前 ...