繁体   English   中英

具有自定义角色声明的Azure移动应用程序身份验证-声明消失

[英]Azure Mobile App Authentication With Custom Role Claims - Claims Disappearing

我们有一个使用社交网络身份验证的Azure移动应用。 尝试使用自定义令牌处理程序将用户角色添加为声明。

当在localhost上运行时,所有这些都有效-令牌已添加到令牌处理程序中,并且在调用AuthorizationAttribute OnAuthorization方法时可用。 具有指定角色的Authorize属性可以按预期工作。

但是在运行Azure时,将添加声明,但是在调用OnAuthorization方法时,自定义角色声明消失了。

这是代码:

启动/配置类

public class OwinStartup
{
    public void Configuration(IAppBuilder app)
    {
        var config = GlobalConfiguration.Configuration;

        new MobileAppConfiguration()
        .AddPushNotifications()
        .ApplyTo(config);

        MobileAppSettingsDictionary settings = config.GetMobileAppSettingsProvider().
GetMobileAppSettings();

        app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
        {
            SigningKey = ConfigurationManager.AppSettings["authSigningKey"],
            ValidAudiences = new[] { ConfigurationManager.AppSettings["authAudience"] },
            ValidIssuers = new[] { ConfigurationManager.AppSettings["authIssuer"] },
            TokenHandler = new AppServiceTokenHandlerWithCustomClaims(config)
        });

        //Authenticate stage handler in OWIN Pipeline
        app.Use((context, next) =>
        {
            return next.Invoke();
        });

        app.UseStageMarker(PipelineStage.Authenticate);

    }

添加角色声明的令牌处理程序

public class AppServiceTokenHandlerWithCustomClaims : AppServiceTokenHandler
{
    public AppServiceTokenHandlerWithCustomClaims(HttpConfiguration config)
        : base(config)
    {

    }

    public override bool TryValidateLoginToken(
        string token,
        string signingKey,
        IEnumerable<string> validAudiences,
        IEnumerable<string> validIssuers,
        out ClaimsPrincipal claimsPrincipal)
    {
        var validated = base.TryValidateLoginToken(token, signingKey, validAudiences, validIssuers, out claimsPrincipal);

        if (validated)
        {
            string sid = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value;

            var roleProvider = UnityConfig.Container.Resolve<IRoleProvider>("RoleProvider");

            var roles = roleProvider.GetUserRolesBySid(sid);

            foreach (var role in roles)
            {
                ((ClaimsIdentity)claimsPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role));
            }
        }
        return validated;
    }
}

角色声明来自身份声明集合的角色声明的示例

{http://schemas.microsoft.com/ws/2008/06/identity/claims/role: admin}

在Web Api控制器上授权属性

[Authorize(Roles = "admin")]

对具有Authorize属性并指定了一个或多个角色的端点的每次调用都会失败(401)

不确定在Azure中运行时声明被剥夺身份或不保留在身份中怎么回事。

谢谢迈克尔

我在书中对此做了一章-https: //adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/chapter2/custom/#using-third-party-tokens

注意有关带有附加声明的自定义身份验证的内容。 您需要使用原始令牌调用自定义API,检查令牌的有效性,然后生成具有所需声明的新令牌(zumo令牌)。 然后,您可以将这些声明用于所需的任何内容。

根据此博客文章 ,您的某些选择可能是错误的。 AppSettings仅设置用于本地调试,在Azure中不起作用。

尝试这个:

public void Configuration(IAppBuilder app)
{
    var config = GlobalConfiguration.Configuration;

    new MobileAppConfiguration()
        .AddPushNotifications()
        .ApplyTo(config);

    MobileAppSettingsDictionary settings = config
        .GetMobileAppSettingsProvider()
        .GetMobileAppSettings();

    // Local Debugging
    if (string.IsNullOrEmpty(settings.HostName))
    {
        app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
        {
            SigningKey = ConfigurationManager.AppSettings["authSigningKey"],
            ValidAudiences = new[] { ConfigurationManager.AppSettings["authAudience"] },
            ValidIssuers = new[] { ConfigurationManager.AppSettings["authIssuer"] },
            TokenHandler = new AppServiceTokenHandlerWithCustomClaims(config)
        });
    }
    // Azure
    else
    {
        var signingKey = GetSigningKey();
        string hostName = GetHostName(settings);

        app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions
        {
            SigningKey = signingKey,
            ValidAudiences = new[] { hostName },
            ValidIssuers = new[] { hostName },
            TokenHandler = new AppServiceTokenHandlerWithCustomClaims(config)
        });
    }


    //Authenticate stage handler in OWIN Pipeline
    app.Use((context, next) =>
    {
        return next.Invoke();
    });

    app.UseStageMarker(PipelineStage.Authenticate);

}

private static string GetSigningKey()
{
    // Check for the App Service Auth environment variable WEBSITE_AUTH_SIGNING_KEY,
    // which holds the signing key on the server. If it's not there, check for a SigningKey
    // app setting, which can be used for local debugging.

    string key = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");

    if (string.IsNullOrWhiteSpace(key))
    {
        key = ConfigurationManager.AppSettings["SigningKey"];
    }

    return key;
}

private static string GetHostName(MobileAppSettingsDictionary settings)
{
    return string.Format("https://{0}/", settings.HostName);
}

暂无
暂无

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

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