asp.Netwebapiカスタム認証
9714 ワード
///
///
///
/// Account API
/// TimeStamp
/// Sign
public class AuthFilterOutside : AuthorizeAttribute
{
// , Ticket
public override void OnAuthorization(HttpActionContext actionContext)
{
//url token
var content = actionContext.Request.Properties["MS_HttpContext"] as HttpContextBase;
string account = content.Request.QueryString["Account"];
string sign = content.Request.QueryString["Sign"];
int timeStamp = 0;
int.TryParse(content.Request.QueryString["TimeStamp"], out timeStamp);
ApiInfo apiInfo = DB.GetApiInfo(account);
int nowTimeStamp = Convert.ToInt32(GenerateTimeStamp());
//
if (apiInfo == null || nowTimeStamp - timeStamp > 15)
{
HandleUnauthorizedRequest(actionContext);
return;
}
SortedDictionary<string, string> dic = new SortedDictionary<string, string>();
foreach (string key in content.Request.QueryString.AllKeys)
{
if (key != "sign")
{
dic.Add(key, content.Request.QueryString[key]);
}
}
string makeSign = GetMakeSign(dic, apiInfo.Token);
//
if (sign != makeSign)
{
HandleUnauthorizedRequest(actionContext);
return;
}
}
protected override void HandleUnauthorizedRequest(HttpActionContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
response.StatusCode = HttpStatusCode.Forbidden;
string str = "{\"success\":\"false\",\"message\":\" : !\"}";
response.Content = new StringContent(str, Encoding.UTF8, "application/json");
}
public static string GenerateTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
///
/// ascii Key
///
///
///
///
public string GetMakeSign(SortedDictionary<string, string> dic, string token)
{
StringBuilder strBuilder = new StringBuilder();
foreach (var item in dic)
{
strBuilder.AppendFormat("{0}={1}&", item.Key, item.Value);
}
strBuilder.AppendFormat("key={0}", token);
var md5 = MD5.Create();
var bs = md5.ComputeHash(Encoding.UTF8.GetBytes(strBuilder.ToString()));
var sb = new StringBuilder();
foreach (byte b in bs)
{
sb.Append(b.ToString("x2"));
}
//
return sb.ToString().ToUpper();
}
}
転載先:https://www.cnblogs.com/xuannian/p/9708521.html