没有登录的ASP.NET API Windows身份验证

时间:2015-03-26 16:40:56

标签: asp.net windows-authentication roleprovider

需要使用Windows AD进行授权的Intranet应用程序。任何人都可以访问该网站,但只有特定AD组的成员才能访问某些网页和API调用。组名在web.config中,因为它会因环境而异。我希望能够在API控制器和方法上使用属性:

 [MyAdminAttribute]
 public class MyController : ApiController

这是我的自定义属性:

public class MyAdminAttribute: AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var user = ((ApiController)actionContext.ControllerContext.Controller).User;  // THIS USER IS ALWAYS NULL, WHY?
        var adminGroup = WebConfigurationManager.AppSettings["MyAdminGroup"];
        var isInAdminGroup = user.IsInRole(adminGroup);
        var roles = ((ClaimsIdentity)user.Identity).Claims
            .Where(c => c.Type == ClaimTypes.Role)
            .Select(c => c.Value).ToList();  // Just checking here, 0 roles found.

        return isInAdminGroup;
    }
}

我还需要能够检查用户是否在Razor视图中扮演角色:

 @if (User.IsInRole(WebConfigurationManager.AppSettings["MyAdminGroup"])) {

以下是相关的web.config设置:

<authentication mode="Windows"/>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
 <providers>
    <clear />
    <add 
        name="AspNetWindowsTokenRoleProvider"
        type="System.Web.Security.WindowsTokenRoleProvider" 
        applicationName="/" />
 </providers>
</roleManager>

但是,User始终为null,User.IsInRole()始终为false。为什么会这样?

0 个答案:

没有答案