標籤:sde user map action 1.0 ati msi etc default
在ASP.NET Core中關於Security有兩個容易混淆的概念一個是Authentication(認證),一個是Authorization(授權)。而前者是確定使用者是誰的過程,後者是圍繞著他們允許做什麼,今天的主題就是關於在ASP.NET Core 2.0中如何使用CookieAuthentication認證。
在ASP.NET Core 2.0中使用CookieAuthentication跟在1.0中有些不同,需要在ConfigureServices和Configure中分別設定,前者我們叫註冊服務,後者我們叫註冊中介軟體
public void ConfigureServices(IServiceCollection services){ services.AddCookieAuthentication(options => { options.ExpireTimeSpan = TimeSpan.FromDays(2);
// Other options }); services.AddMvc(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); // 因為是後台系統,必須登陸以後才能操作 options.Filters.Add(new AuthorizeFilter(policy)); });}
public void Configure(IApplicationBuilder app, IHostingEnvironment env){ if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles();
// 使用Authentication中介軟體 app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); });}
在上面的services.AddCookieAuthentication中只是指定一下到期時間,如果沒有任何參數,系統會為某些屬性指定預設值
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";}
根據微軟的命名規範在ConfigureServices統一使用Add***,在Configure統一使用Use***
登陸代碼
public async Task<IActionResult> LoginDo(){ var user = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, "bob") },CookieAuthenticationDefaults.AuthenticationScheme)); await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, user); return Redirect("/");}
登出代碼
public async Task<IActionResult> Logout(){ await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme); return Redirect("/");}
在ASP.NET Core 2.0中使用CookieAuthentication