我们已经创建了一个 web api 项目,其中我们暂时使用了基本身份验证。我们使用 nuget 包来生成 Web Api 帮助文档,因此它为 Web Api 帮助添加了新的区域、控制器和视图。我们在 IIS 上托管了 web api。现在,任何人都可以通过浏览 Web Api url“ http://localhost/WebApi/Help ”来浏览 Web Api 帮助。我们想要验证帮助页面(在 MVC 中实现)。这里的问题是我的 web api 使用基本身份验证,我想创建一种机制,以便在对 Web Api 帮助页面的任何请求之前对 web api 帮助进行身份验证。
为此,我创建了一个“AccountController”、“Login”页面。我还创建了一个身份验证过滤器并装饰了“HelpController”(它具有用于呈现帮助页面的所有操作)。登录页面代码:
public ActionResult Login(LoginViewModel model)
{
bool isValidated = //Code for validating the users
if (ModelState.IsValid && isValidated)
{
var identity = new HelpAuthenticationIdentity(model.UserName, model.Password);
var principal = new WindowsPrincipal(identity);
ControllerContext.HttpContext.User = principal;
return RedirectToAction("Index", "Help", new { area = "HelpPage" });
}
else
return View();
}
我创建了一个继承 WindowsIdentity 类的身份类
public class HelpAuthenticationIdentity : WindowsIdentity
{
public HelpAuthenticationIdentity(string userName, string password)
: base(userName, "Basic")
{
this.Password = password;
}
public string Password { get; set; }
}
当我在输入有效凭据后单击登录时,它将被重定向到帮助控制器的索引操作。由于我有身份验证过滤器,它将首先调用“OnAuthentication”方法。在这里,它总是将“context.HttpContext.User.Identity.IsAuthenticated”标志设为假。认证过滤器属性如下:
/// <summary>
/// Authentication filter to authenticate the request for Web Api Help
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class HelpAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new HttpUnauthorizedResult();
}
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
{
if(context.Result == null || context.Result is HttpUnauthorizedResult)
{
context.Result = new RedirectToRouteResult("Login",
new System.Web.Routing.RouteValueDictionary{
{"controller", "Account"},
{"action", "Login"}
});
}
}
}
请提供您的意见。