diff --git a/Owin.Security.Providers/BattleNet/BattleNetAuthenticationExtensions.cs b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationExtensions.cs new file mode 100644 index 0000000..353a8f3 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationExtensions.cs @@ -0,0 +1,28 @@ +using System; + +namespace Owin.Security.Providers.BattleNet +{ + public static class BattleNetAuthenticationExtensions + { + + public static IAppBuilder UseBattleNetAuthentication(this IAppBuilder app, BattleNetAuthenticationOptions options) + { + if (app == null) + throw new ArgumentException("app"); + if (options == null) + throw new ArgumentException("options"); + + app.Use(typeof(BattleNetAuthenticationMiddleware), app, options); + + return app; + } + public static IAppBuilder UseBattleNetAuthentication(this IAppBuilder app, string clientId, string clientSecret) + { + return app.UseBattleNetAuthentication(new BattleNetAuthenticationOptions + { + ClientId = clientId, + ClientSecret = clientSecret + }); + } + } +} diff --git a/Owin.Security.Providers/BattleNet/BattleNetAuthenticationHandler.cs b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationHandler.cs new file mode 100644 index 0000000..5fd3a22 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationHandler.cs @@ -0,0 +1,253 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Security.Claims; +using System.Threading.Tasks; +using Microsoft.Owin.Infrastructure; +using Microsoft.Owin.Logging; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Infrastructure; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Owin.Security.Providers.BattleNet +{ + public class BattleNetAuthenticationHandler : AuthenticationHandler + { + + private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; + private const string TokenEndpoint = "https://eu.battle.net/oauth/token"; + private const string AccountUserIdEndpoint = "https://eu.api.battle.net/account/user/id"; + private const string AccountUserBattleTagEndpoint = "https://eu.api.battle.net/account/user/battletag"; + + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + + public BattleNetAuthenticationHandler(HttpClient httpClient, ILogger logger) + { + _httpClient = httpClient; + _logger = logger; + } + + protected override async Task AuthenticateCoreAsync() + { + AuthenticationProperties properties = null; + + try + { + string code = null; + string state = null; + + var query = Request.Query; + var values = query.GetValues("code"); + if (values != null && values.Count == 1) + { + code = values[0]; + } + values = query.GetValues("state"); + if (values != null && values.Count == 1) + { + state = values[0]; + } + + properties = Options.StateDataFormat.Unprotect(state); + if (properties == null) + { + return null; + } + + // OAuth2 10.12 CSRF + if (!ValidateCorrelationId(properties, _logger)) + { + return new AuthenticationTicket(null, properties); + } + + // Check for error + if (Request.Query.Get("error") != null) + return new AuthenticationTicket(null, properties); + + var requestPrefix = Request.Scheme + "://" + Request.Host; + var redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; + + // Build up the body for the token request + var body = new List> + { + new KeyValuePair("grant_type", "authorization_code"), + new KeyValuePair("code", code), + new KeyValuePair("redirect_uri", redirectUri), + new KeyValuePair("client_id", Options.ClientId), + new KeyValuePair("client_secret", Options.ClientSecret) + }; + + // Request the token + var tokenResponse = await _httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body)); + tokenResponse.EnsureSuccessStatusCode(); + var text = await tokenResponse.Content.ReadAsStringAsync(); + + // Deserializes the token response + var response = JsonConvert.DeserializeObject(text); + var accessToken = (string)response.access_token; + var expires = (string)response.expires_in; + + // Get WoW User Id + var graphResponse = await _httpClient.GetAsync(AccountUserIdEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled); + graphResponse.EnsureSuccessStatusCode(); + text = await graphResponse.Content.ReadAsStringAsync(); + var userId = JObject.Parse(text); + + // Get WoW BattleTag + graphResponse = await _httpClient.GetAsync(AccountUserBattleTagEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled); + graphResponse.EnsureSuccessStatusCode(); + text = await graphResponse.Content.ReadAsStringAsync(); + var battleTag = JObject.Parse(text); + + + var context = new BattleNetAuthenticatedContext(Context, userId, battleTag, accessToken, expires) + { + Identity = new ClaimsIdentity( + Options.AuthenticationType, + ClaimsIdentity.DefaultNameClaimType, + ClaimsIdentity.DefaultRoleClaimType) + }; + + if (!string.IsNullOrEmpty(context.Id)) + { + context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.BattleTag)) + { + context.Identity.AddClaim(new Claim("urn:battlenet:battletag", context.BattleTag, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.AccessToken)) + { + context.Identity.AddClaim(new Claim("urn:battlenet:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType)); + } + context.Properties = properties; + + await Options.Provider.Authenticated(context); + + return new AuthenticationTicket(context.Identity, context.Properties); + + } + catch (Exception ex) + { + _logger.WriteError(ex.Message); + } + return new AuthenticationTicket(null, properties); + } + + protected override Task ApplyResponseChallengeAsync() + { + if (Response.StatusCode != 401) + { + return Task.FromResult(null); + } + + var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); + + if (challenge != null) + { + var baseUri = + Request.Scheme + + Uri.SchemeDelimiter + + Request.Host + + Request.PathBase; + + var currentUri = + baseUri + + Request.Path + + Request.QueryString; + + var redirectUri = + baseUri + + Options.CallbackPath; + + var properties = challenge.Properties; + if (string.IsNullOrEmpty(properties.RedirectUri)) + { + properties.RedirectUri = currentUri; + } + + // OAuth2 10.12 CSRF + GenerateCorrelationId(properties); + + // comma separated + var scope = string.Join(" ", Options.Scope); + + var state = Options.StateDataFormat.Protect(properties); + + var authorizationEndpoint = + "https://eu.battle.net/oauth/authorize" + + "?response_type=code" + + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + + "&scope=" + Uri.EscapeDataString(scope) + + "&state=" + Uri.EscapeDataString(state); + + Response.Redirect(authorizationEndpoint); + } + + return Task.FromResult(null); + + + + } + + public override async Task InvokeAsync() + { + + return await InvokeReplyPathAsync(); + + } + + private async Task InvokeReplyPathAsync() + { + if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) + { + // TODO: error responses + + var ticket = await AuthenticateAsync(); + if (ticket == null) + { + _logger.WriteWarning("Invalid return state, unable to redirect."); + Response.StatusCode = 500; + return true; + } + + var context = new BattleNetReturnEndpointContext(Context, ticket) + { + SignInAsAuthenticationType = Options.SignInAsAuthenticationType, + RedirectUri = ticket.Properties.RedirectUri + }; + + await Options.Provider.ReturnEndpoint(context); + + if (context.SignInAsAuthenticationType != null && + context.Identity != null) + { + ClaimsIdentity grantIdentity = context.Identity; + if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) + { + grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType); + } + Context.Authentication.SignIn(context.Properties, grantIdentity); + } + + if (!context.IsRequestCompleted && context.RedirectUri != null) + { + string redirectUri = context.RedirectUri; + if (context.Identity == null) + { + // add a redirect hint that sign-in failed in some way + redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied"); + } + Response.Redirect(redirectUri); + context.RequestCompleted(); + } + + return context.IsRequestCompleted; + } + return false; + } + } +} diff --git a/Owin.Security.Providers/BattleNet/BattleNetAuthenticationMiddleware.cs b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationMiddleware.cs new file mode 100644 index 0000000..e54e1fa --- /dev/null +++ b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationMiddleware.cs @@ -0,0 +1,84 @@ +using System; +using System.Globalization; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Logging; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.DataHandler; +using Microsoft.Owin.Security.DataProtection; +using Microsoft.Owin.Security.Infrastructure; +using Owin.Security.Providers.Properties; + +namespace Owin.Security.Providers.BattleNet +{ + public class BattleNetAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public BattleNetAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, BattleNetAuthenticationOptions options) + : base(next, options) + { + if (String.IsNullOrWhiteSpace(Options.ClientId)) + throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, + Resources.Exception_OptionMustBeProvided, "ClientId")); + if (String.IsNullOrWhiteSpace(Options.ClientSecret)) + throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, + Resources.Exception_OptionMustBeProvided, "ClientSecret")); + + _logger = app.CreateLogger(); + + if (Options.Provider == null) + Options.Provider = new BattleNetAuthenticationProvider(); + + if (Options.StateDataFormat == null) + { + var dataProtector = app.CreateDataProtector( + typeof(BattleNetAuthenticationMiddleware).FullName, + Options.AuthenticationType, "v1"); + Options.StateDataFormat = new PropertiesDataFormat(dataProtector); + } + + if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType)) + Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(); + + _httpClient = new HttpClient(ResolveHttpMessageHandler(Options)) + { + Timeout = Options.BackchannelTimeout, + MaxResponseContentBufferSize = 1024 * 1024 * 10 + }; + } + + /// + /// Provides the object for processing + /// authentication-related requests. + /// + /// + /// An configured with the + /// supplied to the constructor. + /// + protected override AuthenticationHandler CreateHandler() + { + return new BattleNetAuthenticationHandler(_httpClient, _logger); + } + + private static HttpMessageHandler ResolveHttpMessageHandler(BattleNetAuthenticationOptions options) + { + HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler(); + + // If they provided a validator, apply it or fail. + if (options.BackchannelCertificateValidator != null) + { + // Set the cert validate callback + var webRequestHandler = handler as WebRequestHandler; + if (webRequestHandler == null) + { + throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch); + } + webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate; + } + + return handler; + } + } +} diff --git a/Owin.Security.Providers/BattleNet/BattleNetAuthenticationOptions.cs b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationOptions.cs new file mode 100644 index 0000000..9589cb0 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/BattleNetAuthenticationOptions.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; + +namespace Owin.Security.Providers.BattleNet +{ + public class BattleNetAuthenticationOptions : AuthenticationOptions + { + /// + /// Initializes a new . + /// By default the scope is only wow.profile but there is also the scope for sc2.profile + /// + public BattleNetAuthenticationOptions() + : base("BattleNet") + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-battlenet"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = new List + { + "wow.profile" + }; + BackchannelTimeout = TimeSpan.FromSeconds(60); + } + + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to Battle.net. + /// + /// + /// The pinned certificate validator. + /// + /// + /// If this property is null then the default certificate checks are performed, + /// validating the subject name and if the signing chain is a trusted party. + /// + public ICertificateValidator BackchannelCertificateValidator { get; set; } + + /// + /// The HttpMessageHandler used to communicate with Battle.net. + /// This cannot be set at the same time as BackchannelCertificateValidator unless the value + /// can be downcast to a WebRequestHandler. + /// + public HttpMessageHandler BackchannelHttpHandler { get; set; } + + /// + /// Gets or sets timeout value in milliseconds for back channel communications with Battle.net. + /// + /// + /// The back channel timeout in milliseconds. + /// + public TimeSpan BackchannelTimeout { get; set; } + + /// + /// The request path within the application's base path where the user-agent will be returned. + /// The middleware will process this request when it arrives. + /// Default value is "/signin-battlenet". + /// + public PathString CallbackPath { get; set; } + + /// + /// Get or sets the text that the user can display on a sign in user interface. + /// + public string Caption + { + get { return Description.Caption; } + set { Description.Caption = value; } + } + + /// + /// Gets or sets the Battle.net supplied Client Id + /// + public string ClientId { get; set; } + + /// + /// Gets or sets the Battle.net supplied Client Secret + /// + public string ClientSecret { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public IBattleNetAuthenticationProvider Provider { get; set; } + + /// + /// A list of permissions to request. + /// + public IList Scope { get; private set; } + + /// + /// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user + /// . + /// + public string SignInAsAuthenticationType { get; set; } + + /// + /// Gets or sets the type used to secure data handled by the middleware. + /// + public ISecureDataFormat StateDataFormat { get; set; } + + } +} diff --git a/Owin.Security.Providers/BattleNet/Constants.cs b/Owin.Security.Providers/BattleNet/Constants.cs new file mode 100644 index 0000000..fd9c1e7 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/Constants.cs @@ -0,0 +1,8 @@ + +namespace Owin.Security.Providers.BattleNet +{ + internal static class Constants + { + internal const string DefaultAuthenticationType = "BattleNet"; + } +} diff --git a/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticatedContext.cs b/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticatedContext.cs new file mode 100644 index 0000000..bb98895 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticatedContext.cs @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Globalization; +using System.Security.Claims; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; +using Newtonsoft.Json.Linq; + +namespace Owin.Security.Providers.BattleNet +{ + /// + /// Contains information about the login session as well as the user . + /// + public class BattleNetAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The JSON-serialized userId + /// The JSON-serialized battleTag + /// Battle.net Access token + /// Seconds until expiration + public BattleNetAuthenticatedContext(IOwinContext context, JObject userId, JObject battleTag, string accessToken, string expires) + : base(context) + { + JsonUserId = userId; + JsonBattleTag = battleTag; + AccessToken = accessToken; + + int expiresValue; + if (Int32.TryParse(expires, NumberStyles.Integer, CultureInfo.InvariantCulture, out expiresValue)) + { + ExpiresIn = TimeSpan.FromSeconds(expiresValue); + } + + Id = TryGetValue(userId, "id"); + BattleTag = TryGetValue(battleTag, "battletag"); + + } + + /// + /// Gets the JSON-serialized user ID + /// + /// + /// Contains the Battle.net user ID obtained from the endpoint https://eu.api.battle.net/account/user/id + /// + public JObject JsonUserId { get; private set; } + + /// + /// Gets the JSON-serialized BattleTag + /// + /// + /// Contains the Battle.net battle tag obtained from the endpoint https://eu.api.battle.net/account/user/battletag. For more information + /// see https://dev.battle.net/io-docs + /// + public JObject JsonBattleTag { get; private set; } + + /// + /// Gets the Battle.net OAuth access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Battle.net access token expiration time + /// + public TimeSpan? ExpiresIn { get; set; } + + /// + /// Gets the Battle.net user ID + /// + public string Id { get; private set; } + + /// + /// Get Wow users battle tag + /// + public string BattleTag { get; private set; } + + /// + /// Gets the representing the user + /// + public ClaimsIdentity Identity { get; set; } + + /// + /// Gets or sets a property bag for common authentication properties + /// + public AuthenticationProperties Properties { get; set; } + + private static string TryGetValue(JObject user, string propertyName) + { + JToken value; + return user.TryGetValue(propertyName, out value) ? value.ToString() : null; + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticationProvider.cs b/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticationProvider.cs new file mode 100644 index 0000000..1482200 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/Provider/BattleNetAuthenticationProvider.cs @@ -0,0 +1,51 @@ +using System; +using System.Threading.Tasks; + + +namespace Owin.Security.Providers.BattleNet +{ + /// + /// Default implementation. + /// + public class BattleNetAuthenticationProvider : IBattleNetAuthenticationProvider + { + /// + /// Initializes a + /// + public BattleNetAuthenticationProvider() + { + OnAuthenticated = context => Task.FromResult(null); + OnReturnEndpoint = context => Task.FromResult(null); + } + + /// + /// Gets or sets the function that is invoked when the Authenticated method is invoked. + /// + public Func OnAuthenticated { get; set; } + + /// + /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. + /// + public Func OnReturnEndpoint { get; set; } + + /// + /// Invoked whenever Battle.net successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public Task Authenticated(BattleNetAuthenticatedContext context) + { + return OnAuthenticated(context); + } + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + public Task ReturnEndpoint(BattleNetReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} diff --git a/Owin.Security.Providers/BattleNet/Provider/BattleNetReturnEndpointContext.cs b/Owin.Security.Providers/BattleNet/Provider/BattleNetReturnEndpointContext.cs new file mode 100644 index 0000000..d0449f4 --- /dev/null +++ b/Owin.Security.Providers/BattleNet/Provider/BattleNetReturnEndpointContext.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; + +namespace Owin.Security.Providers.BattleNet +{ + /// + /// Provides context information to middleware providers. + /// + public class BattleNetReturnEndpointContext : ReturnEndpointContext + { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public BattleNetReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/Owin.Security.Providers/BattleNet/Provider/IBattleNetAuthenticationProvider.cs b/Owin.Security.Providers/BattleNet/Provider/IBattleNetAuthenticationProvider.cs new file mode 100644 index 0000000..e045a3d --- /dev/null +++ b/Owin.Security.Providers/BattleNet/Provider/IBattleNetAuthenticationProvider.cs @@ -0,0 +1,21 @@ +using System.Threading.Tasks; + +namespace Owin.Security.Providers.BattleNet +{ + public interface IBattleNetAuthenticationProvider + { + /// + /// Invoked whenever Battle.net succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(BattleNetAuthenticatedContext context); + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + Task ReturnEndpoint(BattleNetReturnEndpointContext context); + } +} diff --git a/Owin.Security.Providers/Owin.Security.Providers.csproj b/Owin.Security.Providers/Owin.Security.Providers.csproj index e891268..f270997 100644 --- a/Owin.Security.Providers/Owin.Security.Providers.csproj +++ b/Owin.Security.Providers/Owin.Security.Providers.csproj @@ -67,6 +67,14 @@ + + + + + + + + @@ -76,6 +84,7 @@ + diff --git a/Owin.Security.Providers/Owin.Security.Providers.csproj.DotSettings b/Owin.Security.Providers/Owin.Security.Providers.csproj.DotSettings index 577af8a..6c10e3b 100644 --- a/Owin.Security.Providers/Owin.Security.Providers.csproj.DotSettings +++ b/Owin.Security.Providers/Owin.Security.Providers.csproj.DotSettings @@ -1,4 +1,5 @@  + True True True True diff --git a/README.md b/README.md index fc683bc..2407237 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ Provides a set of extra authentication providers for OWIN ([Project Katana](http - GitHub - Instagram - StackExchange + - Battle.net - OpenID - Generic OpenID 2.0 provider - Steam