Microsoft MVC 4,APIController和适当的RESTful登录Web服务

fra*_*llo 5 rest asp.net-mvc web-services asp.net-mvc-4

我使用Microsoft ASP.NET MVC 4制作了一个简单的RESTful Web服务(目前仅限GET)ApiController.

现在我正在寻找实现服务授权系统的正确方法.我知道我不想使用内置的FormsAuthentication,因为我不想为使用我的WS的所有应用程序提供唯一的登录页面; 此外,它破坏了RESTful范例,强制重定向,而不是通过正确的401状态代码通知客户端.

所以我已禁用FormsAuthentication从我的删除以下行web.config:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

并添加以下内容:

<modules runAllManagedModulesForAllRequests="true">
    <remove name="FormsAuthentication" />
</modules>
Run Code Online (Sandbox Code Playgroud)

我已经有了一个ApiController用于管理用户登录的用户登录,它基本上会根据我的数据库检查凭据并返回用户或者401凭证是否无效.

我已经读过我必须实现MembershipAuthorizationAPI,但我发现没有什么可以帮助我从头开始.你有什么想法?我是否需要在数据库上管理cookie和authcodes,或者是否有与FormsAuthentication我类似的类?

fra*_*llo 3

我找到了一个解决方案,我基本上使用了Microsoft示例中显示的解决方法。

  1. 创建一个名为 App_Start 的文件夹。
  2. 将这两个 放在正确的命名空间中。
  3. FormsAuthentication 和添加的请求/响应处理系统将完成剩下的工作。

由于我不喜欢 401 响应中的“内容已移至此处”,因此我按OnEndRequest如下方式编辑了该方法:

private void OnEndRequest(object source, EventArgs args)
    {
        var context = (HttpApplication)source;
        var response = context.Response;

        if (context.Context.Items.Contains("__WEBAPI:Authentication-Fixup"))
        {
            response.StatusCode = (int)context.Context.Items[FixupKey];
            response.RedirectLocation = null;
            // Clear the page content, since I don't want the "Content moved here." body
            response.ClearContent();
        }
    }
Run Code Online (Sandbox Code Playgroud)

参考: