0

我们已经创建了一个 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"}
                });
        }
    }
}

请提供您的意见。

4

1 回答 1

0

问题已解决。我修改了我的登录操作:

[HttpPost]
public ActionResult Login(LoginViewModel model)
{
    bool isValidated = //Code for validating the users
    if (ModelState.IsValid && isValidated)
    {
        //Set the authentication cookie for the logged in user.
        FormsAuthentication.SetAuthCookie(model.UserName, true);
        return RedirectToAction("Index", "Help", new { area = "HelpPage" });
    }
    else
    {
        return View();
    }                
}

我在 Global.asax.cs 中实现了“Application_AuthenticateRequest”方法

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    try
    {
        if (Context.Request.Cookies[".ASPXAUTH"] != null)
        {
            var authCookie = FormsAuthentication.Decrypt(Context.Request.Cookies[".ASPXAUTH"].Value);
            var identity = new GenericIdentity(authCookie.Name);
            Context.User = new GenericPrincipal(identity, null);
        }
        else
        {
            Context.User = null;
        }
    }
    catch(Exception ex)
    {
        Context.User = null;
    }
}

输入有效凭据后,用户将通过身份验证,并将被重定向到帮助页面。

于 2016-04-27T05:59:11.653 回答