ASP.Netコア2.1+クッキークッキーシンプルなログイン認証の検証[検証]

オリジナル: ASP.Netコア2.1+クッキークッキーシンプルなログイン認証の検証[検証]

入門

このエントリは、ブログパークに掲載されました:https://www.cnblogs.com/fallstar/p/11310749.html
著者:fallstar

ASP.NETコア2.1 +:この記事はに適用されます

今日、私は確認するために、プロジェクトの権限のasp.netコアを追加したいので、どのように追加する少し勉強し、

一瞬トスとフィルタ方式が放棄されたことが判明し、今チェックする方法の政策や制度を使用しています。

孟は、しかし、MSDNとstackoverflowのを検索し始めました。不適切なすべての検索、私は単純に簡単だろう。

彼らは直接できるかどうかためのAllowAnonymous承認が大幅に節約することができます。

初版では、MSDNを参照します:

//Startup.cs
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(x =>
                {
                    x.LoginPath = new PathString("/Home/Login");//登录页面
                    x.LogoutPath = new PathString("/Home/Logout");//登出页面
                });
        }

//HomeController .cs
    /// <summary>
    /// 首页
    /// </summary>
    [Authorize]
    public class HomeController : Controller
    {
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        public IActionResult Login()
        {
            return View();
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public IActionResult Logout()
        {
            HttpContext.SignOutClain();
            return RedirectToAction("Login");
        }
    }

上記のコードは、ジャンプを許可するために使用され、非常に簡単です、インデックスは自宅で匿名アクセスログイン、許可が必要です。

方法を提供する膨張続いWebHelperを

アクションは、その内部のコントローラに直接HttpContext.Login呼び出します。

    /// <summary>
    /// Web帮助类
    /// </summary>
    public static class WebHelper
    {
        #region Auth
        /// <summary>
        ///  登录
        /// </summary>
        public static bool Login(this HttpContext context, string username,string password)
        {
            //验证登录
            if (!(username != "admin" && password != "123456"))
                return false;
            //成功就写入
            context.SignInClain(1, username, true, TimeSpan.FromHours(3));
            return true;
        }

        /// <summary>
        /// 将登录用户信息写入凭据,输出到cookie
        /// </summary>
        /// <param name="context"></param>
        /// <param name="userid"></param>
        /// <param name="username"></param>
        /// <param name="isAdmin"></param>
        public static async void SignInClain(this HttpContext context, int userid, string username, bool isAdmin = false, TimeSpan? expire = null)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, username),
                new Claim(ClaimTypes.NameIdentifier,userid.ToString()),
                new Claim(ClaimTypes.Role,isAdmin?"1":"0")
            };
            if (!expire.HasValue)
                expire = TimeSpan.FromHours(3);

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties()
            {
                ExpiresUtc = DateTime.UtcNow.Add(expire.Value),
                IsPersistent = true,
            };
            await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);
        }

        /// <summary>
        /// 登出,清除登录信息
        /// </summary>
        /// <param name="context"></param>
        public static async void SignOutClain(this HttpContext context)
        {
            await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
        #endregion
    }

私はビンを考えた場合。突然見つけWEBAPIは、ログインページにしました。これは間違いなく不可能です。

それから私は、ハードの研究文書、無ゲインを持って、そして最後に、私は慎重に、クラス内の設定項目を表示し、方法を見つけました。

これの最終版は次のとおりです。


        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.Lax;
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(x =>
                {
                    x.LoginPath = new PathString("/Home/Login");//登录页面
                    x.LogoutPath = new PathString("/Home/Logout");//登出页面
                    //多了下面这段针对WebApi的代码
                    x.Events.OnRedirectToLogin = z =>
                    {
                        if (z.HttpContext.Request.Path.StartsWithSegments("/api", StringComparison.OrdinalIgnoreCase))
                        {
                            z.HttpContext.Response.Redirect("/api/Login/UnAuth");//未授权错误信息的接口地址,返回json
                        }
                        else
                        {
                            z.HttpContext.Response.Redirect(z.RedirectUri);//其它安装默认处理
                        }
                        return Task.CompletedTask;
                    };
                });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

       public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            //...

            app.UseCookiePolicy();
            app.UseAuthentication();

            //app.UseMvc

        }

OK ~~~~ Taitのレポートになりました

おすすめ

転載: www.cnblogs.com/lonelyxmas/p/11318584.html