ASP.Net 코어 2.1 쿠키의 쿠키 간단한 로그인 인증 확인 [검증]

원본 : ASP.Net 코어 2.1 쿠키 쿠키 간단한 로그인 권한 검증 [검증]

소개

이 항목은 블로그 공원에 게시했습니다 : https://www.cnblogs.com/fallstar/p/11310749.html의
저자 : fallstar를

ASP.NET 코어 2.1 + : 적용 대상

오늘은 확인하기 위해 프로젝트 권위의 asp.net 코어를 추가, 그래서 방법을 추가하는 조금 공부하고자,

잠시 던져 및 필터 방식이 버려진 것을 발견하고 지금을 확인하는 방법은 정책과 제도를 사용합니다. . .

멩은 그러나, MSDN을 검색하고 유래하기 시작했다. . . 나는 단순히 쉬운 것, 모두가 부적절하다고. . .

그들이 직접 할 수 있다면 때문에 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 ~ ~ ~ ~ 테이트보고되었다

추천

출처www.cnblogs.com/lonelyxmas/p/11318584.html