【发布时间】:2016-03-30 10:53:57
【问题描述】:
我正在研究如何保护 ASP.NET Web Api 应用程序。我已经开始使用基本身份验证(是的 - 我知道不建议这样做,是的 - 我的最终计划是使用基于令牌的身份验证。但我需要先学习和理解基础知识)。
起初,我所做的是创建一个继承自 AuthorizeAttribute 的 Attribute,并在我想要保护的控制器上使用。这是非常基本的(并且有效):
public class SimpleUserNamePasswordAuthorizeAttribute : AuthorizeAttribute
{
public string UserName { get; set; }
public string Password { get; set; }
protected override bool IsAuthorized(HttpActionContext actionContext)
{
string query = actionContext.Request.RequestUri.Query;
var nvc = HttpUtility.ParseQueryString(query);
string securityQueryToken = nvc["_auth"];
if (string.IsNullOrEmpty(securityQueryToken) && actionContext.Request.Headers.Authorization == null)
{
return false;
}
string authToken = "";
if (actionContext.Request.Headers.Authorization != null)
authToken = actionContext.Request.Headers.Authorization.Parameter;
else
authToken = securityQueryToken;
if (string.IsNullOrWhiteSpace(authToken))
{
return false;
}
// Decode the token from BASE64
string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
if(string.IsNullOrWhiteSpace(decodedToken))
{
return false;
}
// Extract username and password from decoded token
int index = decodedToken.IndexOf(":", StringComparison.Ordinal);
if(index == -1)
{
return false;
}
string userName = decodedToken.Substring(0, decodedToken.IndexOf(":", StringComparison.Ordinal));
string password = decodedToken.Substring(decodedToken.IndexOf(":", StringComparison.Ordinal) + 1);
return ((userName == UserName) && (password == Password));
}
}
我在某处读到,这种工作方式在 Web Api v1 中更为常见。并找到了这个实现基本认证的项目:https://github.com/IdentityModel/IdentityModel.Owin.BasicAuthentication
从中我了解到他们正在使用不同的方法(这似乎更正确),我不需要我自己的 Attribute,并使用 ASP.NET 中的 [Authorize]。
他们通过继承AuthenticationHandler 和AuthenticationMiddleware 并将其用作Owin 中间件来做到这一点。起初它不起作用,直到我从 App_Start 目录中的 WebApiConfig.cs 中删除以下内容:
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
我还注意到它在对服务器的每个请求时都会被调用,而我自己的属性调用只对使用我的属性的相关控制器进行。
- 我想知道,这两种方法有什么区别,哪种方法更“正确”?哪个提供更好的安全性?
- 为什么我必须从
WebApiConfig.cs中删除这些行才能正常工作? - 第二种方法是否具有第一种方法没有的一些性能影响?
【问题讨论】:
标签: c# asp.net asp.net-web-api asp.net-web-api2 owin