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

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

Asp.net Core认证和授权:Cookie认证
 

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

添加服务

  1. publicvoidConfigureServices(IServiceCollection services)
  2. {
  3.  
  4. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  5.  
  6. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
  7. }

注册中间件,添加到管道

app.UseAuthentication();

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

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

  1. // Copyright (c) .NET Foundation. All rights reserved.
  2. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
  3.  
  4. usingMicrosoft.AspNetCore.Http;
  5.  
  6. namespaceMicrosoft.AspNetCore.Authentication.Cookies
  7. {
  8. /// <summary>
  9. /// Default values related to cookie-based authentication handler
  10. /// </summary>
  11. publicstaticclassCookieAuthenticationDefaults
  12. {
  13. /// <summary>
  14. /// The default value used for CookieAuthenticationOptions.AuthenticationScheme
  15. /// </summary>
  16. publicconststringAuthenticationScheme="Cookies";
  17.  
  18. /// <summary>
  19. /// The prefix used to provide a default CookieAuthenticationOptions.CookieName
  20. /// </summary>
  21. publicstaticreadonlystringCookiePrefix=".AspNetCore.";
  22.  
  23. /// <summary>
  24. /// The default value used by CookieAuthenticationMiddleware for the
  25. /// CookieAuthenticationOptions.LoginPath
  26. /// </summary>
  27. publicstaticreadonlyPathStringLoginPath=newPathString("/Account/Login");
  28.  
  29. /// <summary>
  30. /// The default value used by CookieAuthenticationMiddleware for the
  31. /// CookieAuthenticationOptions.LogoutPath
  32. /// </summary>
  33. publicstaticreadonlyPathStringLogoutPath=newPathString("/Account/Logout");
  34.  
  35. /// <summary>
  36. /// The default value used by CookieAuthenticationMiddleware for the
  37. /// CookieAuthenticationOptions.AccessDeniedPath
  38. /// </summary>
  39. publicstaticreadonlyPathStringAccessDeniedPath=newPathString("/Account/AccessDenied");
  40.  
  41. /// <summary>
  42. /// The default value of the CookieAuthenticationOptions.ReturnUrlParameter
  43. /// </summary>
  44. publicstaticreadonlystringReturnUrlParameter="ReturnUrl";
  45. }
  46. }

我们可以自己修改:

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

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

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

option.Events.OnValidatePrincipal = ValidatePrincipal

想添加多个可以这样写:

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

  1. public async TaskValidatePrincipal(CookieValidatePrincipalContext context)
  2. {
  3. var_Context= context.HttpContext.RequestServices.GetRequiredService<EFContext>();
  4. var s = context.HttpContext.RequestServices.GetService<EFContext>();
  5.  
  6. var principal = context.Principal;
  7.  
  8. var u = principal.Claims.Select(c => c.Type=="isEdit").FirstOrDefault();
  9.  
  10. if(u)
  11. {
  12. //更新数据库状态
  13. //
  14.  
  15. // 1. 验证失败 等同于 Principal = principal;
  16. context.RejectPrincipal();
  17.  
  18. //登出
  19. await AuthenticationHttpContextExtensions.SignOutAsync(context.HttpContext,CookieAuthenticationDefaults.AuthenticationScheme);
  20. // 2. 验证通过,并会重新生成Cookie。
  21. //context.ShouldRenew = true;
  22.  
  23. }
  24. }

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

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

这个也很恰当

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

  1. [HttpPost]
  2. public async Task<IActionResult>Login(stringReturnUrl,User model)
  3. {
  4. if(model.UserName=="cnblogs"&& model.PassWord=="pwd")
  5. {
  6. /*
  7. ClaimsIdentity(身份证),Claims(身份信息)
  8. ClaimsPrinciple (证件所有者)
  9. */
  10.  
  11. //身份信息
  12. var claims =newList<Claim>{
  13. newClaim(ClaimTypes.Name,"sky"),
  14. newClaim("Address","北京海淀"),
  15. };
  16.  
  17. //身份证
  18. var claimsIdentity =newClaimsIdentity(claims,CookieAuthenticationDefaults.AuthenticationScheme);
  19.  
  20. //证件所有者
  21. var claimsPrinciple =newClaimsPrincipal(claimsIdentity);
  22.  
  23. /*
  24. 如果登陆选择了记住我,则将cookie持久化
  25. 这里默认持久化
  26. */
  27. var properties =newAuthenticationProperties
  28. {
  29. IsPersistent=true,
  30. ExpiresUtc=DateTimeOffset.UtcNow.AddDays(),
  31. //ExpiresUtc = DateTime.Now.AddDays(1)
  32.  
  33. };
  34. await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrinciple, properties);
  35.  
  36. returnRedirect(ReturnUrl);
  37. }
  38. else
  39. returnView("index");
  40. }

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

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. ASP.NET Core系列:JWT身份认证

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

  9. 在ASP.NET Core中添加的Cookie如果含有特殊字符,会被自动转义

    我们知道在Cookie中有些字符是特殊字符,这些字符是不能出现在Cookie的键值中的. 比如"="是Cookie中用来分隔键和值的特殊字符,例如:Key01=Value01,表示 ...

  10. ASP.NET Core 3.0 gRPC 身份认证和授权

    一.开头聊骚 本文算是对于 ASP.NET Core 3.0 gRPC 研究性学习的最后一篇了,以后在实际使用中,可能会发一些经验之文.本文主要讲 ASP.NET Core 本身的认证授权和gRPC接 ...

随机推荐

  1. [redis] Redis 配置文件置参数详解

    ################################ 基础配置 ################################# #daemonize no 默认情况下, redis 不 ...

  2. Unity3D 使用 UI 的 Grid Layout Group 组件。

    1.首先创建一个容器,用于存放列表项的内容. 这里使用 Panel 来做为容器. 这里要注意! “Grid Layout Group”是要增加在容器的游戏对象里. 同时,只有容器对象的子对象才有排列效 ...

  3. MVC中的URL路由(一)

    URL路由系统通过对请求地址进行解析从而得到以目标Controller名称为核心的路由数据.Url路由系统最初是为了实现请求url与物理文件路径分离而建立的,MVC的Url Route是将Url地址与 ...

  4. SQLPLUS使用

    1.CMD命令 2.输入SQLPLUS 3.如果oracle服务器中装有多个数据库实例,则在用户名处输入:用户名/密码@数据库名称.如果数据库服务器不在本机上,还需要加上数据库服务器的地址:用户名/密 ...

  5. 跨站请求伪造(Cross Site Request Forgery (CSRF))

    跨站请求伪造(Cross Site Request Forgery (CSRF)) 跨站请求伪造(Cross Site Request Forgery (CSRF)) 跨站请求伪造(Cross Sit ...

  6. 手机自动化测试:appium源码分析之bootstrap九

    手机自动化测试:appium源码分析之bootstrap九   poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣, ...

  7. vue项目构建与实战

    关于 微信公众号:前端呼啦圈(Love-FED) 我的博客:劳卜的博客 知乎专栏:前端呼啦圈 前言 由于vue相对来说比较平缓的学习过程和新颖的技术思路,使其受到了广大前后端开发者的青睐,同时其通俗易 ...

  8. Codeforces 777A Shell Game

    A. Shell Game time limit per test:0.5 seconds memory limit per test:256 megabytes input:standard inp ...

  9. 异常-----Can&#39;t convert the date to string, because it is not known which parts of the date variable are in use. Use ?date, ?time or ?datetime built-in, or ?string.u003Cformat&gt; or ?string(format) built-

    1.错误描述 五月 27, 2014 12:07:05 上午 freemarker.log.JDK14LoggerFactory$JDK14Logger error 严重: Template proc ...

  10. Gym 101606F - Flipping Coins - [概率DP]

    题目链接:https://codeforc.es/gym/101606/problem/F 题解: 假设 $f[i][j]$ 表示抛 $i$ 次硬币,有 $j$ 个硬币正面朝上的概率. 所以只有两种挑 ...