码迷,mamicode.com
首页 > Windows程序 > 详细

asp.net mvc api auth

时间:2016-10-18 13:17:19      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

一、登录

/// <summary>
/// 获取令牌
/// </summary>
/// <param name="userName">用户名</param>
/// <param name="password">密码</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

标签:

原文地址:http://www.cnblogs.com/catzhou/p/5972697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!