简体   繁体   中英

Can't load facebook identity in ASP.NET using Owin

I have problem with loading Facebook identity. The page is redirect to facebook properly, but when I get back to my site, I can't read identity from Owin.

Here is my Startup.Auth.cs

var cookieOptions = new CookieAuthenticationOptions
{
    LoginPath = new PathString("/default.aspx")
};

app.UseCookieAuthentication(cookieOptions);
app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);
var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
{
    AppId = ExternalConnections.Where(o => o.Name == "Facebook" && o.Exist && o.SiteId == site.Key).First() != null ? ExternalConnections.Where(o => o.Name == "Facebook" && o.Exist && o.SiteId == site.Key).First().AppId : string.Empty,
    AppSecret = ExternalConnections.Where(o => o.Name == "Facebook" && o.Exist && o.SiteId == site.Key).First() != null ? ExternalConnections.Where(o => o.Name == "Facebook" && o.Exist && o.SiteId == site.Key).First().AppSecretKey : string.Empty,
    SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(),
    CallbackPath = new PathString("/Default.aspx/")
};

facebookAuthenticationOptions.Provider = new FacebookAuthenticationProvider
{
    OnAuthenticated = async context =>
    {
        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
        foreach (var claim in context.User)
        {
            var claimType = string.Format("urn:facebook:{0}", claim.Key);
            string claimValue = claim.Value.ToString();
            if (!context.Identity.HasClaim(claimType, claimValue))
                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
        }
    }
};

facebookAuthenticationOptions.Scope.Add("email");
facebookAuthenticationOptions.Scope.Add("public_profile");

app2.UseFacebookAuthentication(facebookAuthenticationOptions);

And my PageBase.cs to handle login:

var ctx = Context.GetOwinContext();
var user = ctx != null ? ctx.Authentication.User : new ClaimsPrincipal();
if (user != null && user.Identities.Count() > 0 && user.Identity.IsAuthenticated)
{
    var claimsPrincipal = new ClaimsPrincipal(user.Identity);
    Thread.CurrentPrincipal = claimsPrincipal;
    var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

    if (identity.Claims.Count() > 0)
    {
        switch (identity.Claims.First().OriginalIssuer)
        {
            case "Facebook":

                if (!featureExternalLoginFacebook) { break; }

                id = identity.Claims.Where(c => c.Type == "urn:facebook:id").Select(c => c.Value).SingleOrDefault();
                name = identity.Claims.Where(c => c.Type == ClaimTypes.Name).Select(c => c.Value).SingleOrDefault();
                accessToken = identity.Claims.Where(c => c.Type == "FacebookAccessToken").Select(c => c.Value).SingleOrDefault();

                var url = string.Format("https://graph.facebook.com/v2.5/{0}?fields=email,first_name,last_name&access_token={1}", id, accessToken);

                var req = WebRequest.Create(url);
                req.Method = "GET";
                req.ContentType = "application/json";

                using (var res = new StreamReader(req.GetResponse().GetResponseStream()))
                {
                    dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(res.ReadToEnd());

                    if (result.id != null && result.id == id)
                    {
                        email = result.email != null ? result.email : string.Empty;
                        firstName = result.first_name != null ? result.first_name : string.Empty;
                        lastName = result.last_name != null ? result.last_name : string.Empty;
                    }
                }

                break;
        }

        externalApp = identity.Claims.First().OriginalIssuer;

        if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(email))
        {
            return true;
        }
    }

In user.Identities, I had IsAuthenticated as true. Now I have always false, and I don't have identity.Claims for Facebook.

How I can get Facebook user information about logged user, resp. how I can get facebook identity?

Facebook has recently deprecated some of their OAuth endpoints. If you are using the NuGet package Microsoft.Owin.Security.Facebook 3.0.1, you'll need to update to the most recent version (which will also update several related packages).

  • Right click on project
  • Select "Manage NuGet Packages"
  • Select "Installed"
  • Search for "Facebook" or find the package from the list
  • Select "Microsoft.Owin.Security.Facebook" and click "Update"

Reference: https://github.com/aspnet/AspNetKatana/issues/38

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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