zoukankan      html  css  js  c++  java
  • .net core 使用ClaimsIdentity实现登录授权

    一、新建用户

    1、先新建一个用户表,用户存储用户信息。

     1     public class UserInfo
     2     {
     3         public const string Salt = "cesi";
     4         [Key]
     5         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
     6         public Guid Id { get; set; }
     7         [Required]
     8         public string UserName { get; set; }
     9         [Required]
    10         public string PassWord { get; set; }
    11         public string CreateTime { get; set; }
    12     }

    2、新建一个添加用户的接口,添加一个用户,方便后面测试。

     1         [HttpPost]
     2         public async Task<IActionResult> AddUser([FromForm]UserInfo model)
     3         {
     4             if (_context.UserInfo.Any(s => model.UserName.Equals(s.UserName)))
     5             {
     6                 return Ok(new
     7                 {
     8                     code = ResultCode.Error,
     9                     message = "用户名称已存在,请确认!"
    10                 });
    11             }
    12             model.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    13             var pwd = model.PassWord;
    14             var passWordAndSaltBytes = Encoding.UTF8.GetBytes(pwd + UserInfo.Salt);
    15             var hashBytes = new SHA256Managed().ComputeHash(passWordAndSaltBytes);
    16             string hashString = Convert.ToBase64String(hashBytes);
    17             model.PassWord = hashString;
    18             await _context.AddAsync(model);
    19             await _context.SaveChangesAsync();
    20             return Ok(new
    21             {
    22                 code = ResultCode.Success,
    23                 message = "创建用户信息成功!"
    24             });
    25         }

    3、调用接口添加用户信息。

    二、实现用户登录

    1、实现用户登录

     1         [HttpPost("login")]
     2         public async Task<IActionResult> Login([FromForm]LoginModel model)
     3         {
     4             var passWordAndSaltBytes = Encoding.UTF8.GetBytes(model.PassWord + UserInfo.Salt);
     5             var hashBytes = new SHA256Managed().ComputeHash(passWordAndSaltBytes);
     6             string hashString = Convert.ToBase64String(hashBytes);
     7             var userInfo = _context.UserInfo.AsNoTracking().FirstOrDefault(p => p.UserName == model.UserName && p.PassWord == hashString);
     8             if (userInfo == null)
     9             {
    10                 return Ok(new { code = ResultCode.NotLogin, message = "用户名或密码错误" });
    11             }
    12             var httpcontext = _httpContextAccessor.HttpContext;
    13             var claimsIdentity = new ClaimsIdentity("Cookie");
    14             claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()));
    15             claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, model.UserName));
    16             var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
    17             await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
    18             return Ok(new { code = ResultCode.Success, message = "登录成功", data = userInfo });
    19         }

    2、调用登录接口,测试

    三、Setup配置

     1         public void ConfigureServices(IServiceCollection services)
     2         {
     3             services.Configure<CookiePolicyOptions>(options =>
     4             {
     5                 options.CheckConsentNeeded = context => true;
     6                 options.MinimumSameSitePolicy = SameSiteMode.None;
     7             });
     8             services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
     9             .AddCookie(options =>
    10             {
    11                 options.LoginPath = "/api/Login/Index";
    12                 options.AccessDeniedPath = "/api/Login/Denied";
    13             });
    14             services.AddSession(options =>
    15             {
    16                 options.IdleTimeout = TimeSpan.FromSeconds(10);
    17                 options.Cookie.HttpOnly = true;
    18             });
    19             services.AddCors(options =>
    20             {
    21                 string[] CorsOrigins = Configuration["CorsOrigins"].Split(';');
    22                 options.AddPolicy("AnyCors",
    23                     policy => policy.WithOrigins(CorsOrigins)
    24                     .AllowAnyHeader()
    25                     .AllowAnyMethod()
    26                     .AllowCredentials());
    27             });
    28             string connecttext = Configuration.GetConnectionString("Sqlite");
    29             services.AddDbContext<SqlContext>(options => options.UseSqlite(connecttext), ServiceLifetime.Singleton);
    30             services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    31             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    32         }
    33         
    34         public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    35         {
    36             if (env.IsDevelopment())
    37             {
    38                 app.UseDeveloperExceptionPage();
    39             }
    40             else
    41             {
    42                app.UseHsts();
    43             }
    44             app.UseAuthentication();
    45             app.UseCors("AnyCors");
    46             app.UseHttpsRedirection();
    47             app.UseCookiePolicy();
    48             app.UseStaticFiles();
    49             app.UseMvc();
    50         }
  • 相关阅读:
    撩课-Web大前端每天5道面试题-Day15
    撩课-Web大前端每天5道面试题-Day14
    撩课-Java每天5道面试题第26天
    撩课-Java每天5道面试题第25天
    撩课-Web大前端每天5道面试题-Day13
    撩课-Java每天5道面试题第24天
    撩课-每天刷Web面试题(前10天汇总)-Day12
    撩课-Java每天5道面试题第23天
    撩课-Web大前端每天5道面试题-Day11
    java设计模式-策略模式
  • 原文地址:https://www.cnblogs.com/zhangjd/p/11332558.html
Copyright © 2011-2022 走看看