1.当用户登录成功,后端给出token存入cookies(可设置过期时间)。
2.用户每次访问这个网站的不同页面或者请求数据的时候,都需要带上这个token进行验证(token存储在数据库中)
token一般由用户名+密码+时间戳组成并且通过加密方式加密(MD5,RSA,DES......)
token也可以根据账户名密码生成guid+时间戳组成并且通过加密方式加密(MD5,RSA,DES......)(好处:保护账户密码)
3.token验证成功后改变token值再存入cookies与数据库(这样做可以确保token是一直在改变,很大程度上防止了xss攻击)
1.重写Attribute中的方法,代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mvc过滤器.Models;
using System.Security.Cryptography;
using System.Text;
namespace mvc过滤器.BaseClass
{
public class MyAttribute: AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
try
{
HttpCookie Token = httpContext.Request.Cookies["Token"];
string token = Token.Value;//获取cookies的token
using (cosonparkEntities db = new cosonparkEntities())
{
var test = db.Test.Where(x => x.Token == token);//核对token是否一致
if (test.ToList().Count > 0)
{
string guid = Guid.NewGuid().ToString();//获取guid
string time = GetTimeStamp();//时间戳
string str = MD5Str(guid + time);//加密
test.FirstOrDefault().Token = str;
db.SaveChanges();//修改数据库token
HttpCookie tk = new HttpCookie("Token", str);
tk.Expires = DateTime.Now.AddSeconds(30);
httpContext.Response.Cookies.Add(tk);//更新cookies中的token
return true;
}
else
{
return false;
}
}
}
catch (Exception ex)
{
return false;
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.HttpContext.Response.Redirect("/Login/Index");
base.HandleUnauthorizedRequest(filterContext);
}
public string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
public static string MD5Str(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.Default.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
}
}
2.在需要验证的地方使用即可,如:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mvc过滤器.BaseClass;
namespace mvc过滤器.Controllers
{
public class HomeController : Controller
{
[My]//MyAttribute可简写为My
public ActionResult Index()
{
return View();
}
}
}
Tips:这样使用的话,每次打开这个页面都会进行验证,如果验证通过就打开页面,若是不通过就回返回登录页面
1.MD5加密:
public static string MD5Str(string txt)
{
using (MD5 mi = MD5.Create())
{
byte[] buffer = Encoding.Default.GetBytes(txt);
//开始加密
byte[] newBuffer = mi.ComputeHash(buffer);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < newBuffer.Length; i++)
{
sb.Append(newBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
2.RSA加密:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace mvc过滤器.BaseClass
{
public class RSA
{
#region RSA 的密钥产生
///
/// RSA产生密钥
///
/// 私钥
/// 公钥
public static void RSAKey(out string xmlKeys, out string xmlPublicKey)
{
try
{
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
xmlKeys = rsa.ToXmlString(true);
xmlPublicKey = rsa.ToXmlString(false);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region RSA加密函数
//##############################################################################
//RSA 方式加密
//KEY必须是XML的形式,返回的是字符串
//该加密方式有长度限制的!
//##############################################################################
///
/// RSA的加密函数
///
/// 公钥
/// 待加密的字符串
///
public static string RSAEncrypt(string xmlPublicKey, string encryptString)
{
try
{
byte[] PlainTextBArray;
byte[] CypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);
CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
///
/// RSA的加密函数
///
/// 公钥
/// 待加密的字节数组
///
public string RSAEncrypt(string xmlPublicKey, byte[] EncryptString)
{
try
{
byte[] CypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPublicKey);
CypherTextBArray = rsa.Encrypt(EncryptString, false);
Result = Convert.ToBase64String(CypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region RSA的解密函数
///
/// RSA的解密函数
///
/// 私钥
/// 待解密的字符串
///
public static string RSADecrypt(string xmlPrivateKey, string decryptString)
{
try
{
byte[] PlainTextBArray;
byte[] DypherTextBArray;
string Result;
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
PlainTextBArray = Convert.FromBase64String(decryptString);
DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
///
/// RSA的解密函数
///
/// 私钥
/// 待解密的字节数组
///
public string RSADecrypt(string xmlPrivateKey, byte[] DecryptString)
{
try
{
byte[] DypherTextBArray;
string Result;
System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
rsa.FromXmlString(xmlPrivateKey);
DypherTextBArray = rsa.Decrypt(DecryptString, false);
Result = (new UnicodeEncoding()).GetString(DypherTextBArray);
return Result;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
3.DES加密:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
namespace mvc过滤器.BaseClass
{
public class DES
{
///
/// 加密函数
///
/// 密钥
/// 需要加密的字符串
///
public static string DesEncrypt(string key, string encryptString)
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateEncryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
///
/// 解密函数
///
/// 密钥
/// 需要解密的字符串
///
public static string DesDecrypt(string key, string decryptString)
{
try
{
byte[] keyBytes = Encoding.UTF8.GetBytes(key.Substring(0, 8));
byte[] keyIV = keyBytes;
byte[] inputByteArray = Convert.FromBase64String(decryptString);
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
CryptoStream cStream = new CryptoStream(mStream, provider.CreateDecryptor(keyBytes, keyIV), CryptoStreamMode.Write);
cStream.Write(inputByteArray, 0, inputByteArray.Length);
cStream.FlushFinalBlock();
return Encoding.UTF8.GetString(mStream.ToArray());
}
catch (Exception ex)
{
return "";
}
}
}
}
4.GUID获取:
string guid = Guid.NewGuid().ToString();
5.时间戳获取:
///
/// 获取时间戳
///
///
public string GetTimeStamp()
{
TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}