.net core 使用ClaimsIdentity实现登录授权
一、新建用户
1、先新建一个用户表,用户存储用户信息。
复制代码
public class UserInfo
{
public const string Salt = "cesi";
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public string UserName { get; set; }
[Required]
public string PassWord { get; set; }
public string CreateTime { get; set; }
}
复制代码
2、新建一个添加用户的接口,添加一个用户,方便后面测试。
复制代码
[HttpPost]
public async Task<IActionResult> AddUser([FromForm]UserInfo model)
{
if (_context.UserInfo.Any(s => model.UserName.Equals(s.UserName)))
{
return Ok(new
{
code = ResultCode.Error,
message = "用户名称已存在,请确认!"
});
}
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));
var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
return Ok(new { code = ResultCode.Success, message = "登录成功", data = userInfo });
}
复制代码
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);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseCors("AnyCors");
app.UseHttpsRedirection();
app.UseCookiePolicy();
app.UseStaticFiles();
app.UseMvc();
}