[BasicHttpAuthorize]
通过将属性添加到适当的控制器/方法,对初始(登录)请求使用基本身份验证。如果需要,使用属性指定用户和角色。像这样定义BasicHttpAuthorizeAttribute
为一个专门的AuthorizeAttribute:
public class BasicHttpAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
if (Thread.CurrentPrincipal.Identity.Name.Length == 0) { // If an identity has not already been established by other means:
AuthenticationHeaderValue auth = actionContext.Request.Headers.Authorization;
if (string.Compare(auth.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) == 0) {
string credentials = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter));
int separatorIndex = credentials.IndexOf(':');
if (separatorIndex >= 0) {
string userName = credentials.Substring(0, separatorIndex);
string password = credentials.Substring(separatorIndex + 1);
if (Membership.ValidateUser(userName, password))
Thread.CurrentPrincipal = actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(userName, "Basic"), System.Web.Security.Roles.Provider.GetRolesForUser(userName));
}
}
}
return base.IsAuthorized(actionContext);
}
}
让初始响应包含用户的 API 密钥。使用 API 密钥进行后续调用。这样,即使用户更改了用户名或密码,客户端的身份验证仍然有效。但是,在更改密码时,请为用户提供“断开客户端连接”的选项,您可以通过删除服务器上的 API 密钥来实现该选项。