.net core 登陆授权
.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");
var pwd = model.PassWord;
var passWordAndSaltBytes = Encoding.UTF8.GetBytes(pwd + UserInfo.Salt);
var hashBytes = new SHA256Managed().ComputeHash(passWordAndSaltBytes);
string hashString = Convert.ToBase64String(hashBytes);
model.PassWord = hashString;
await _context.AddAsync(model);
await _context.SaveChangesAsync();
return Ok(new
{
code = ResultCode.Success,
message = "创建用户信息成功!"
});
}
复制代码
3、调用接口添加用户信息
二、实现用户登录
[HttpPost("login")]
public async Task<IActionResult> Login([FromForm]LoginModel model)
{
var passWordAndSaltBytes = Encoding.UTF8.GetBytes(model.PassWord + UserInfo.Salt);
var hashBytes = new SHA256Managed().ComputeHash(passWordAndSaltBytes);
string hashString = Convert.ToBase64String(hashBytes);
var userInfo = _context.UserInfo.AsNoTracking().FirstOrDefault(p => p.UserName == model.UserName && p.PassWord == hashString);
if (userInfo == null)
{
return Ok(new { code = ResultCode.NotLogin, message = "用户名或密码错误" });
}
var httpcontext = _httpContextAccessor.HttpContext;
var claimsIdentity = new ClaimsIdentity("Cookie");
claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userInfo.Id.ToString()));
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配置
复制代码
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/api/Login/Index";
options.AccessDeniedPath = "/api/Login/Denied";
});
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
});
services.AddCors(options =>
{
string[] CorsOrigins = Configuration["CorsOrigins"].Split(';');
options.AddPolicy("AnyCors",
policy => policy.WithOrigins(CorsOrigins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
string connecttext = Configuration.GetConnectionString("Sqlite");
services.AddDbContext<SqlContext>(options => options.UseSqlite(connecttext), ServiceLifetime.Singleton);
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
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();
}
本文来自博客园,作者:.net&new,转载请注明原文链接:https://www.cnblogs.com/wugh8726254/p/14878442.html