1. 程式人生 > >NETCore MVC登入授權

NETCore MVC登入授權

1.需要在Startup ConfigureServices(IServiceCollection services)中 配置如下程式碼

 #region  //身份認證時需要使用的方法
            services.AddSession(options=> {
                options.Cookie.HttpOnly = true;
              
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.IdleTimeout = TimeSpan.FromMinutes(ApplicationEnvironments.Site.SessionTimeout);
            });
           
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.DataProtectionProvider= DataProtectionProvider.Create(new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory+ "/shared-auth-ticket-keys/"));
                options.Cookie.Name = ApplicationEnvironments.Site.CookieName;
                options.Cookie.Path = "/";
                options.LoginPath = new PathString("/login");
                options.AccessDeniedPath = new PathString("/Forbidden"); //禁止訪問路徑:當用戶試圖訪問資源時,但未通過該資源的任何授權策略,請求將被重定向到這個相對路徑。
               // options.SlidingExpiration = false;  //Cookie可以分為永久性的和臨時性的。 臨時性的是指只在當前瀏覽器程序裡有效,瀏覽器一旦關閉就失效(被瀏覽器刪除)。 永久性的是指Cookie指定了一個過期時間,在這個時間到達之前,此cookie一直有效(瀏覽器一直記錄著此cookie的存在)。 slidingExpriation的作用是,指示瀏覽器把cookie作為永久性cookie儲存,但是會自動更改過期時間,以使使用者不會在登入後並一直活動,但是一段時間後卻自動登出。也就是說,你10點登入了,伺服器端設定的TimeOut為30分鐘,如果slidingExpriation為false,那麼10:30以後,你就必須重新登入。如果為true的話,你10:16分時打開了一個新頁面,伺服器就會通知瀏覽器,把過期時間修改為10:46。 更詳細的說明還是參考MSDN的文件。
            });
            #endregion
services.MVC() .AddSessionStateTempDataProvider();

在Configure(IApplicationBuilder app, IHostingEnvironment env)新增如下程式碼

app.UseAuthentication();

在登入頁面中呼叫如下程式碼


var claims = new List<Claim>()
{
   new Claim(ClaimTypes.Name,model.UserName) ,

  new Claim(ClaimTypes.NameIdentifier,model.UserId.ToString()
)

var Identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
Identity.AddClaims(claims);
          
            //init the identity instances 
var userPrincipal = new ClaimsPrincipal(Identity);  };
  await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTimeOffset.Now.AddMinutes(ApplicationEnvironments.Site.SessionTimeout),
                IsPersistent = true,
                AllowRefresh = true
            });

退出使用

HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme)