1,在asp.net mvc 中常用的是 Cooke+Session 或者 form 认证(实际也是Cooke)的方式,当然都是mvc中在 webapi中也是可以使用的,那么上面的两种方式这里就不多写了,后面有时间写,今天最主要是 JWT的认证方式
2,简单说明一下,JWT是什么。JWT 全称 JSON Web Tokens ,是一种规范化的 token。是对 token 这一技术提出一套规范,其它细节,查资料就可。
3,使用,.NET里面可以使用JWT来生成Token以及解密Token。我们打开Nuget,搜索JWT 安装。
4,既然是根据同koken去获取权限,那么第一个就是去获取token
private string secret = "zhonlong"; //这个密钥以一般用加密过的
public string Get()
{
IDateTimeProvider provider = new UtcDateTimeProvider();
var now = provider.GetNow();
var unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); // or use JwtValidator.UnixEpoch
var secondsSinceEpoch = Math.Round((now - unixEpoch).TotalSeconds);
var payload = new Dictionary<string, object>
{
{"name", "MrBug" },
{"exp",secondsSinceEpoch+1000 }, // 1000 秒过期时间,必须大于签发时间
{"jti","luozhipeng" }
};
Console.WriteLine(secondsSinceEpoch);
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(payload, secret);
return token;
}
5,那么下次访问服务端的时候,获取到了token之后验证一下
//解密token
public string DecodeToken()
{
try
{
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var json = decoder.Decode("密钥", secret, verify: true);//token为之前生成的字符串
}
catch (TokenExpiredException)
{
Console.WriteLine("Token has expired"); //过期
}
catch (SignatureVerificationException)
{
Console.WriteLine("Token has invalid signature"); //签名没有验证
}
return "value"; // 根据你的json 里面解析出数据,然后去验证一下数据(当然这一步放到了验证中)
}
6,最后别忘记了加上验证
public class TokenAuthAttribute : AuthorizeAttribute
{
//重写基类的验证方式,加入我们自定义的Ticket验证
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//url获取token
var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
var token = content.Request.Headers["Token"]; //自己加入在头部的名称
if (!string.IsNullOrEmpty(token))
{
//解密用户ticket,并校验用户名密码是否匹配
if (ValidateTicket(token))
{
base.IsAuthorized(actionContext);
}
else
{
HandleUnauthorizedRequest(actionContext);
}
}
//如果取不到身份验证信息,并且不允许匿名访问,则返回未验证401
else
{
var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
if (isAnonymous) base.OnAuthorization(actionContext);
else HandleUnauthorizedRequest(actionContext);
}
}
//校验票据(数据库数据匹配)
private bool ValidateTicket(string encryptToken)
{
//正常这里是用的token 来验证的
bool flag = false;
try
{
//获取数据库Token
if ("jiaxiel" == encryptToken) //存在
{
//未超时
flag = true;
}
}
catch (Exception ex)
{
}
return flag;
}
}
到此基本的验证授权都给上了,还需要优化!
下载地址:https://download.csdn.net/download/weixin_42780928/12264868