Email Address in MVC 5 Google Authentication

I’m not proud to admit that I spent hours trying to figure out this very simple problem. The goal was simple: when a user logs into my web application using Google authentication, I want to be able to grab their email address so I can store it as part of their user profile. As expected, this is very simple.

I’m assuming you’ve already enabled Google authentication by uncommenting app.UseGoogleAuthentication() in your Startup.Auth.cs.

To get the email address, just hop on over to AccountController.ExternalLoginCallback. Here, after the user has successfully authenticated with Google, you can grab the external identity. That external identity has some default claims in it, one of which (for Google Authentication at least) is the user’s email address.

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

        var externalIdentity = await AuthenticationManager
            .GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

        var emailClaim = externalIdentity.Claims.FirstOrDefault(x => 
            x.Type.Equals(
                "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", 
                StringComparison.OrdinalIgnoreCase));

        var emailAddress = emailClaim != null 
            ? emailClaim.Value 
            : null;

        // Remainder of method excluded for brevity...

The email address claim is identified by the http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress type. If you find that claim, it’s Value is the user’s email address.

If you find that you need other information that is not provided in the external identity by default, John Palmer has some great examples for adding claims on the IdentityUserPropertiesSample GitHub project.

Pass a Connection String to a Generated DbContext

The default DbContext generated with your Entity Data Model has one constructor that takes no arguments. If you need to build the connection string programatically and pass it to the DbContext, you will have to add your own constructor. However, if you do this in the generated file, {ModelName}.Context.cs, you will lose your changes the next time the {ModelName}.Context.tt script is run.

The solution is to edit the script, {ModelName}.Context.tt. Just add the following code after the code to generate the default constructor (around line 71). Run the script (Ctrl+S), and verify that the new constructor exists in {ModelName}.Context.cs.

    public <#=code.Escape(container)#>(string nameOrConnectionString)
    : base(nameOrConnectionString)
    {
<#
if (!loader.IsLazyLoadingEnabled(container))
{
#>
    this.Configuration.LazyLoadingEnabled = false;
<#
}
#>
    }

How Not To Restart A ClickOnce Application

Normally if you need to restart a WPF application programatically, you would use the following code:

private void Restart() 
{
    System.Diagnostics.Process.Start(
        Application.ResourceAssembly.Location); 
    Application.Current.Shutdown(); 
}

If you have a ClickOnce WPF application, you do not want to do this. In order to understand why, you need to understand how a ClickOnce application is normally launched.

Continue reading How Not To Restart A ClickOnce Application

Borderless WPF Window

I’ve put together a very simple borderless WPF window that complements Microsoft’s Metro style quite well. I won’t go into a lot of detail here, since the code does most of the talking, but I will go over the important parts here. If you want to skip right to the source code, you can find it over at GitHub: http://bit.ly/N7afKQ Continue reading Borderless WPF Window