更新时间:2023-02-15 17:25:50
我觉得令牌将要走了坚实的道路。窗体身份验证是基于cookie进行网页。不是所有的非浏览器客户端的最主意情况,但。
我会建议是创建一个自定义AuthorizationFilterAttribute并重写OnAuthorization方法。在该方法中,你可以检查他们所提供的有效凭据后,您已经发到客户端的令牌的存在。你可以在你想验证的任何方法或控制器使用此属性。以下是你可能会引用一个样本
公共类AuthorizeTokenAttribute:AuthorizationFilterAttribute
{
公共覆盖无效OnAuthorization(HttpActionContext ActionContext中)
{
如果(ActionContext中!= NULL)
{
如果(!的AuthorizeRequest(actionContext.ControllerContext.Request))
{
actionContext.Response =新的Htt presponseMessage(的HTTPStatus code.Unauthorized){RequestMessage = actionContext.ControllerContext.Request};
}
返回;
}
} 私人布尔的AuthorizeRequest(System.Net.Http.Htt prequestMessage要求)
{
布尔授权= FALSE;
如果(request.Headers.Contains(Constants.TOKEN_HEADER))
{
变种tokenValue = request.Headers.GetValues(TOKEN_HEADER);
如果(tokenValue.Count()== 1){
VAR值= tokenValue.FirstOrDefault();
//令牌验证逻辑在这里
//设置授权相应的变量
}
}
返回的授权;
}}
TOKEN_HEADER只是一个字符串重新presenting的HTTP标头,客户端应该通过回身份验证请求。
因此,让我们走过它
此外,检查这个职位由约翰·彼得森。 使您的ASP.NET Web API的安全一>
How do I even begin coding authentication using ASP.NET Web API so it is cross-platform to support desktop, mobile and web? I'd read of some methods of doing RESTful authentication, such as using tokens in the header.
Are there any example projects out there that utilizes this method?
Questions:
[Authorize]
attribute to read the token?
I think tokens would be a solid way to go. Forms authentication is based on cookies for the web. Not the most idea situation for all non browser clients though.
What I'd suggest is creating a custom AuthorizationFilterAttribute and overriding the OnAuthorization method. In that method, you could check for the existence of a token that you've issued to the client after they've supplied valid credentials. You can use this attribute on any method or controller you want validated. Here's a sample you might reference
public class AuthorizeTokenAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext != null)
{
if (!AuthorizeRequest(actionContext.ControllerContext.Request))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = actionContext.ControllerContext.Request };
}
return;
}
}
private bool AuthorizeRequest(System.Net.Http.HttpRequestMessage request)
{
bool authorized = false;
if (request.Headers.Contains(Constants.TOKEN_HEADER))
{
var tokenValue = request.Headers.GetValues("TOKEN_HEADER");
if (tokenValue.Count() == 1) {
var value = tokenValue.FirstOrDefault();
//Token validation logic here
//set authorized variable accordingly
}
}
return authorized;
} }
TOKEN_HEADER is just a string representing an HTTP header that the client should pass back for authenticated requests.
So let's walk through it
Also, check this post by John Petersen. Making your ASP.NET Web API’s secure