如何访问Microsoft.Owin.Security.xyz OnAuthenticated上下文AddClaims值?

时间:2013-10-18 17:49:15

标签: asp.net asp.net-mvc facebook asp.net-identity owin

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

我可以看到我期待的数据是在登录时返回的,并且在Starup.Auth.cs中被添加为声明。但是,当我在帐户控制器内时,UserManager或UserStore中出现的唯一声明由LOCAL AUTHORITY颁发。 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似乎注意到声明属性。稍后从标识中检索属性时属性为空。

3 个答案:

答案 0 :(得分:16)

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

这对我有用:

在Startup.ConfigureAuth(StartupAuth.cs)中创建一个新的(在此处插入提供程序名称)AuthenticationOptions对象,向其传递客户端ID,客户端密钥和新的AuthenticationProvider。您将使用lambda表达式向OnAuthenticated方法传递一些代码,以将声明添加到包含您从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);
        } 
    }
}

最后,我想显示不属于LOCAL AUTHORITY的任何值。我创建了_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

任何反馈,更正或改进都将受到赞赏。

答案 1 :(得分:1)

因此,本文将解释这一切是如何运作的:Decoupling owin external auth

但简短的回答是,当您从Facebook进行身份验证时,就会给您一个外部身份。然后,您需要获取该外部身份并“登录”本地应用程序身份,您需要将所需的任何声明从外部身份添加到成为User.Identity的ClaimsIdentity。

编辑:为了进一步澄清,您可以在ExternalLoginCallback中执行此操作:

    // GET: /Account/ExternalLoginCallback
    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl) {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null) {
            return RedirectToAction("Login");
        }

        // Sign in this external identity if its already linked
        var user = await UserManager.FindAsync(loginInfo.Login);
        if (user != null) {
            await SignInAsync(user, isPersistent: false);
            return RedirectToLocal(returnUrl);
        }

    private async Task SignInAsync(ApplicationUser user, bool isPersistent) {
        AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

所以你需要将额外的数据传递给SignIn,它看起来像这样:

   ClaimsIdentity id = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

此ClaimsIdentity将包含您添加的声明,您需要将该声明添加到SignInAsync方法中创建的标识中才能显示。

答案 2 :(得分:0)

简而言之,使用AddClaim所需的行如下:

取自约翰斯的答案。

ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);