使用基于 Token 的身份验证方法,在服务端不需要存储用户的登录记录。大概的流程是这样的:
JWT 标准的 Token 有三个部分:
public class JwtHelper
{
private string m_Secret = "BFE7E27E-C1F3-41E0-AAD5-7D14AFC6CD2C";
public string EncodeJwt(LoginInfo userInfo)
{
IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
return encoder.Encode(userInfo, m_Secret);
}
public LoginInfo DecodeJwt(string token)
{
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);
var userInfo = decoder.DecodeToObject(token, m_Secret, verify: true);//token为之前生成的字符串
return userInfo;
}
}
public ActionResult CreateToken(string UserName, string PassWord)
{
if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(PassWord))
throw new Exception("参数为空");
JwtResult jwtResult;
try
{
//var param = HttpContext.Request["UserName"];
//param = HttpContext.Request["PassWord"];
if (!UserName.Equals("test") || !PassWord.Equals("test"))
{
throw new Exception("用户密码不正确。");
}
LoginInfo pUserLoginInfo = new LoginInfo() { Name = UserName, Password = PassWord };
JwtHelper pHelper = new JwtHelper();
string sJwt = pHelper.EncodeJwt(pUserLoginInfo);
jwtResult = new JwtResult()
{
JwtCode = sJwt,
StatusCode = "200",
Message = "success"
};
return Json(jwtResult);
}
catch (Exception ex)
{
jwtResult = new JwtResult()
{
JwtCode = "",
StatusCode = "403",
Message = ex.Message
};
}
return Json(jwtResult);
}
AuthorizeAttribute类有两个重要的方法:AuthorizeCore和HandleUnauthorizedRequest。其中AuthorizeCore函数是用来判断一个请求是否通过用户验证,它的返回结果是一个bool。HandleUnauthorizedRequest函数则是在AuthorizeCore返回结果是false时会调用的函数。
AuthorizeAttribute属性置于Action前,在调用Action前会进行验证。
AuthorizeAttribute属性置于Controller类前,在调用Controller中任何Action前会进行验证。
public class AppAuthorizeAttribute: AuthorizeAttribute
{
///
/// 验证入口
///
///
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
JwtHelper pHelper = new JwtHelper();
try
{
//前端请求api时会将token存放在名为"auth"的请求头中
var authHeader = httpContext.Request.Headers["auth"];
if (authHeader == null)
{
httpContext.Response.StatusCode = 403;
return false;
}
var userinfo = pHelper.DecodeJwt(authHeader);
if (userinfo != null)
return true;
httpContext.Response.StatusCode = 403;
return false;
}
catch
{
httpContext.Response.StatusCode = 403;
return false;
}
}
///
/// 验证失败处理
///
///
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
if (filterContext.HttpContext.Response.StatusCode == 403)
{
filterContext.Result = new RedirectResult("/Error");
filterContext.HttpContext.Response.Redirect("/Home/Error");
}
}
}
[AppAuthorize]
public class PagingController : Controller
{
// GET: Home
public ActionResult Index()
{
Models.UserInfo pUser = new Models.UserInfo()
{
Name = "Test",
Age = 18
};
ViewBag.Name = "Xq_lureker";
ViewBag.Age = "18";
return View(pUser);
}
}
参考:
https://blog.csdn.net/lxrj2008/article/details/75088780
https://www.cnblogs.com/xiaobai123/p/9242828.html
链接:https://pan.baidu.com/s/10ajfvmq9zeIZpiZAMWrKVQ
提取码:yae0
复制这段内容后打开百度网盘手机App,操作更方便哦