8 24 81

.net core 基于Claim登录验证

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

Claim是什么,可以理解为你的身份证的中的名字,性别等等的每一条信息,然后Claim组成一个ClaimIdentity 就是组成一个身份证。

那么我们.net core 是如何基于Claim实现登录验证呢

首先我们需要在startup中配置:

        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();   //添加中间件
        }

然后我们需要在我们的登录用户名和密码的表中添加这个字段

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

然后我们在登录的控制器写登录方法

        /// <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] 特性之后,每次请求该控制器的方法都会验证。

基于Claim的登录验证就是这些,如果有错误请指正。
posted @ 2019-04-15 16:18  Ivan_Ivan  阅读(2430)  评论(2编辑  收藏  举报