[英]ASP.NET Web API 2 Custom Authorization and Authorize Attribute
I have created a Google Chrome Extension and I plan to communicate with ASP.NET Wep API 2 service.我已经创建了一个 Google Chrome 扩展程序,我计划与 ASP.NET Wep API 2 服务进行通信。 Web service creates encrypted FormsAuthenticationTicket and sends it in the Login/SignIn response for the first time.
Web 服务创建加密的 FormsAuthenticationTicket 并在第一次登录/登录响应中发送它。 Validating user whether is authorized or not has been controlled by checking
Request Cookie
.通过检查
Request Cookie
来控制验证用户是否被授权。
Project creates ticket via GetEncryptedTicket(int UserID)
function.项目通过
GetEncryptedTicket(int UserID)
函数创建票证。
How can control and use [Authorize]
attribute above the service functions?如何控制和使用服务功能上面的
[Authorize]
属性? I know oAuth 2.0
may be the better option to implement it but I want to use following function to create ticket.我知道
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;
}
Use Action filter to validate the token like this public class BasicAuthenticationAttribute : ActionFilterAttribute {使用 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
};
}
}
}
And Use [BasicAuthentication] Attribute to validate token and allow Access并使用 [BasicAuthentication] 属性来验证令牌并允许访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.