.Net Core MVC 基于Cookie进行用户认证
在打代码之前先说一下思路。
登录的的时候服务端生成加密的字符串(用户名、id、当前时间)并且存入客户端cookie中,服务端的缓存中。对客户端的每次请求进行拦截,解密保存在cookie中的加密字符串。查看是否已过期,如果已过期跳转到登录页,并且删除cookie与缓存中的数据。如未过期修改缓存中的时间,并进行下一步操作。
加密解密的代码
引入包:Microsoft.Extensions.Configuration(读配置文件的时候会用到,加密key与解密key最好存在配置文件中,从配置文件中读取)
public class Encryption
{
private IConfiguration _configuration;
public Encryption(IConfiguration configuration)
{
_configuration = configuration;
} public byte[] EncrKey()
{
return ASCIIEncoding.ASCII.GetBytes(_configuration["MD5:EncrKey"]);
}
public byte[] DecrKey()
{
return ASCIIEncoding.ASCII.GetBytes(_configuration["MD5:DecrKey"]);
} /// <summary>
/// DES加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public async Task<string> Encrypt(string str)
{
MemoryStream ms = null;
CryptoStream cs = null;
StreamWriter sw = null; DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
var s= ASCIIEncoding.ASCII.GetBytes(_configuration["MD5:EncrKey"]);
ms = new MemoryStream();
cs = new CryptoStream(ms, des.CreateEncryptor(this.EncrKey(), this.DecrKey()), CryptoStreamMode.Write);
sw = new StreamWriter(cs);
sw.Write(str);
sw.Flush();
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.GetBuffer(), , (int)ms.Length);
}
finally
{
if (sw != null) sw.Close();
if (cs != null) cs.Close();
if (ms != null) ms.Close();
}
} /// <summary>
/// DES解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public async Task<string> Decrypt(string str)
{
MemoryStream ms = null;
CryptoStream cs = null;
StreamReader sr = null; DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
ms = new MemoryStream(Convert.FromBase64String(str));
cs = new CryptoStream(ms, des.CreateDecryptor(this.EncrKey(), this.DecrKey()), CryptoStreamMode.Read);
sr = new StreamReader(cs);
return sr.ReadToEnd();
}
finally
{
if (sr != null) sr.Close();
if (cs != null) cs.Close();
if (ms != null) ms.Close();
}
}
}
操作Redis
引入包:StackExchange.Redis
连接字符串最好也存入配置文件中
public class RedisContent
{
public StackExchange.Redis.ConnectionMultiplexer Redis = null;
public StackExchange.Redis.IDatabase db = null; public RedisContent(IConfiguration configuration)
{
_configuration = configuration;
this.Redis = ConnectionMultiplexer.Connect($"{_configuration["Redis:dbconn"]}");
this.db = this.Redis.GetDatabase();
}
private IConfiguration _configuration;
}
定义一个特性类,对于一些不需要认证的接口,加上这个特性即可。相当于微软的[AllowAnonymous]认证中间件。这里的话我们自己写一个。
public class AllowAuthAttribute : Attribute
{
}
添加过滤器AuthorizeFilter。上面封装的一些方法,全部以注入的形式进行使用。
public class AuthorizeFilter : Attribute, IAuthorizationFilter
{
private readonly ILogger<AuthorizeFilter> _logger;
private readonly RedisContent _content;
private readonly Encryption _encryption;
public AuthorizeFilter(RedisContent content,
Encryption encryption,
ILogger<AuthorizeFilter> logger)
{
_content = content;
_encryption = encryption;
_logger = logger;
} public void OnAuthorization(AuthorizationFilterContext context)
{
var isDefined = false;
var controllerActionDescriptor = context.ActionDescriptor as ControllerActionDescriptor;
if (controllerActionDescriptor != null)
{
//判断请求的控制器和方法有没有加上AllowAuthAttribute(不需要认证)
isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
.Any(a => a.GetType().Equals(typeof(AllowAuthAttribute)));
}
if (isDefined) return;
if (context.HttpContext.Request.Path == "/")
return;
string value = string.Empty;
context.HttpContext.Request.Cookies.TryGetValue("userinfo", out value);
if (string.IsNullOrEmpty(value))
context.HttpContext.Response.Redirect("https://localhost:44300/");
else
{
//解密cookie
var decryptValueArray = _encryption.Decrypt(value).Result.Split("|");
string user = _content.db.StringGet($"{decryptValueArray[0]}-{decryptValueArray[2]}");
if (string.IsNullOrEmpty(user) || !user.Equals(value))
{
_logger.LogError($"Token已过期/有误! Url:{context.HttpContext.Request.Path}");
context.HttpContext.Response.Cookies.Delete("userinfo");
context.HttpContext.Response.Redirect("https://localhost:44300/");
}
else
{
//重新设置key的时间
_content.db.KeyExpire($"{decryptValueArray[0]}-{decryptValueArray[2]}", TimeSpan.FromMinutes());
return;
}
}
}
}
编写控制器中的代码
/// <summary>
/// 验证登录 颁发Token 存入cookie
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <returns></returns>
[AllowAuth]
public async Task<IActionResult> LoginUser(string userName, string password)
{
if (string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password))
return Json(new { success = false, msg = "用户名或密码不能为空" });
//带参查询
var data = await _userInfoServices.QueryUserInfo(userName, password);
if (data.Any())
{
//得到uid,将uid也带进token中加密
var uid = data.ToList()[].id;
//加密 30分钟的有效期
var token = await _encryption.Encrypt(userName + "|" + DateTime.Now + "|" + uid + "|" + );
//存入redis中
_content.db.StringSet($"{userName}" + "-" + uid, token, TimeSpan.FromMinutes());
//存入cookie中
Response.Cookies.Append("userinfo", token);
return Json(new { success = true, msg = "登陆成功" });
}
else
{
return Json(new { success = false, msg = "用户名或密码输入错误" });
}
}
如有不足,还望见谅!
.Net Core MVC 基于Cookie进行用户认证的更多相关文章
- Asp.Net Core 2.0 项目实战(10) 基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
- 理解ASP.NET Core - 基于Cookie的身份认证(Authentication)
注:本文隶属于<理解ASP.NET Core>系列文章,请查看置顶博客或点击此处查看全文目录 概述 通常,身份认证(Authentication)和授权(Authorization)都会放 ...
- Laravel 5 中使用 JWT(Json Web Token) 实现基于API的用户认证
在JavaScript前端技术大行其道的今天,我们通常只需在后台构建API提供给前端调用,并且后端仅仅设计为给前端移动App调用.用户认证是Web应用的重要组成部分,基于API的用户认证有两个最佳解决 ...
- JWT 实现基于API的用户认证
基于 JWT-Auth 实现 API 验证 如果想要了解其生成Token的算法原理,请自行查阅相关资料 需要提及的几点: 使用session存在的问题: session和cookie是为了解决http ...
- 5分钟搞懂:基于token的用户认证
https://www.qikegu.com/easy-understanding/880 用户认证 用户认证或者说用户登录是确认某人确实是某人的过程,生活中靠身份证,网络上就要靠账号和密码.用户提供 ...
- 项目一:第十一天 2、运单waybill快速录入 3、权限demo演示-了解 5、权限模块数据模型 6、基于shiro实现用户认证-登录(重点)
1. easyui DataGrid行编辑功能 2. 运单waybill快速录入 3. 权限demo演示-了解 4. Apache shiro安全框架概述 5. 权限模块数据模型 6. 基于shiro ...
- Linux下基于LDAP统一用户认证的研究
Linux下基于LDAP统一用户认证的研究 本文出自 "李晨光原创技术博客" 博客,谢绝转载!
- 基于cookie的用户登录状态管理
cookie是什么 先来花5分钟看完这篇文章:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Cookies 看完上文,相信大家对cookie已经有 ...
- net core体系-web应用程序-4asp.net core2.0 项目实战(1)-12基于cookie登录授权认证并实现前台会员、后台管理员同时登录
1.登录的实现 登录功能实现起来有哪些常用的方式,大家首先想到的肯定是cookie或session或cookie+session,当然还有其他模式,今天主要探讨一下在Asp.net core 2.0下 ...
随机推荐
- hdu1078 dfs+dp(记忆化搜索)搜索一条递增路径,路径和最大,起点是(0,0)
#include<bits/stdc++.h> using namespace std; typedef unsigned int ui; typedef long long ll; ty ...
- JavaWeb----Cookie&Session
## 会话技术 1.会话:一次会话中包含多次请求和响应. * 第一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止. 2.功能:再一次会话的范围内的多次请求间,共享数据 3. ...
- Nuget多项目批量打包上传服务器的简明教程
本篇不会介绍Nuget是什么,如何打包上传Nuget包,怎么搭建私有Nuget服务器.这些问题园子里都有相应的文章分享,这里不做过多阐述.另外本文假设你已经下载了Nuget.exe,并且已经设置好了环 ...
- SecureCRT的主题配置
SecureCRT是用来远程连接服务器终端的常用软件,由于其本身的主题十分难看,故此经过一番查找,确定了自己喜欢的主题配置,下面是记录自己配置的过程. 修改主题样式 SecureCRT修改主题分两 ...
- AI领域:如何做优秀研究并写高水平论文?
来源:深度强化学习实验室 每个人从本科到硕士,再到博士.博士后,甚至工作以后,都会遇到做研究.写论文这个差事.论文通常是对现有工作的一个总结和展示,特别对于博士和做研究的人来说,论文则显得更加重要. ...
- 热点 | 四月最佳Github项目库与最有趣Reddit热点讨论
来源:Analytics Vidhya 编译:磐石 [磐创AI导读]:Github是全球最大的开源代码社区,Reddit是最受大家欢迎的热点讨论交流平台.接下来磐创AI将为大家带来四月份Github最 ...
- K8S 资源收集和展示 top & DashBoard-UI
一.前言 在近期的 K8S 开发调试的过程中,总会想知道 Node 或者 Pod 的更多信息.但 $ kubectl top node $ kubectl top pod 中的 top 操作符,需要 ...
- sql server 数据库安装手册
1. 双击setup.exe运行安装程序,进入[SQL Server 安装中心] 2. 选择左侧菜单栏[安装],运行第一项[全新安装或向现有安装添加功能] 3. 进入[SQL Server 2008 ...
- coding++ :Layui-监听事件
在使用layui的form表单做验证提交的时候,如果结合vue,或者是三级联动的时候,就需要做事件监听了. 具体语法: form.on('event(过滤器值)', callback); 可以用于监听 ...
- Sql Server数据库性能优化之索引
最近在做SQL Server数据库性能优化,因此复习下一索引.视图.存储过程等知识点.本篇为索引篇,知识整理来源于互联网. 索引加快检索表中数据的方法,它对数据表中一个或者多个列的值进行结构排序,是数 ...