Created
March 13, 2014 20:56
-
-
Save n3rd/9536844 to your computer and use it in GitHub Desktop.
Google OAuth 2.0 DelegatingHandler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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