具有Forms身份验证和角色的Web API

时间:2013-08-23 12:35:00

标签: asp.net-mvc asp.net-web-api forms-authentication

我有一个MVC4 Web应用程序设置,它使用Forms身份验证和Web API进行交互。所有API控制器都使用[Authorize]属性。

这开箱即用,直到我们开始添加角色支持。我没有实现一个成熟的RoleProvider,而是在故障单的UserData中添加了一个角色列表,并创建了以下模块:

public class SecurityModule : IHttpModule
{
    public void Init(HttpApplication context)
    {
        var roleManager = (RoleManagerModule)context.Modules["RoleManager"];
        roleManager.GetRoles += GetRoles;
    }

    void GetRoles(object sender, RoleManagerEventArgs e)
    {
        var user = e.Context.User;
        if (user.Identity.IsAuthenticated && !(user is MyCustomPrincipal))
        {
            var roles = GetRolesFromFormsAuthCookie();
            if (roles != null)
                e.Context.User = new MyCustomPrincipal(user.Identity, roles,
                                                       otherData);
        }
        e.RolesPopulated = true;
    }
}

这对MVC调用完美无缺。但是,对于API,即使GetRoles 被调用,当它到达相应的方法时,也会回到GenericPrincipal

如何使用Web API进行此操作?我是否必须创建DelegatingHandler

我还在我的Principal中存储了一些自定义数据,这可能是不依赖于RoleProvider的原因(因为我最终会使用RolePrincipal),尽管我可以将它存储在请求上下文中。


更新:我现在添加了与DelegatingHandler相同的IHttpModule并设置了Thread.CurrentPrincipal。这是一种合理的方法吗?

1 个答案:

答案 0 :(得分:1)

您是否尝试过在HttpModule中设置Thread.CurrentPrincipal?您还可以使用适用于ASP.NET MVC和ASP.NET Web API的Katana处理程序。