2013-02-18 92 views
3

在我的MVC 4 Web API项目中,我有一个自定义角色提供程序,它按照设计的System.Web.Mvc.Authorize属性在我的主页System.Web.Mvc.Controller上运行。System.Web.Http.AuthorizeAttribute无法识别自定义角色提供者

在任何System.Web.Http.ApiControllerSystem.Web.Http.Authorize自定义角色提供程序永远不会被调用,总是返回false。有没有一种方法可以指定Web API AuthorizeAttribute选择我的自定义角色提供程序,如MVC AuthorizeAttribute?

角色提供:

public class CustomRoleProvider : RoleProvider 
{   
    //Overriden methods 
    public override string[] GetRolesForUser(string username) 
    { 
     //Always return "Master" for testing purposes 
     return new string[] { "Master" }; 
    } 

    public override bool IsUserInRole(string username, string roleName) 
    { 
     //Always return true for testing purposes 
     return true; 
    } 

    //Other overridden method stubs... 
} 

Web.config文件:

<roleManager defaultProvider="CustomRoleProvider" enabled="true" cacheRolesInCookie="false" > 
    <providers> 
    <clear /> 
    <add name="CustomRoleProvider" type="MyApp.SecurityExtensions.CustomRoleProvider, MyApp" /> 
    </providers> 
</roleManager> 
+0

它只从MVC控制器中触发它。使用'[System.Web.Http.Authorize(Roles =“Master”)]'立即从API控制器评估为false – chrisjsherm 2013-02-18 21:48:16

+0

我将关闭缓存以进行测试... – leastprivilege 2013-02-19 07:25:34

+0

Cookie正在过期每会话,所以我刚才一直在关闭浏览器,但是如果我在调试时忘记关闭浏览器,这点很重要。我更新了操作系统,以反映关闭缓存 – chrisjsherm 2013-02-19 18:11:11

回答

2

这是不是一个真正的答案,但是这可能帮助:

两个通过查询当前pricipal属性的工作。 MVC属性使用HTTPContent.User,而System.Web.http版本使用Thread.CurrentPrincipal,但这种差异很小。

我并没有真正熟悉Web API,但我怀疑RoleManagerModule没有在属性触发的时候运行,或者您还没有达到PostAuthenticateRequest事件,因为在这种情况下,模块将取代Pricipal。

您确定您的WebAPI使用需要某种形式的ASP身份验证吗?如果您没有将WebAPI项目配置为需要某种形式的身份验证,那么显然您永远不会到达PostAuthenticateRequest事件,因此RoleManagerModule将永远不会启动。

想到的最后一种可能性是其他人在RoleManagerModule这样做后取代了Principal。如果可能,临时删除System.Web.Http.AuthorizeAttribute,在控制器中设置断点,并确定Thread.CurrentPrincipal具有哪个类。这可能会给你一个提示它出错的地方。

+0

我的客户端使用的第三方认证库在使用IPrincipal接口后没有执行'bool IsInRole(string role)'方法。你的建议,看看是否有东西替换校长让我走上正轨 – chrisjsherm 2013-02-20 14:32:46

0

您将需要使用的System.Web。 Http .AuthorizeAttribute for Web API的控制器。示例:http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/

+0

我之前已经对该帖子进行过扫描,但为什么我必须扩展AuthorizeAttribute才能使其与API控制器一起工作?我可以看到'System.Web.Security.RolePrincipal'正确设置了'ProviderName'' – chrisjsherm 2013-02-18 22:09:39

+0

只是为了澄清,就像你在OP的评论中看到的那样,我回应了一个随后被删除的评论,我正在使用' System.Web.Http.AuthorizeAttribute'而不是'System.Web.Mvc.AuthorizeAttribute'在我的ApiController上。我会更新OP来说明清楚。谢谢 – chrisjsherm 2013-02-19 15:45:58

相关问题