授权 - GetRolesForUser总是空的?

时间:2016-10-18 01:05:24

标签: asp.net-mvc-4 c#-4.0 authorization roles

我在.NET MVC 4应用程序中使用自定义登录验证。但是我无法通过Web.config文件实现角色授权。

我尝试过如下:

if(loginvalid)
{
    var claimsIdentity = new Claims.ClaimsIdentity(
        new[] 
            { 
                new Claims.Claim(Claims.ClaimTypes.NameIdentifier, "username"),
                new Claims.Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"),
                new Claims.Claim(Claims.ClaimTypes.Name,"username"),
                new Claims.Claim(Claims.ClaimTypes.Role, "admin"),
            },
            "CustomApiKeyAuth"
            );

    var principal = new Claims.ClaimsPrincipal(new[] { claimsIdentity });

    System.Threading.Thread.CurrentPrincipal = principal;
    System.Web.HttpContext.Current.User = principal;

    var test1 = User.Identity.IsAuthenticated;

    // here roleNames variable is always empty.
    string[] roleNames = Roles.GetRolesForUser();
}

在上面的代码中,roleNames变量始终为空。我做错了什么?

Web.config代码:

<location path="token.axd"> 
    <system.web>
        <authorization>
            <allow roles="admin"/> 
            <deny users="*"/> 
        </authorization>
    </system.web>
</location>

0 个答案:

没有答案