ASP.Net Core 2.1+ Cookie Cookie simple login authorization verification [verification]

Original: ASP.Net Core 2.1+ Cookie Cookie simple login authorization verification [verification]

Introduction

This entry was posted on blog Park: https://www.cnblogs.com/fallstar/p/11310749.html
Author: fallstar

This article applies to: ASP.NET Core 2.1 +

Today, I want to add a asp.net core of the project authority to verify, so study a little how to add,

Toss for a moment and found that the Filter manner was abandoned and now uses Policy and Scheme of ways to check the. . .

Meng then began to search msdn and stackoverflow, however. . . Find all inappropriate, I would simply easy. . .

Because if they can directly AllowAnonymous and Authorize can save a lot of.

Referring to the msdn, with the first edition:

//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");
        }
    }

The above code is very simple, it is used to authorize jump, Index is home need permission, Login anonymous access.

Followed by expansion to provide a method of WebHelper

Action call HttpContext.Login directly in the controller inside it.

    /// <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
    }

When I thought of the bin. . . Suddenly found webapi was brought to the login page. . . It is definitely impossible.

Then I have a hard research documents, no gain, and finally, I carefully view the configuration items inside the class, and then found a way.

The final version of this is the following:


        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 ~ ~ ~ ~ became Tait report

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11318584.html