简体   繁体   中英

Getting User.Identity.Name after AspNet OpenAuth Login MVC

I am using OAuth to sing the user up with Facebook.

I am doing successful signup using the following method:-

Request.GetOwinContext().Authentication.SignIn(id);

This Autheticates the user. I can check this using User.Identity.IsAuthenticated

But I am not able to get the name of the User or any of his details using User.Identity.Name .

How can I get the name of the User who has just been authenticated without going back to the database?

The reason you can't get anything from User.Identity.Name is because there's no actual user record to pull that info from, which means hitting the database wouldn't help you anyways. Sign-in provider logins are handled separately from system user logins, in a separate table in fact. They can and often are tied to an actual user account, but they don't have to be. The provider login is enough to authenticate, and sometimes that may be all that's needed. If you do actually need the user information, then you'll need to create a user record after successful provider login and associate that with the provider login.

The best response that thing I came up with is adding claims and adding the Name claim to the answer.

var newClaims = new Claim[]
                        {
                            new Claim(ClaimTypes.NameIdentifier, PersonId.ToString()),
                            new Claim(ClaimTypes.GivenName, FirstName),
                            new Claim(ClaimTypes.Surname, LastName),
                            new Claim(ClaimTypes.Name, FirstName + LastName),
                            new Claim(ClaimTypes.Email, Email)
                        };

The Name claim that I added would fill the User.Identity.Name field.

I hope this helps someone.

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