asp.net mvc api auth

时间:2022-04-15 01:38:17

/// <summary>
/// 获取令牌
/// </summary>
/// <param>用户名</param>
/// <param>密码</param>
/// <returns></returns>
[HttpGet]
public object Login(string userName, string password)
{

if(验证没通过)
    return Json("用户名或密码错误");
FormsAuthenticationTicket token = new FormsAuthenticationTicket(0, userName, DateTime.Now,DateTime.Now.AddHours(1), true,userName,
FormsAuthentication.FormsCookiePath);
//返回登录结果、用户信息、用户验证票据信息
var Token = FormsAuthentication.Encrypt(token);
//将身份信息保存在Cache中,,一小时之内有访问有效
HttpRuntime.Cache.Insert(userName, Token, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(1,0,0), System.Web.Caching.CacheItemPriority.Default, null);

return Json(new { token = Token });
}

二、api auth

using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Security;

public class ApiAuthAttribute : AuthorizeAttribute// ActionFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
var token = content.Request.QueryString["Token"];
if (!string.IsNullOrEmpty(token))
{
//解密用户ticket,并校验用户名密码是否匹配
if (ValidateTicket(token))
{
base.IsAuthorized(actionContext);
}
else
HandleUnauthorizedRequest(actionContext);

}
else
HandleUnauthorizedRequest(actionContext);
}
private bool ValidateTicket(string encryptToken)
{
//解密Ticket
var userName = FormsAuthentication.Decrypt(encryptToken).UserData;

var token = HttpRuntime.Cache.Get(userName)?.ToString();

if (token == null)
{
return false;
}


//对比session中的令牌
if (token == encryptToken)
{
return true;
}

return false;

}
}

三、在需要验证的地方添加[ApiAuth]

asp.net mvc api auth