我很惊讶,在Google搜索了几个小时之后,我竟然找不到一个清晰的示例来说明如何从登录屏幕一直到在我的ApiController方法上使用Authorize属性来对用户进行身份验证.
那是因为你混淆了这两个概念:
MVC中的Authorize
属性用于应用访问规则,例如:
[System.Web.Http.Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
上述规则将只允许users in the Admin and Super User roles to access the method
这些规则也可以在网上设置.配置文件,使用location
元素.例子:
<location path="Home/AdministratorsOnly">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
然而,在执行这些授权规则之前,你必须是authenticated to the current web site岁.
尽管这些说明了如何处理未经授权的请求,但它们并没有清楚地展示诸如LoginController之类的东西来请求用户凭据并验证它们.
从这里,我们可以将问题分为两部分:
在同一Web应用程序中使用Web API服务时对用户进行身份验证
这将是最简单的方法,因为您将依赖于Authentication in ASP.Net
这是一个简单的示例:
网状物配置
<authentication mode="Forms">
<forms
protection="All"
slidingExpiration="true"
loginUrl="account/login"
cookieless="UseCookies"
enableCrossAppRedirects="false"
name="cookieName"
/>
</authentication>
用户将被重定向到account/login路径,在那里您将呈现自定义控件以请求用户凭据,然后您将使用以下方法设置身份验证cookie:
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
跨平台认证
这种情况下,当你only exposing Web API services within the Web application岁时,你会有另一个客户机使用这些服务,该客户机可能是另一个Web应用程序或任何其他应用程序.Net应用程序(Win窗体、WPF、控制台、Windows服务等)
例如,假设您将使用来自同一网络域(在Intranet内)上的另一个Web应用程序的Web API服务,在这种情况下,您可以依赖ASP.NET提供的Windows身份验证.
<authentication mode="Windows" />
如果您的服务在Internet上公开,则需要将经过身份验证的令牌传递给每个Web API服务.
有关更多信息,请浏览以下文章: