Skip to content

Instantly share code, notes, and snippets.

@n3rd
Created March 13, 2014 20:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save n3rd/9536844 to your computer and use it in GitHub Desktop.
Save n3rd/9536844 to your computer and use it in GitHub Desktop.
Google OAuth 2.0 DelegatingHandler
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace N3rd.Web.MessageHandlers
{
public class AuthenticationHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
IEnumerable<string> authorizationHeaders = null;
if (request.Headers.TryGetValues("Authorization", out authorizationHeaders))
{
await ValidateAuthorizationHeaderAsync(authorizationHeaders.First());
}
return await base.SendAsync(request, cancellationToken);
}
private async Task ValidateAuthorizationHeaderAsync(string authorizationHeader)
{
var credentials = authorizationHeader.Split(' ');
if (credentials.Length >= 2)
{
var authScheme = credentials[0];
var authParam = credentials[1];
if ("Bearer".Equals(authScheme, StringComparison.InvariantCultureIgnoreCase))
{
await ValidateBearerTokenAsync(authParam);
}
}
}
private async Task ValidateBearerTokenAsync(string bearerToken)
{
var httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=" + bearerToken);
var response = await httpClient.SendAsync(request);
if (response.StatusCode == HttpStatusCode.OK)
{
dynamic json = await response.Content.ReadAsAsync<dynamic>();
SetClaimsPrincipal(json);
}
}
private void SetClaimsPrincipal(dynamic json)
{
var usernameClaim = new Claim(ClaimTypes.Name, (string) json.email);
var identity = new ClaimsIdentity(new[] { usernameClaim }, "Google");
var principal = new ClaimsPrincipal(identity);
SetPrincipal(principal);
}
private void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment