.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、调用接口添加用户信息。

二、实现用户登录
1、实现用户登录
[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();
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 core 使用ClaimsIdentity实现登录授权的更多相关文章
- ASP.Net Core 2.1+ Cookie 登录授权验证【简单Cookie验证】
介绍 本文章发布于博客园:https://www.cnblogs.com/fallstar/p/11310749.html 作者:fallstar 本文章适用于:ASP.NET Core 2.1 + ...
- Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- net core体系-web应用程序-4asp.net core2.0 项目实战(1)-12基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- Asp .Net Core 2.0 登录授权以及多用户登录
用户登录是一个非常常见的应用场景 .net core 2.0 的登录方式发生了点变化,应该是属于是良性的变化,变得更方便,更容易扩展. 配置 打开项目中的Startup.cs文件,找到Configur ...
- Asp .Net Core 2.0 登录授权以及前后台多用户登录
用户登录是一个非常常见的应用场景 .net core 2.0 的登录方式发生了点变化,应该是属于是良性的变化,变得更方便,更容易扩展. 配置 打开项目中的Startup.cs文件,找到Configur ...
- 零开始:NetCore项目权限管理系统:登录授权
喜欢NetCore的朋友,欢迎加群QQ:86594082 源码地址:https://github.com/feiyit/SoaProJect 管理员的模型 namespace FytSoa.Core. ...
- 使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)——第1部分
原文:使用JWT的ASP.NET CORE令牌身份验证和授权(无Cookie)--第1部分 原文链接:https://www.codeproject.com/Articles/5160941/ASP- ...
- .NET Core中的鉴权授权正确方式(.NET5)
一.简介 前后端分离的站点一般都会用jwt或IdentityServer4之类的生成token的方式进行登录鉴权.这里要说的是小项目没有做前后端分离的时站点登录授权的正确方式. 一.传统的授权方式 这 ...
- 网站微信登录授权 ASP.NET
最新做一些项目都有微信登录注册什么的,今天就把自己整理的demo提供给大家 微信认证流程(我自己简称三次握手): 1.用户同意授权,获取code 2.通过code换取网页授权access_token, ...
随机推荐
- C# 异步的简单用法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- override关键字
https://www.cnblogs.com/xinxue/p/5471708.html 2 重写 (override) 在 1.2.2 中提到 override 关键字,可以避免派生类中忘记重写 ...
- 历史相关API
一.history对象 ①history.back()移动到上一个访问页面,等同于浏览器的后退键. ②history.forward()动到下一个访问页面,等同于浏览器的前进键. ③history.g ...
- Bzoj 4147: [AMPPZ2014]Euclidean Nim(博弈)
4147: [AMPPZ2014]Euclidean Nim Time Limit: 1 Sec Memory Limit: 256 MB Description Euclid和Pythagoras在 ...
- 网络请求之get post
——http get和post的区别? 1.get用于获取数据,post用于提交数据 2.get提交参数追加在url后面,post参数可以通过http body提交 3.get的url会有长度上的限制 ...
- react 通过 xlink 方式引用 iconfont
项目中采用 xlink 的方式引用 iconfont 文件,在正常的 html 文件中可以正常引用,但是在 react 下确不可以运行. 经过查找,发现需要更改如下 引入的属性默认为 xlink-hr ...
- shell编程题(四)
编译当前目录下的所有.c文件 #!/bin/bash ] ;] 输入参数个数 echo "Please follow up file.c!" echo "eg: ./ma ...
- [nginx]nginx的一个奇葩问题 500 Internal Server Error phpstudy2018 nginx虚拟主机配置 fastadmin常见问题处理
[nginx]nginx的一个奇葩问题 500 Internal Server Error 解决方案 nginx 一直报500 Internal Server Error 错误,配置是通过phpstu ...
- 微信小程序 图片设置为圆形
要图片圆形显示,需要设置border-radius:50%,还要设置overflow:hidden,具体如下: Tip:user-avatar是图片控件的class .user-avatar { wi ...
- input的禁止标签
<body> <input type="text" name="" value="你好" disabled="d ...