在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. git 操作问题

    clone远程版本号库的时候,报错,提示路径不正确. 之前输入的路径为:ssh://[ip]:[port号]/[数据库名称] 增加username后的路径:ssh://[username]@[ip]: ...

  2. HTML学习笔记之三(localstorage的使用)

    localstorage的使用 1.获取对象 var localstroage = window.localStorage; 2.存储值 localstroage.setItem('openid',' ...

  3. Express4.x API (一):application (译)

    Express4.x API 译文 系列文章 Express4.x API (一):application (译) -- 完成 Express4.x API (二):request (译) -- 完成 ...

  4. 八、 Spring Boot 过滤器、监听器

    直接使用@WebFilter和@WebListener的方式,完成一个Filter 和一个 Listener.过滤器(Filter)文件MyFilter.Javapackage org.springb ...

  5. pycharm运行scrapy

    1.打开pycharm, 点击File>Open找到mySpider项目导入 . 2.打开File>Settings>Project 点击Project Interpreter 右边 ...

  6. 由一道bash jail题引出的琐事@_@

    关键词:Terminal devices.shell.stdio 题目入口: (需要注册) root@kali:~# ssh level1@24.37.41.154 -p 1016 level1@24 ...

  7. Fragment多重嵌套实现电影,影院展示页

    转载请标明出处: http://www.cnblogs.com/dingxiansen/p/8135888.html 本文出自:丁先森-博客园 公司以前的app是用H5封的,由于一个模块效果用H5实现 ...

  8. 【java】io流之字符输入流:java.io.Reader类及子类的子类java.io.FileReader

    package 文件操作; import java.io.File; import java.io.FileReader; import java.io.IOException; import jav ...

  9. HTML5 桌面通知:Notification API

    原文地址:http://blog.gdfengshuo.com/article/23/ 前言 Notification API 是 HTML5 新增的桌面通知 API,用于向用户显示通知信息.该通知是 ...

  10. js登录滑动验证,不滑动无法登陆

    js的判断这里是根据滑块的位置进行判断,应该是用一个flag判断 <%@ page language="java" contentType="text/html; ...