在ASP.NET Core 2.0中使用CookieAuthentication

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.