关于asp.net core 的文章,博客园已经有很多大牛写过了。

这里我只是记录下自己在学习中的点滴和一些不懂的地方

Cookie一般是用户网站授权,当用户访问需要授权(authorization)的页面,程序会判断是否已经授权,并认证

添加认证代码:
引入命名空间:Microsoft.AspNetCore.Authentication.Cookies;

添加服务

public void ConfigureServices(IServiceCollection services)
{ services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();
}

注册中间件,添加到管道

app.UseAuthentication();

注意:一定要在app.UseMvc之前添加

我们通过源码可以看到cookie的一些默认配置

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Authentication.Cookies
{
/// <summary>
/// Default values related to cookie-based authentication handler
/// </summary>
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";
}
}

我们可以自己修改:

  services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(option =>
{
option.LoginPath = "/Login"; //没有授权,跳转的url
option.LogoutPath = "/Login"; //退出,的url
});

因为cookie在有效期内都是有效的,如果用户资料修改了,客户端的Cookie是不知道的

网上有人提出了解决方案,如果用户修改了资料,在数据库用一个字段记录,cookie有个事件,在每次请求都会访问

option.Events.OnValidatePrincipal = ValidatePrincipal

想添加多个可以这样写:

option.Events = new CookieAuthenticationEvents
                    {
                        OnValidatePrincipal = ValidatePrincipal,
                        //OnRedirectToLogin =
                    };

 public async Task ValidatePrincipal(CookieValidatePrincipalContext context)
{
var _Context = context.HttpContext.RequestServices.GetRequiredService<EFContext>();
var s = context.HttpContext.RequestServices.GetService<EFContext>(); var principal = context.Principal; var u = principal.Claims.Select(c => c.Type == "isEdit").FirstOrDefault(); if (u)
{
//更新数据库状态
// // 1. 验证失败 等同于 Principal = principal;
context.RejectPrincipal(); //登出
await AuthenticationHttpContextExtensions.SignOutAsync(context.HttpContext, CookieAuthenticationDefaults.AuthenticationScheme);
// 2. 验证通过,并会重新生成Cookie。
//context.ShouldRenew = true; }
}

用户登陆,网上有人这里解释的

ClaimsIdentity(身份证),Claims(身份信息)
           ClaimsPrinciple (证件所有者)

这个也很恰当

https://www.cnblogs.com/dudu/p/6367303.html

  [HttpPost]
public async Task<IActionResult> Login(string ReturnUrl, User model)
{
if (model.UserName=="cnblogs" && model.PassWord == "pwd")
{
/*
ClaimsIdentity(身份证),Claims(身份信息)
ClaimsPrinciple (证件所有者)
*/ //身份信息
var claims = new List<Claim> {
new Claim(ClaimTypes.Name,"sky"),
new Claim("Address","北京海淀"),
}; //身份证
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); //证件所有者
var claimsPrinciple = new ClaimsPrincipal(claimsIdentity); /*
如果登陆选择了记住我,则将cookie持久化
这里默认持久化
*/
var properties = new AuthenticationProperties
{
IsPersistent = true,
ExpiresUtc = DateTimeOffset.UtcNow.AddDays(),
//ExpiresUtc = DateTime.Now.AddDays(1) };
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrinciple, properties); return Redirect(ReturnUrl);
}
else
return View("index");
}

博客园的大神文章,很多。就放几个参考吧

https://www.cnblogs.com/RainingNight/p/7587194.html

https://www.cnblogs.com/tdfblog/p/7416589.html

Asp.net Core认证和授权:Cookie认证的更多相关文章

  1. ASP.NET Core 2.0使用Cookie认证实现SSO单点登录

    之前写了一个使用ASP.NET MVC实现SSO登录的Demo,https://github.com/bidianqing/SSO.Sample,这个Demo是基于.NET Framework,.NE ...

  2. 关于ASP.Net Core Web及API身份认证的解决方案

    6月15日,在端午节前的最后一个工作日,想起有段日子没有写过文章了,倒有些荒疏了.今借夏日蒸蒸之气,偷得浮生半日悠闲.闲话就说到这里吧,提前祝大家端午愉快(屈原听了该不高兴了:))!.NetCore自 ...

  3. 【ASP.NET Core】运行原理[3]:认证

    本节将分析Authentication 源代码参考.NET Core 2.0.0 HttpAbstractions Security 目录 认证 AddAuthentication IAuthenti ...

  4. ASP.NET Core如何使用WSFederation身份认证集成ADFS

    如果要在ASP.NET Core项目中使用WSFederation身份认证,首先需要在项目中引入NuGet包: Microsoft.AspNetCore.Authentication.WsFedera ...

  5. NET Core 2.0使用Cookie认证实现SSO单点登录

    NET Core 2.0使用Cookie认证实现SSO单点登录 之前写了一个使用ASP.NET MVC实现SSO登录的Demo,https://github.com/bidianqing/SSO.Sa ...

  6. ASP.NET Core编程实现基本身份认证

    概览 在HTTP中,基本认证(Basic access authentication,简称BA认证)是一种用来允许网页浏览器或其他客户端程序在请求资源时提供用户名和口令形式的身份凭证的一种登录验证方式 ...

  7. .Net Core 认证系统之Cookie认证源码解析

    接着上文.Net Core 认证系统源码解析,Cookie认证算是常用的认证模式,但是目前主流都是前后端分离,有点鸡肋但是,不考虑移动端的站点或者纯管理后台网站可以使用这种认证方式.注意:基于浏览器且 ...

  8. .Net Core 认证组件之Cookie认证组件解析源码

    接着上文.Net Core 认证系统源码解析,Cookie认证算是常用的认证模式,但是目前主流都是前后端分离,有点鸡肋但是,不考虑移动端的站点或者纯管理后台网站可以使用这种认证方式.注意:基于浏览器且 ...

  9. ASP.NET Core系列:JWT身份认证

    1. JWT概述 JSON Web Token(JWT)是目前流行的跨域身份验证解决方案. JWT的官网地址:https://jwt.io JWT的实现方式是将用户信息存储在客户端,服务端不进行保存. ...

  10. Asp.Net Core 中IdentityServer4 授权中心之自定义授权模式

    一.前言 上一篇我分享了一篇关于 Asp.Net Core 中IdentityServer4 授权中心之应用实战 的文章,其中有不少博友给我提了问题,其中有一个博友问我的一个场景,我给他解答的还不够完 ...

随机推荐

  1. [No0000146]深入浅出图解C#堆与栈 C# Heap(ing) VS Stack(ing)理解堆与栈3/4

    前言   虽然在.Net Framework 中我们不必考虑内在管理和垃圾回收(GC),但是为了优化应用程序性能我们始终需要了解内存管理和垃圾回收(GC).另外,了解内存管理可以帮助我们理解在每一个程 ...

  2. hdu6330 多校3 L 画一个cube

    http://acm.hdu.edu.cn/showproblem.php?pid=6330 技巧:循环变量要选1~A,然后把公式写下标里.会快很多 #define _CRT_SECURE_NO_WA ...

  3. 2014年蓝桥杯省赛A组c++第3题(数组构造+暴力求解)

    /* 标题:神奇算式 由4个不同的数字,组成的一个乘法算式,它们的乘积仍然由这4个数字组成. 比如: 210 x 6 = 1260 8 x 473 = 3784 27 x 81 = 2187 都符合要 ...

  4. CloudStack+KVM环境搭建(步骤很详细,说明ClockStack是用来管理虚拟机的)

    文章目录环境准备配置本地域名解析关闭selinux安装ntp服务安装管理端安装Mysql数据库安装服务端RPM:初始化CloudStack数据库:初始化cloudstack管理服务器安装系统虚拟机安装 ...

  5. 这个zsh超级棒

    https://github.com/robbyrussell/oh-my-zsh wget用法: http://man.linuxde.net/wget https://pan.baidu.com/ ...

  6. es分页搜索

    1.es分页语法GET /_search?from=起始数&size=页面显示条数例如:GET /test_index/test_type/_search?from=0&size=3 ...

  7. 同步fifo的Verilog实现

    FIFO是一种先进先出的数据缓存器,他与普通存储器相比: 优点:没有外部读写地址线,这样使用起来非常简单: 缺点:只能顺序写入数据,顺序的读出数据, 其数据地址由内部读写指针自动加1完成,不能像普通存 ...

  8. gitlab数据库

    event表中action对应操作: 1 - 新建项目 5 - push 8 - 在某项目中赋予某人权限 9 - 在某项目中取消某人权限

  9. The each() function is deprecated报错的解决方法

    下午ytkah安装程序时出现了如下提示,意思是each函数过时了,可能跟php版本有关,因为今天早上刚把LAMP组件升级了,php升到7.2了,切换成php 7.1版本,提示消失了,可见PHP 7.2 ...

  10. kafka3 本地目录结构以及在在zk上的znode

    一 kafka本地目录结构 [root@hadoop ~]# cd /tmp/kafka-logs1 [root@hadoop kafka-logs1]# find . . ./.lock ./rec ...