我需要开发一个 iPhone 客户端来使用来自某处的 JSON 数据。我选择了 MS 的 Web API,因为它看起来很简单,但在验证用户身份时,事情变得非常令人沮丧。
我很惊讶我无法找到一个清晰的示例来说明如何从登录屏幕一直到使用 Authorize
对用户进行身份验证。属性超过我的ApiController
经过几个小时的谷歌搜索后的方法。
这不是一个问题,而是请求提供如何准确执行此操作的示例。我查看了以下页面:
尽管这些解释了如何处理未经授权的请求,但它们并没有清楚地展示类似 LoginController
的内容。或类似的东西来请求用户凭据并验证它们。
有人愿意写一个简单的例子或者给我指出正确的方向吗?
最佳答案
I am amazed how I've not been able to find a clear example of how to authenticate a user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
那是因为您对这两个概念感到困惑:
身份验证是系统可以安全地识别其用户的机制。身份验证系统提供了以下问题的答案:
- 用户是谁?
- 用户真的是他/她所代表的那个人吗?
授权是一种机制,系统通过该机制确定特定的经过身份验证的用户对系统控制的安全资源应具有何种级别的访问权限。例如,数据库管理系统可能被设计为向某些特定个人提供从数据库检索信息的能力,但不提供更改数据库中存储的数据的能力,同时向其他个人提供更改数据的能力。授权系统提供了以下问题的答案:
- 用户 X 是否有权访问资源 R?
- 用户 X 是否有权执行操作 P?
- 用户 X 是否有权对资源 R 执行操作 P?
MVC中的Authorize
属性用于应用访问规则,例如:
[System.Web.Http.Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
上述规则将仅允许具有管理员和 super 用户角色的用户访问该方法
这些规则也可以使用 location
元素在 web.config 文件中设置。示例:
<location path="Home/AdministratorsOnly">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
但是,在执行这些授权规则之前,您必须通过当前网站的身份验证。
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
从这里,我们可以将问题一分为二:
在同一 Web 应用程序中使用 Web API 服务时对用户进行身份验证
这将是最简单的方法,因为您将依赖 Authentication in ASP.Net
这是一个简单的例子:
Web.config
<authentication mode="Forms"> <forms protection="All" slidingExpiration="true" loginUrl="account/login" cookieless="UseCookies" enableCrossAppRedirects="false" name="cookieName" /> </authentication>
用户将被重定向到帐户/登录路线,在那里您将呈现自定义控件来询问用户凭据,然后您将使用以下方法设置身份验证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);
跨平台认证
这种情况是当您仅在 Web 应用程序中公开 Web API 服务时,因此,您将有另一个客户端使用这些服务,该客户端可以是另一个 Web 应用程序或任何 .Net 应用程序( Win Forms、WPF、控制台、Windows 服务等)
例如,假设您将从同一网络域(Intranet 内)上的另一个 Web 应用程序使用 Web API 服务,在这种情况下,您可以依赖 ASP.Net 提供的 Windows 身份验证。
<authentication mode="Windows" />
如果您的服务暴露在 Internet 上,那么您需要将经过身份验证的 token 传递给每个 Web API 服务。
有关更多信息,请阅读以下文章:
关于asp.net - ASP.NET Web API 中的用户身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11731683/