webapi使用jwt做权限验证
2021-03-18 08:24
标签:rom auth object author datetime else pass webapi sum 考虑到很多公司目前并没有切换到.netcore,所有本文尝试使用.netframework下的webapi 首先使用Nuget 安装 jwt包 安装完成后,创建 jwt的帮助类 然后创建相关的Model 创建获取token的api 创建验证token的filter 最后把特性加到需要需要验证的Action上 然后进行测试,首先获取token 调用接口,并传入token值 如果不传入token值,那么会报401错误 当然了,那个401错误其实是在filter里自己定义的,你改成别的状态码也是可以的,不过尽量还是要遵循国际惯例了 webapi使用jwt做权限验证 标签:rom auth object author datetime else pass webapi sum 原文地址:https://www.cnblogs.com/bjjjunjie/p/12361023.htmlpublic class JwtToken
{
static IJwtAlgorithm algorithm = new HMACSHA256Algorithm();//HMACSHA256加密
static IJsonSerializer serializer = new JsonNetSerializer();//序列化和反序列
static IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();//Base64编解码
static IDateTimeProvider provider = new UtcDateTimeProvider();//UTC时间获取
const string secret = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4aKpVo2OHXPwb1R7duLgg";//服务端
///
public class LoginResult
{
public bool Success { get; set; }
public string Token { get; set; }
public string Message { get; set; }
}
public LoginResult Post([FromBody]LoginRequest request)
{
LoginResult rs = new LoginResult();
//这是是获取用户名和密码的,这里只是为了模拟
if (request.UserName == "admin" && request.Password == "123456")
{
try
{
var payload = new Dictionarystring, object>
{
{ "username","admin"},//发行人
{ "exp", DateTimeOffset.UtcNow.AddSeconds(100).ToUnixTimeSeconds() },//到期时间
};
rs.Token = JwtToken.CreateJWT(payload);
rs.Success = true;
}
catch (Exception ex)
{
rs.Message = ex.Message;
rs.Success = false;
}
}
else
{
rs.Message = "fail";
rs.Success = false;
}
return rs;
}
public class ApiAuthorizeAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var attr = actionContext.ActionDescriptor.GetCustomAttributes().OfType();
bool isAnonymous = attr.Any(a => a is AllowAnonymousAttribute);
if (!isAnonymous)
{
var rq= actionContext.Request.Properties;
var authorization = actionContext.Request.Headers.Authorization;
if (authorization==null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
string ResultMessage;//需要解析的消息
string Payload;//获取负载
var result = JwtToken.ValidateJWT(authorization.Scheme, out Payload, out ResultMessage); //TokenManager.ValidateToken(authorization.Scheme);
if (!result)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
}
}
// GET: User
[ApiAuthorize]
public string Get()
{
return $"获取到了";
}
上一篇:软件包,API,SDK的区别