zoukankan      html  css  js  c++  java
  • [转]Asp.Net Core 简单的使用加密的Cookie保存用户状态

    本文转自:http://www.cnblogs.com/Joes/p/6023820.html

    在以前的Asp.Net中可以用 FormsAuthentication 类的一系列方法来使用加密的Cookie存储用户身份,使用简单,可控性强。在Asp.Net Core中是否也可以的?答案是当然的。

    使用步骤:

    1、在 project.json 中添加项目依赖 "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"

    复制代码
    "dependencies": {
        "Microsoft.NETCore.App": {
          "version": "1.0.1",
          "type": "platform"
        },
        "Microsoft.AspNetCore.Diagnostics": "1.0.0",
        "Microsoft.AspNetCore.Mvc": "1.0.1",
        "Microsoft.AspNetCore.Razor.Tools": {
          "version": "1.0.0-preview2-final",
          "type": "build"
        },
        "Microsoft.AspNetCore.Routing": "1.0.1",
        "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
        "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
        "Microsoft.AspNetCore.StaticFiles": "1.0.0",
        "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
        "Microsoft.Extensions.Configuration.Json": "1.0.0",
        "Microsoft.Extensions.Logging": "1.0.0",
        "Microsoft.Extensions.Logging.Console": "1.0.0",
        "Microsoft.Extensions.Logging.Debug": "1.0.0",
        "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
        "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
        "Microsoft.AspNetCore.Authentication.Cookies": "1.0.0"
      }
    复制代码

    2、在 Startup.cs 中添加中间件:

    复制代码
         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
    
                app.UseStaticFiles();
    
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationScheme = "member",    // Cookie 验证方案名称,后面多处都需要用到,部分地方必须要求常量,所以直接配置为字符串。
                    AutomaticAuthenticate = true,     // 是否自动启用验证,如果不启用,则即便客服端传输了Cookie信息,服务端也不会主动解析。                                 // 除了明确配置了 [Authorize(ActiveAuthenticationSchemes = "上面的方案名")] 属性的地方,才会解析,此功能一般用在需要在同一应用中启用多种验证方案的时候。比如分Area.
                    LoginPath = "/account/login"     // 登录页
                });
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
    复制代码

    3、创建一个新的 Controller,并添加登录的方法,大致如下:

    复制代码
         [AllowAnonymous]
            public async Task<IActionResult> Login()
            {
                // 这里应该写业务逻辑来获取用户名,用户Id等信息。
    
                var userId = 10000;
                var userName = "admin";
    
                // ========================
    
                var identity = new ClaimsIdentity("Forms");     // 指定身份认证类型
    
                identity.AddClaim(new Claim(ClaimTypes.Sid, userId.ToString()));  // 用户Id
    
                identity.AddClaim(new Claim(ClaimTypes.Name, userName));       // 用户名称
    
                var principal = new ClaimsPrincipal(identity);
    
                await HttpContext.Authentication.SignInAsync("member", principal, new AuthenticationProperties { IsPersistent = true });
           string returnUrl = Request.Query["returnUrl"];
           if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl);
           return RedirectToAction("index", "account");
            }
    复制代码

    4、退出登录方法:

    复制代码
            public async Task<IActionResult> Logout()
            {
                await HttpContext.Authentication.SignOutAsync("member");   // Startup.cs中配置的验证方案名
                     return RedirectToAction("index", "home");      }    
    复制代码

    5、获取用户信息:

    复制代码
            [Authorize(ActiveAuthenticationSchemes = "member")]
            public IActionResult Index()
            {
                var userId = User.FindFirst(ClaimTypes.Sid).Value;
    
                var userName = User.Identity.Name;
    
                return Json(new { Id = userId, Name = userName });
            }  
    复制代码

    其它说明:

    这里生成的Cookie是加密过的,大概如下:

    相关的Cookie名称,域,过期时间等都可以在 Startup.cs 中进行设置,大概如下:

    复制代码
                app.UseCookieAuthentication(new CookieAuthenticationOptions
                {
                    AuthenticationScheme = "member",    // 验证方案名
                    AutomaticAuthenticate = true,   // 是否自动启用验证
                    LoginPath = "/account/login",    // 登录地址
                    CookieDomain = "abc.com",       // 验证域
                    CookieName = "abc",             // Cookie 名称
                    CookiePath = "/",               // Cookie 路径
                    ExpireTimeSpan = TimeSpan.FromDays(3),  // 过期时间
                    SlidingExpiration = true,   // 是否在过期时间过半的时候,自动延期
                    CookieHttpOnly = true       // 是否允许客户端Js获取。默认True,不允许。
                });
    复制代码

    步骤很简单,也是极好用的,若结合是否自动启用验证的AutomaticAuthenticate来进行Area分区域认证,灵活性更强。

  • 相关阅读:
    Cygwin一些设置总结!
    【补题】牛客58矩阵消除【数据水的一匹,算法:二进制枚举】
    【补题】牛客58E题(数学)
    [补题]牛客练习56,迷宫【orz】
    【补题】牛客58E题(数学)
    判断两个二叉树是否相同
    判断两个二叉树是否相同
    利用费马小定理求逆元
    [补题]牛客练习56,迷宫【orz】
    【补题】牛客58矩阵消除【数据水的一匹,算法:二进制枚举】
  • 原文地址:https://www.cnblogs.com/freeliver54/p/6259302.html
Copyright © 2011-2022 走看看