GibboK
GibboK

Reputation: 73908

DotNetOpenAuth how to retrieve the email and name from OpenId

I'm using DotNetOpenAuth with MVC 3. I'm able to authenticate with OpenId.

So my URL pointing to a controller has a variable appended OpenId=

Here is an example:

https://www.google.com/accounts/o8/id?id=DFtOawDkCUoLb3YxPzmrEI59-JiSZiAeR-NWw-0

http://mysite.com/Account/Register?OpenID=.......

How how can I get the email and name for the OpenId account and showing to the View?

switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    LogOnModel lm = new LogOnModel();
                    lm.OpenID = response.ClaimedIdentifier;
                    // Check if user exist
                    MembershipUser user = MembershipService.GetUser(lm.OpenID);
                    if (user != null)
                    {
                        lm.UserName = user.UserName;
                        FormsService.SignIn(user.UserName, false);
                    }

                    return View("LogOn", lm);

                case AuthenticationStatus.Canceled:
                    ViewBag.Message = "Canceled at provider";
                    return View("LogOn");
                case AuthenticationStatus.Failed:
                    ViewBag.Message = response.Exception.Message;
                    return View("LogOn");
            }

Upvotes: 2

Views: 456

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

var fetchResponse = response.GetExtension<FetchResponse>();
string email = String.Empty; 
if (fetchResponse != null)
{
    email =  fetchResponse.GetAttributeValue(WellKnownAttributes.Contact.Email);
}  

But don't forget to ask for it when sending the request so that the user could authorize you to have this information during the authentication phase with his OpenId provider:

IAuthenticationRequest request = openid.CreateRequest(openidurl);
var fetchRequest = new FetchRequest();
fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
request.AddExtension(fetch);
request.RedirectToProvider();

Upvotes: 3

Related Questions