我正在尝试检索作为OnAuthenticated上下文返回并作为声明添加到此示例之后的用户属性:How to access Facebook private information by using ASP.NET Identity (OWIN)?

我可以看到登录时返回了我期望的数据,并将其作为声明添加到Starup.Auth.cs中。但是,当我在客户控制器中时,出现在UserManager或UserStore中的唯一声明是由本地授权颁发的。找不到针对Facebook(或其他外部提供商)的索赔。添加到上下文中的声明在哪里结束? (我正在使用VS2013 RTM。)

Azure上的完整源和实时网站都链接在这里:https://github.com/johndpalm/IdentityUserPropertiesSample/tree/VS2013rtm

这是我在Startup.Auth.cs中的内容:

var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
{
    AppId = ConfigurationManager.AppSettings.Get("FacebookAppId"),
    AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
    Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
    {
        OnAuthenticated = (context) =>
            {
                const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
                foreach (var x in context.User)
                {
                    var claimType = string.Format("urn:facebook:{0}", x.Key);
                    string claimValue = x.Value.ToString();
                    if (!context.Identity.HasClaim(claimType, claimValue))
                        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));

                }
                context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                return Task.FromResult(0);
            }
    }

};

facebookOptions.Scope.Add("email");

app.UseFacebookAuthentication(facebookOptions);


捕获外部登录属性的另一种方法是为访问令牌添加一个声明,并用属性填充它:

const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
{
    AppId = ConfigurationManager.AppSettings.Get("FacebookAppId"),
    AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
    Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
    {
        OnAuthenticated = (context) =>
        {
            var claim = new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook");
            foreach (var x in context.User)
            {
                string key = string.Format("urn:facebook:{0}", x.Key);
                string value = x.Value.ToString();
                claim.Properties.Add(key, value);
            }

            context.Identity.AddClaim(claim);

            return Task.FromResult(0);
        }
    }
};


注意-此示例无法正常工作:尽管最好通过一个带有属性的声明。外部cookie似乎表明了对Claims属性的尊重。稍后从标识中检索属性时,这些属性为空。

最佳答案

我能够使用MVC 5 RTM模板,OWIN和ASP.NET标识位创建一个工作示例。您可以在此处找到完整的源代码和一个实时示例的链接:https://github.com/johndpalm/IdentityUserPropertiesSample

这对我有用:

在Startup.ConfigureAuth(StartupAuth.cs)中创建一个新的(在此处插入提供者名称)AuthenticationOptions对象,并向其传递客户端ID,客户端密码和新的AuthenticationProvider。您将使用lambda表达式传递OnAuthenticated方法一些代码,以将Claims添加到Identity中,该Claims包含您从context.Identity中提取的值。

StartUp.Auth.cs

// Facebook : Create New App
// https://dev.twitter.com/apps
if (ConfigurationManager.AppSettings.Get("FacebookAppId").Length > 0)
{
    var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
    {
        AppId = ConfigurationManager.AppSettings.Get("FacebookAppId"),
        AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
        Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
        {
            OnAuthenticated = (context) =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                    foreach (var x in context.User)
                    {
                        var claimType = string.Format("urn:facebook:{0}", x.Key);
                        string claimValue = x.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));

                    }
                    return Task.FromResult(0);
                }
        }

    };
    app.UseFacebookAuthentication(facebookOptions);
}


注意:Facebook身份验证提供程序使用此处使用的代码。如果您对Microsoft帐户提供程序(或我使用MS帐户代码作为模型创建的Foursquare provider)使用相同的代码,则它将无法登录。如果仅选择access_token参数,它将正常工作。似乎有些参数破坏了登录过程。 (An issue has been opened on katanaproject.codeplex.com if progress on this is of interest to you.)如果找到原因,我将进行更新。除了验证我可以获取access_token之外,我对Twitter或Google所做的工作不多。

var msaccountOptions = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions()
{
    ClientId = ConfigurationManager.AppSettings.Get("MicrosoftClientId"),
    ClientSecret = ConfigurationManager.AppSettings.Get("MicrosoftClientSecret"),
    Provider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider()
    {
        OnAuthenticated = (context) =>
            {
                context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsoftaccount:access_token", context.AccessToken, XmlSchemaString, "Microsoft"));
                return Task.FromResult(0);
            }
    }
};

app.UseMicrosoftAccountAuthentication(msaccountOptions);


在AccountController中,我使用外部cookie从AuthenticationManager中提取ClaimsIdentity。然后,将其添加到使用应用程序cookie创建的身份中。我忽略了任何以“ ... schemas.xmlsoap.org/ws/2005/05/identity/claims”开头的声明,因为它似乎破坏了登录名。

AccountController.cs

private async Task SignInAsync(CustomUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

// Extracted the part that has been changed in SignInAsync for clarity.
    await SetExternalProperties(identity);

    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

private async Task SetExternalProperties(ClaimsIdentity identity)
{
    // get external claims captured in Startup.ConfigureAuth
    ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

    if (ext != null)
    {
        var ignoreClaim = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";
        // add external claims to identity
        foreach (var c in ext.Claims)
        {
            if (!c.Type.StartsWith(ignoreClaim))
                if (!identity.HasClaim(c.Type, c.Value))
                    identity.AddClaim(c);
        }
    }
}


最后,我想显示不是本地授权提供的任何值。我创建了显示在_ExternalUserPropertiesListPartial上的局部视图/Account/Manage page。我从AuthenticationManager.User.Claims获得了先前存储的声明,然后将其传递给视图。

AccountController.cs

[ChildActionOnly]
public ActionResult ExternalUserPropertiesList()
{
    var extList = GetExternalProperties();
    return (ActionResult)PartialView("_ExternalUserPropertiesListPartial", extList);
}

private List<ExtPropertyViewModel> GetExternalProperties()
{
    var claimlist = from claims in AuthenticationManager.User.Claims
                    where claims.Issuer != "LOCAL AUTHORITY"
                    select new ExtPropertyViewModel
                    {
                        Issuer = claims.Issuer,
                        Type = claims.Type,
                        Value = claims.Value
                    };

    return claimlist.ToList<ExtPropertyViewModel>();
}


只是为了彻底,视图:

_ExternalUserPropertiesListPartial.cshtml

@model IEnumerable<MySample.Models.ExtPropertyViewModel>

@if (Model != null)
{
    <legend>External User Properties</legend>
    <table class="table">
        <tbody>
            @foreach (var claim in Model)
            {
                <tr>
                    <td>@claim.Issuer</td>
                    <td>@claim.Type</td>
                    <td>@claim.Value</td>
                </tr>
            }
        </tbody>
    </table>
}


同样,工作示例和完整代码在GitHub上:https://github.com/johndpalm/IdentityUserPropertiesSample

并且任何反馈,更正或改进将不胜感激。

关于asp.net - 如何访问Microsoft.Owin.Security.xyz OnAuthenticated上下文AddClaims值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19456008/

10-09 18:38