[英]ASP.NET Web API 2 Custom Authorization and Authorize Attribute
我已经创建了一个 Google Chrome 扩展程序,我计划与 ASP.NET Wep API 2 服务进行通信。 Web 服务创建加密的 FormsAuthenticationTicket 并在第一次登录/登录响应中发送它。 通过检查Request Cookie
来控制验证用户是否被授权。
项目通过GetEncryptedTicket(int UserID)
函数创建票证。
如何控制和使用服务功能上面的[Authorize]
属性? 我知道oAuth 2.0
可能是实现它的更好选择,但我想使用以下函数来创建票证。
public static string GetEncryptedTicket(int UserID)
{
DateTime now = DateTime.UtcNow.ToLocalTime();
var ticket = new FormsAuthenticationTicket(
1,
"TICKET_NAME",
now,
now.Add(FormsAuthentication.Timeout),
true,
UserID.ToString(),
FormsAuthentication.FormsCookiePath
);
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
return encryptedTicket;
}
使用 Action 过滤器来验证令牌,就像这个公共类 BasicAuthenticationAttribute : ActionFilterAttribute {
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
try
{
if (actionContext.Headers.GetValues("UserToken").FirstOrDefault() == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
ReasonPhrase = "Http request doesnot have the UserToken header"
};
}
else
{
string username = string.Empty, password = string.Empty;
var userToken = actionContext.Request.Headers.GetValues("UserToken").FirstOrDefault();
var token = FormsAuthentication.Decrypt(userToken);
if (token.Expired)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
{
ReasonPhrase = "Invalid User Token"
};
}
}
}
catch (Exception ex)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError)
{
ReasonPhrase = ex.Message
};
}
}
}
并使用 [BasicAuthentication] 属性来验证令牌并允许访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.