Youtube Queuer – Implementing Google Authorization in ASP.NET MVC

As I have mentioned in an eariler post, I’ve started working on a Youtube video queuer. More details are available in the linked post.

First thing to implement in order to fetch a user’s subscriptions is authorization. The user has to give permission for my app to browse related data (subscriptions in this case).

Setup

In order to authorize a user, you need to have an application with this NuGet package*: Google.Apis.Auth. This will install other needed dependencies.

Secondly, you need a valid Google account, then access the Developer Console and setup an OAuth 2.0 client identifier. After that, you have to add Authorised JavaScript origins and Authorised redirect URIs. Mine look like this now:

2017-02-13 22_10_08-OAuth client - playlister.png

The two last redirect URIs are important, as it seems that by default, after authorization, the user is redirected to http://localhost/authorize. Make sure to add them. Save changes and download the JSON file containing the settings, it will be of use in the code.

*: Package is needed in order to easily handle the authorization flow, explained below. You can handle authorization using HttpClient and plain web requests, but that’s probably not a wise thing to do if you have an official client package.

Code

First, we need to load the client secrets file. I have created a simple class for this:

public class GoogleSettingsProvider
{
    private static readonly string SecretFileName = "client_secrets.json";

    public Stream GetSecretsStream()
    {
       var path = HttpContext.Current.Server.MapPath("~/" + SecretFileName);
        return new FileStream(path, FileMode.Open, FileAccess.Read);
    }
}

We can now load the client secrets, so it is time to use the loaded secrets to handle the authorization itself. The process is pretty straightforward:

public class GoogleAuthService
{
    private UserCredential _credential; 

    public async Task AuthorizeUser(Stream stream)
    {
        var secrets = GoogleClientSecrets.Load(stream).Secrets;
        _credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(secrets,
            new List<string>;
            {
                YouTubeService.Scope.Youtube,
                YouTubeService.Scope.YoutubeForceSsl
            }, "user", CancellationToken.None,
            new Google.Apis.Util.Store.FileDataStore(GetType().ToString()));
    }
}

Now, we can create a controller action for handling the authorization:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public async Task<ActionResult>; Authorize()
    {
        var authService = new GoogleAuthService();
        var stream = new GoogleSettingsProvider().GetSecretsStream();
        await authService.AuthorizeUser(stream);

        return View("Index");
    }
}

When all the above implemented, run the application locally. Browsing to localhost/Home/Authorize will show a Google login screen:

google_auth.PNG

Summary

The authorization process does not require much code. Important thing to keep in mind is the fact, that if adding a new redirect URI, you need to download the updated client secrets, as during the authorization, Google API takes into account what is contained in loaded secrets.

Be careful when including a client secrets file in a version control – if your repository is public, then virtually anyone has access to your credentials and access Google API on your account’s behalf, possibly with malicious intent.

Advertisements

One thought on “Youtube Queuer – Implementing Google Authorization in ASP.NET MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s