Search code examples
openiddotnetopenauthasp.net-4.5google-openid

Get users email address using Google OpenID


I am trying to retrieve a user's email address from Google via OpenID using DotNetOpenAuth.

My code so far correctly redirects to Google for the current user, and asks for permission for my application to read the email address. On being diverted back to my page however, it bounces straight back to Google. I see why this happens (because the page never enters postback state), but how do you differentiate therefore between the request and response data, so that I can correctly read the email address in the page?

Is there a recommended/industry standard approach for this?

I'm only just starting out with OpenID and DotNetOpenAuth but have strong ASP.NET skills, so please keep your answers clear(!)

Thanks

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    ltl.Text = "Welcome " & User.Identity.Name

    If Not Page.IsPostBack Then
        Dim openid As New OpenIdRelyingParty
        Dim req As IAuthenticationRequest = openid.CreateRequest(User.Identity.Name)
        Dim fetch As New FetchRequest
        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email)
        fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName)
        req.AddExtension(fetch)
        req.RedirectToProvider()
    Else
        Dim openid As New OpenIdRelyingParty
        Dim resp As IAuthenticationResponse = openid.GetResponse()
        If resp IsNot Nothing Then
            Dim fetch As FetchResponse = resp.GetExtension(Of FetchResponse)()
            If fetch IsNot Nothing Then
                Trace.Warn(fetch.GetAttributeValue(WellKnownAttributes.Contact.Email))
            Else
                Trace.Warn("fetch was Nothing")
            End If
        Else
            Trace.Warn("resp was Nothing")
        End If
    End If
End Sub

Solution

  • Have you found the DotNetOpenAuth samples available on SourceForge?

    Here is the recommended pattern:

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        ltl.Text = "Welcome " & User.Identity.Name
    
        Dim openid As New OpenIdRelyingParty
        Dim resp As IAuthenticationResponse = openid.GetResponse()
        If resp Is Nothing Then
            Dim req As IAuthenticationRequest = openid.CreateRequest(User.Identity.Name)
            Dim fetch As New FetchRequest
            fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email)
            fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName)
            req.AddExtension(fetch)
            req.RedirectToProvider()
        Else
            Dim fetch As FetchResponse = resp.GetExtension(Of FetchResponse)()
            If fetch IsNot Nothing Then
                Trace.Warn(fetch.GetAttributeValue(WellKnownAttributes.Contact.Email))
            Else
                Trace.Warn("fetch was Nothing")
            End If
        End If
    End Sub