Asp.net Core認證和受權:Cookie認證

關於asp.net core 的文章,博客園已經有不少大牛寫過了。html

這裏我只是記錄下本身在學習中的點滴和一些不懂的地方數據庫

Cookie通常是用戶網站受權,當用戶訪問須要受權(authorization)的頁面,程序會判斷是否已經受權,並認證cookie

 

添加認證代碼:
引入命名空間:Microsoft.AspNetCore.Authentication.Cookies;app

添加服務asp.net

public void ConfigureServices(IServiceCollection services)
        {
           

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie();
        }

 

註冊中間件,添加到管道async

 app.UseAuthentication();ide

注意:必定要在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";
    }
}

 

 

咱們能夠本身修改:ui

  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(1),
                    //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

相關文章
相關標籤/搜索