Model文件夹下新建三个类LoginResult,LoginRequest,AuthInfo
根据自己业务进行修改
public class LoginResult
{
public bool Success { get; set; }
public string Token { get; set; }
public string Message { get; set; }
}
public class LoginRequest
{
public string UserName { get; set; }
public string Password { get; set; }
}
public class AuthInfo
{
//模拟JWT的payload
public string UserName { get; set; }
public List<string> Roles { get; set; }
public bool IsAdmin { get; set; }
/// <summary>
/// 过期时间
/// </summary>
public string ExpirationTime { get; set; }
}
用户登录方法登录方法,
将秘钥和数据用Encode进行加密,然后Return出去
Header里加入 auth:Token 值
注:每次访问必须添加
我这里为了方便测试所以用了GET
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
//using JwtWebApi.Models;
using System;
using System.Collections.Generic;
using System.Web.Http;
namespace DMSAPI.Controllers
{
public class SignInController : ApiController
{
[HttpGet]
public LoginResult Post()
{
LoginResult rs = new LoginResult();
//这是是获取用户名和密码的,这里只是为了模拟
AuthInfo info = new AuthInfo { UserName = "wangshibang", Roles = new List<string> { "Admin", "Manage" }, IsAdmin = true ,ExpirationTime=DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") };
try
{
const string secret = "To Live is to change the world";
//secret需要加密
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
var token = encoder.Encode(info, secret);
rs.Message = "XXXXX";
rs.Token = token;
rs.Success = true;
}
catch (Exception ex)
{
rs.Message = ex.Message;
rs.Success = false;
}
return rs;
}
}
}
项目下添加一个Attributes文件夹,需要写个权限拦截器,新建一个ApiAuthorizeAttribute类继承自AuthorizeAttribute类
每次
在此你可以根据你的业务来写,我这是个例子所以只是简单的加了时间控制
using DMSAPI.Models;
using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Controllers;
namespace JwtWebApi.Attributes
{
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var authHeader = from t in actionContext.Request.Headers where t.Key == "auth" select t.Value.FirstOrDefault();
if (authHeader != null)
{
string token = authHeader.FirstOrDefault();
if (!string.IsNullOrEmpty(token))
{
try
{
const string secret = "To Live is to change the world";
//secret需要加密
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var json = decoder.DecodeToObject<AuthInfo>(token, secret, verify: true);
if (json != null)
{
if (Convert.ToDateTime(json.ExpirationTime) < DateTime.Now.AddHours(2) && !string.IsNullOrEmpty(json.ExpirationTime) )
{
actionContext.RequestContext.RouteData.Values.Add("auth", json);
return true;
}
else return true;
}
return false;
}
catch (Exception ex)
{
return false;
}
}
}
return false;
}
}
}
创建一个控制器可以写接下来的方法 在前面加入[ApiAuthorize],就会在拦截器里自动验证Token
[ApiAuthorize]
[HttpGet]
public string Get11()
{
AuthInfo info = RequestContext.RouteData.Values["auth"] as AuthInfo;
if (info == null)
{
return "获取不到,失败";
}
else
{
return $"获取到了,Auth的Name是 {info.UserName}";
}
}
转载:https://www.cnblogs.com/wangyulong/p/8727683.html
注:原文章在Token反编译时IJwtDecoder使用JWT 4.0,而我的用的JWT7.2所以传入参数有所不同