.net core 基于Claim登陆验证

网站,首先须要安全,实现安全就必须使用登陆验证,.net core 基于Claim登陆验证就很简单使用。安全

Claim是什么,能够理解为你的身份证的中的名字,性别等等的每一条信息,而后Claim组成一个ClaimIdentity 就是组成一个身份证。服务器

那么咱们.net core 是如何基于Claim实现登陆验证呢cookie

首先咱们须要在startup中配置:app

        public void ConfigureServices(IServiceCollection services)
        {           
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                  .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
                  {
                      o.LoginPath = new PathString("/Login"); // 登陆页面的url
                      o.AccessDeniedPath = new PathString("/Login");//没有受权跳转的页面
                      o.ExpireTimeSpan = TimeSpan.FromHours(0.5); // cookies的过时时间
                  });
}
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseAuthentication();   //添加中间件
        }

而后咱们须要在咱们的登陆用户名和密码的表中添加这个字段async

        /// <summary>
        /// 属性标识此身份验证模块实现的身份验证类型
        /// </summary>
        public string AuthenticationType { get; internal set; }

而后咱们在登陆的控制器写登陆方法ide

        /// <summary>
        /// 登陆
        /// </summary>
        /// <param name="name">用户名</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        [HttpGet("login/{name}/{password}")]
        public async Task<IActionResult> Login(string name, string password)
        {
            var user = userLogicHandler.GetUsers(name, password);
            if (user !=null)
            {
                user.AuthenticationType = CookieAuthenticationDefaults.AuthenticationScheme;
                var identity = new ClaimsIdentity(user.AuthenticationType);
                identity.AddClaim(new Claim(ClaimTypes.Name, user.UserId));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                return Ok(200);
            }
            else
            {
                return Ok(500);
            }
        }

登陆的时候上传密码和名称到服务器中,若是匹配,那么服务器会将ClaimsIdentity保存到客户端中的cookies中,而后每次请求须要验证的控制器的时候就会验证是否有ClaimIdentity。网站

    [Hidden]
    [Route("Home")]
    [Authorize]
    public class HomeController : Controller
    {
        /// <summary>
        /// 主界面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Home()
        {
            return View();
        }

如上,加上[Authorize] 特性以后,每次请求该控制器的方法都会验证。ui

基于Claim的登陆验证就是这些,若是有错误请指正。
相关文章
相关标签/搜索