【发布时间】:2013-03-28 06:30:43
【问题描述】:
我正在构建一个具有基本帐户功能的 WebAPI AccountController,例如登录、注销、注册等。
我的控制器顶部装饰有[System.Web.Http.Authorize] 属性。
在以下方法中,经过身份验证的用户是我的本地系统用户,除非我用“AllowAnonymous”装饰该方法:
// GET/api/isAuthenticated
// [System.Web.Http.AllowAnonymous]
[System.Web.Http.HttpGet]
public HttpResponseMessage IsAuthenticated()
{
if (User.Identity.IsAuthenticated)
{
var userProfile = _service.GetUserProfile(WebSecurity.CurrentUserId);
return Request.CreateResponse(HttpStatusCode.OK, userProfile);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, false);
}
}
据我了解,AllowAnonymous 告诉控制器不要将 Authorize 属性应用于给定方法。由于我正在构建一个 Web 应用程序,我从不想针对本地凭据进行授权。
我从 MVC SPA 模板中提取了此代码,所以我想知道 - 当不使用 [AllowAnonymous] 时,如何将其更改为针对本地存储的用户凭据而不是系统用户进行授权?
【问题讨论】:
-
查看您的 web.config,
authorization配置部分描述了授权方案。听起来您目前设置为匿名。 -
还要记住,Web API 中没有“会话”的概念。这是设计使然,因为 Web API 遵循 REST。 HTTP 是一种无状态协议,因此对授权视图的每个请求的标头中都必须包含某种身份验证或授权(例如令牌)。
-
@asawyer - 我刚刚看了看,我将身份验证设置为 Forms,但如果我将鼠标悬停在“User.Identity”上,则 authenticationType 被列为“Negotiate”而不是“Forms”——所以它正在拉我的系统凭据。知道还能在哪里配置吗?
-
@ChrisPratt - 感谢 Chris 的提醒。
标签: c# .net asp.net-mvc asp.net-mvc-4