简体   繁体   English

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

[英]Web API with Forms authentication and roles

I have a MVC4 web application set up, which uses Forms authentication and Web API for interaction. 我设置了一个MVC4 Web应用程序,该应用程序使用Forms身份验证和Web API进行交互。 All API controllers use the [Authorize] attribute. 所有API控制器都使用[Authorize]属性。

This was working just fine out of the box, until we started adding role support. 在开始添加角色支持之前,这种方法开箱即用。 Instead of implementing a full-fledged RoleProvider, I added a list of roles to the ticket's UserData , and created the following module: 我没有实现正式的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;
    }
}

This works flawlessly for MVC calls. 这对于MVC调用是完美的。 For API, however, even though GetRoles gets called , when it reaches the corresponding method, it's back to GenericPrincipal . 对于API,即使GetRoles 被调用 ,当到达相应方法时,它又返回GenericPrincipal

How can I make this work with Web API too? 我如何也可以使用Web API? Do I have to create a DelegatingHandler ? 我必须创建一个DelegatingHandler吗?

I'm also storing some custom data in my Principal, which might be a reason not to rely on just a RoleProvider (since I'd end up with a RolePrincipal), although I could just store that in the request context. 我还在我的Principal中存储了一些自定义数据,这也许是一个不仅仅依赖RoleProvider的原因(因为我最终会使用RolePrincipal),尽管我可以将其存储在请求上下文中。


Update: I've now added a DelegatingHandler that does the same as the IHttpModule and sets Thread.CurrentPrincipal . 更新:我现在添加了一个DelegatingHandler ,它与IHttpModule相同,并设置Thread.CurrentPrincipal Is this a reasonable approach? 这是合理的方法吗?

Have you tried to set the Thread.CurrentPrincipal in the HttpModule as well ?. 您是否也尝试过在HttpModule中设置Thread.CurrentPrincipal? You can also use a Katana handler, which will work for both, ASP.NET MVC and ASP.NET Web API. 您还可以使用Katana处理程序,该处理程序对ASP.NET MVC和ASP.NET Web API均适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM