Social authentication via Google in ASP.NET Core MVC

Posted on Sunday, 29th May 2016

Lately I’ve been re-developing my blog and moving it to .NET Core MVC. As I’ve been doing this I decided to change authentication methods to take advantage of Google’s OAuth API as I didn’t want the hastle of managing username and passwords.

Initially, I started looking at the SimpleAuthentication library - but quickly realised ASP.NET Core already provided support for third party authentication providers via the Microsoft.AspNet.Authentication library.

Having implemented cookie based authentication I thought I’d take a moment to demonstrate how easy it is with ASP.NET’s new middleware functionality.

Let’s get started.

Sign up for Google Auth Service

Before we start, we’re going to need to register our application with the Google Developer’s Console and create a Client Id and Client Secret (which we’ll use later on in this demonstration).

  1. To do this go to Google’s developer console and click “Create Project”. Enter your project name (in this instance it’s called BlogAuth) then click Create.
  2. Next we need to enable authentication with Google’s social API (Google+). Within the Overview page click the Google+ API link located under Social API and click Enable once the Google+ page has loaded.
  3. At this point you should see a message informing you that we need to create our credentials. To do this click the Credentials link on the left hand side, or the Go to Credentials button.
  4. Go across to the OAuth Consent Screen and enter a name of the application you’re setting up. This name is visible to the user when authenticating. Once done, click Save.
  5. At this point we need to create our ClientId and ClientSecret, so go across to the Credentials tab and click Create Credentials and select OAuth client ID from the dropdown then select Web Application.
  6. Now we need to enter our app details. Enter an app name (used for recognising the app within Google Developer Console) and enter your domain into the Authorized JavaScript origins. If you’re developing locally then enter your localhost address into this field including port number.
  7. Next enter the return path into the Authorized redirect URIs field. This is a callback path that Google will use to set the authorisation cookie. In this instance we’ll want to enter http://:/signin-google (where domain and port are the values you entered in step 6).
  8. Once done click Create.
  9. You should now be greeted with a screen displaying your Client ID and Client Secret. Take a note of these as we’ll need them shortly.

Once you’ve stored your Client ID and Secret somewhere you’re safe to close the Google Developer Console window.

Authentication middleware setup

With our Client ID and Client Secret in hand, our next step is to set up authentication within our application. Before we start, we first need to to import the Microsoft.AspNet.Authentication package (Microsoft.AspNetCore.Authorization if you’re using RC2 or later) into our solution via NuGet using the following command:

// RC1
install Microsoft.AspNet.Authentication

// RC2
install Microsoft.AspNetCore.Authorization

Once installed it’s time to hook it up to ASP.NET Core’s pipeline within your solution’s Startup.cs file.

First we need to register our authentication scheme with ASP.NET. within the ConfigureServices method:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    ...

    // Add authentication middleware and inform .NET Core MVC what scheme we'll be using
    services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{

    ...
    // Adds a cookie-based authentication middleware to application
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        LoginPath = "/account/login",
        AuthenticationScheme = "Cookies",
        AutomaticAuthenticate = true,
        AutomaticChallenge = true
    });

    // Plugin Google Authentication configuration options
    app.UseGoogleAuthentication(new GoogleOptions
    {
        ClientId = "your_client_id",
        ClientSecret = "your_client_secret",
        Scope = { "email", "openid" }
    });

    ...

}

In terms of configuring our ASP.NET Core MVC application to use Google for authentication - we’re done! (yes, it’s that easy, thanks to .NET Core MVC’s middleware approach). 

All that’s left to do now is to plumb in our UI and controllers.

Setting up our controller

First, let’s go ahead and create the controller that we’ll use to authenticate our users. We’ll call this controller AccountController:

public class AccountController : Controller
{
    [HttpGet]
    public IActionResult Login()
    {
        return View();
    }

    public IActionResult External(string provider)
    {
        var authProperties = new AuthenticationProperties
        {
            // Specify where to return the user after successful authentication with Google
            RedirectUri = "/account/secure"
        };

        return new ChallengeResult(provider, authProperties);
    }

    [Authorize]
    public IActionResult Secure()
    {
        // Yay, we're secured! Any unauthenticated access to this action will be redirected to the login screen
        return View();
    }

    public async Task<IActionResult> LogOut()
    {
        await HttpContext.Authentication.SignOutAsync("Cookies");

        return RedirectToAction("Index", "Homepage");
    }
}

Now we’ve created our AccountController that we’ll use to authenticate users, we also need to create our views for the Login and Secure controller actions. Please be aware that these are rather basic and are simply as a means to demonstrate the process of logging in via Google authentication.

// Login.cshtml

<h2>Login</h2>
<a href="/account/external?provider=Google">Sign in with Google</a>

// Secure.cshtml

<h2>Secured!</h2>
This page can only be accessed by authenticated users.

Now, if we fire up our application and head to the /login/ page and click _Sign in with Google_ we should be taken to the Google account authentication screen. Once we click Continue  we should be automatically redirected back to our /secure/ page as expected!