[.Net Core] - 当 .Net Core 版本由 1.x 升级至 2.x 后,Cookie 使用方式变更

背景

Asp.Net Core 项目升级至 2.x 版本后,Cookie 验证方式需要进行更新。

升级前:.Net Core 1.x

Startup.cs

复制代码
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Other Options ...
// IMPORTANT: UseCookieAuthentication() MUST before UseMvc()
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new PathString("/Home/Index/"),
        AccessDeniedPath = new PathString("/Home/AccessDenied/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookiePath = "/"
    });

    // Add MVC to the request pipeline.
    app.UseMvc(routes =>
    {
        routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
    });
}
复制代码

Login

复制代码
var claims = new List<Claim>
{
    new Claim(ClaimTypes.Email, user.Email),
    new Claim(ClaimTypes.Name, user.Name),
    new Claim(ClaimTypes.Sid, Convert.ToString(user.Gid))
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "AccountLogin"));
var property = new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddHours(1) };
await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal, property);
return RedirectToAction(nameof(LoginController.Index), "Candidate");
复制代码

Logout

HttpContext.Session.Clear();
await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
return RedirectToAction(nameof(HomeController.Index), "Home");

升级后:.Net Core 2.x

Startup.cs

复制代码
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("MyCookieAuthenticationScheme")
            .AddCookie("MyCookieAuthenticationScheme", options => {
                options.SlidingExpiration = false;
                options.ExpireTimeSpan = TimeSpan.FromHours(1);
                options.Cookie = new CookieBuilder { HttpOnly = true, Name = "MyCookie", Path = "/" };
                options.LoginPath = "/Home/Index/";
                options.AccessDeniedPath = "/Home/AccessDenied/";
            });
    services.AddMvc();
// Other Options ... } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { // Other Options ...
app.UseAuthentication();
// Add MVC to the request pipeline. app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); }); }
复制代码

Login

复制代码
var claims = new List<Claim>
{
    new Claim(ClaimTypes.Email, user.Email),
    new Claim(ClaimTypes.Name, user.Name),
    new Claim(ClaimTypes.Sid, Convert.ToString(user.Gid))
};
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "AccountLogin"));
await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);
return RedirectToAction(nameof(CandidateController.Index), "Candidate");
复制代码

Logout

HttpContext.Session.Clear();
await HttpContext.SignOutAsync("MyCookieAuthenticationScheme");
return RedirectToAction(nameof(HomeController.Index), "Home");

参考资料(了解更多细节

https://www.cnblogs.com/tdfblog/p/aspnet-core-security-authentication-cookie.html

posted @   jinzesudawei  阅读(411)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示