From 88bf254a7b4b3979f3631adf5d95d1af278c45be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan=20Negri=C8=9Boiu?= Date: Tue, 20 Feb 2018 18:30:58 -0800 Subject: [PATCH] introduce Typeform OAuth provider (#226) * add Option to specify Production vs. Sandbox Environment also fixes issue https://github.com/TerribleDev/OwinOAuthProviders/issues/54 * ability to specify Production vs. Sandbox environment per auth session in addition to global setting * add examples to show usage of new Production vs. Sandbox Option for Salesforce provider * initial commit for Typeform provider * add Typeform project to solution * use GUID for UserId and add warning regaring use for authentication --- OwinOAuthProviders.sln | 6 + .../App_Start/Startup.Auth.cs | 14 +- .../OwinOAuthProvidersDemo.csproj | 4 + .../Constants.cs | 7 + .../Owin.Security.Providers.Typeform.csproj | 107 +++++++++ .../Properties/AssemblyInfo.cs | 15 ++ .../ITypeformAuthenticationProvider.cs | 24 ++ .../Provider/TypeformAuthenticatedContext.cs | 59 +++++ .../TypeformAuthenticationProvider.cs | 50 ++++ .../Provider/TypeformReturnEndpointContext.cs | 26 +++ .../Resources.Designer.cs | 81 +++++++ .../Resources.resx | 126 ++++++++++ .../TypeformAuthenticationExtensions.cs | 29 +++ .../TypeformAuthenticationHandler.cs | 219 ++++++++++++++++++ .../TypeformAuthenticationMiddleware.cs | 83 +++++++ .../TypeformAuthenticationOptions.cs | 107 +++++++++ .../packages.config | 7 + 17 files changed, 963 insertions(+), 1 deletion(-) create mode 100644 src/Owin.Security.Providers.Typeform/Constants.cs create mode 100644 src/Owin.Security.Providers.Typeform/Owin.Security.Providers.Typeform.csproj create mode 100644 src/Owin.Security.Providers.Typeform/Properties/AssemblyInfo.cs create mode 100644 src/Owin.Security.Providers.Typeform/Provider/ITypeformAuthenticationProvider.cs create mode 100644 src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticatedContext.cs create mode 100644 src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticationProvider.cs create mode 100644 src/Owin.Security.Providers.Typeform/Provider/TypeformReturnEndpointContext.cs create mode 100644 src/Owin.Security.Providers.Typeform/Resources.Designer.cs create mode 100644 src/Owin.Security.Providers.Typeform/Resources.resx create mode 100644 src/Owin.Security.Providers.Typeform/TypeformAuthenticationExtensions.cs create mode 100644 src/Owin.Security.Providers.Typeform/TypeformAuthenticationHandler.cs create mode 100644 src/Owin.Security.Providers.Typeform/TypeformAuthenticationMiddleware.cs create mode 100644 src/Owin.Security.Providers.Typeform/TypeformAuthenticationOptions.cs create mode 100644 src/Owin.Security.Providers.Typeform/packages.config diff --git a/OwinOAuthProviders.sln b/OwinOAuthProviders.sln index f22edb8..3e28843 100644 --- a/OwinOAuthProviders.sln +++ b/OwinOAuthProviders.sln @@ -112,6 +112,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.Pod EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.ArcGISPortal", "src\Owin.Security.Providers.ArcGISPortal\Owin.Security.Providers.ArcGISPortal.csproj", "{18547CA4-D7D3-43C2-81C2-A21FC8151A93}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.Typeform", "src\Owin.Security.Providers.Typeform\Owin.Security.Providers.Typeform.csproj", "{C8862B45-E1D1-4AB7-A83D-3A2FD2A22526}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -338,6 +340,10 @@ Global {18547CA4-D7D3-43C2-81C2-A21FC8151A93}.Debug|Any CPU.Build.0 = Debug|Any CPU {18547CA4-D7D3-43C2-81C2-A21FC8151A93}.Release|Any CPU.ActiveCfg = Release|Any CPU {18547CA4-D7D3-43C2-81C2-A21FC8151A93}.Release|Any CPU.Build.0 = Release|Any CPU + {C8862B45-E1D1-4AB7-A83D-3A2FD2A22526}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8862B45-E1D1-4AB7-A83D-3A2FD2A22526}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8862B45-E1D1-4AB7-A83D-3A2FD2A22526}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8862B45-E1D1-4AB7-A83D-3A2FD2A22526}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs index 3cf891a..dfae802 100755 --- a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs +++ b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs @@ -5,6 +5,7 @@ using Owin; using Owin.Security.Providers.Evernote; using Owin.Security.Providers.PayPal; using Owin.Security.Providers.ArcGISPortal; +using Owin.Security.Providers.Typeform; namespace OwinOAuthProvidersDemo { @@ -357,6 +358,17 @@ namespace OwinOAuthProvidersDemo // AppSecret = "", // DebugUsingRequestHeadersToBuildBaseUri = true //}); + + // WARNING: + // Typeform doesn't supply the user's ID so use this provider for authorization only, not authentication + // because each time you sign in with the same Typeform account it will yield a distinct UserId. + //var typeformOptions = new Owin.Security.Providers.Typeform.TypeformAuthenticationOptions + //{ + // ClientId = "", + // ClientSecret = "", + //}; + //typeformOptions.Scope.Add("forms:read"); + //app.UseTypeformAuthentication(typeformOptions); } - } + } } \ No newline at end of file diff --git a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj index dcb8075..67c3177 100644 --- a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj +++ b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj @@ -431,6 +431,10 @@ {c3cf8734-6aac-4f59-9a3e-1cba8582cd48} Owin.Security.Providers.Twitch + + {c8862b45-e1d1-4ab7-a83d-3a2fd2a22526} + Owin.Security.Providers.Typeform + {3e89eca3-f4e7-4181-b26b-8250d5151044} Owin.Security.Providers.Untappd diff --git a/src/Owin.Security.Providers.Typeform/Constants.cs b/src/Owin.Security.Providers.Typeform/Constants.cs new file mode 100644 index 0000000..6acbe32 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Constants.cs @@ -0,0 +1,7 @@ +namespace Owin.Security.Providers.Typeform +{ + public static class Constants + { + public const string DefaultAuthenticationType = "Typeform"; + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/Owin.Security.Providers.Typeform.csproj b/src/Owin.Security.Providers.Typeform/Owin.Security.Providers.Typeform.csproj new file mode 100644 index 0000000..83e9c4a --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Owin.Security.Providers.Typeform.csproj @@ -0,0 +1,107 @@ + + + + + Debug + AnyCPU + {C8862B45-E1D1-4AB7-A83D-3A2FD2A22526} + Library + Properties + Owin.Security.Providers.Typeform + Owin.Security.Providers.Typeform + v4.5 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 6 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 6 + + + + ..\..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll + True + + + ..\..\packages\Microsoft.Owin.Security.3.0.1\lib\net45\Microsoft.Owin.Security.dll + True + + + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + True + + + ..\..\packages\Owin.1.0\lib\net40\Owin.dll + True + + + + + + + + + + + + + + + + + Resources.resx + True + True + + + + + + + + + + + + + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + + + + + + + + + + + $(PostBuildEventDependsOn); + PostBuildMacros; + + + \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/Properties/AssemblyInfo.cs b/src/Owin.Security.Providers.Typeform/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8679e19 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Properties/AssemblyInfo.cs @@ -0,0 +1,15 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Owin.Security.Providers.Typeform")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Owin.Security.Providers.Typeform")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: Guid("b6a4a4cb-d365-41a0-b4c9-966e7ef19de0")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] diff --git a/src/Owin.Security.Providers.Typeform/Provider/ITypeformAuthenticationProvider.cs b/src/Owin.Security.Providers.Typeform/Provider/ITypeformAuthenticationProvider.cs new file mode 100644 index 0000000..6e71239 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Provider/ITypeformAuthenticationProvider.cs @@ -0,0 +1,24 @@ +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Typeform +{ + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface ITypeformAuthenticationProvider + { + /// + /// Invoked whenever Typeform successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(TypeformAuthenticatedContext 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(TypeformReturnEndpointContext context); + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticatedContext.cs b/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticatedContext.cs new file mode 100644 index 0000000..b6a30e4 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticatedContext.cs @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Linq; +using System.Security.Claims; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; + +namespace Owin.Security.Providers.Typeform +{ + /// + /// Contains information about the login session as well as the user . + /// + public class TypeformAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The JSON-serialized user + /// Typeform Access token + /// Typeform Refresh token + /// Typeform instance url + public TypeformAuthenticatedContext(IOwinContext context, string accessToken) + : base(context) + { + AccessToken = accessToken; + + // Typeform doesn't supply a unique identifier for the user, + // so we generate a fake one because OWIN pipeline requires it + // This means you can only use Typeform OAuth for authorization, not authentication because + // each time you sign in with the same Typeform account this provider will yield a distinct UserId + UserId = Guid.NewGuid().ToString(); + } + + /// + /// Gets the Typeform access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Typeform User ID + /// + [Obsolete("This is not the real UserId because Typeform OAuth endpoint does not provide it. Use Typeform OAuth for authorization, not authentication.")] + public string UserId { 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; } + } +} diff --git a/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticationProvider.cs b/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticationProvider.cs new file mode 100644 index 0000000..1c34734 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Provider/TypeformAuthenticationProvider.cs @@ -0,0 +1,50 @@ +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Typeform +{ + /// + /// Default implementation. + /// + public class TypeformAuthenticationProvider : ITypeformAuthenticationProvider + { + /// + /// Initializes a + /// + public TypeformAuthenticationProvider() + { + 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 Typeform successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(TypeformAuthenticatedContext 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 virtual Task ReturnEndpoint(TypeformReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/Provider/TypeformReturnEndpointContext.cs b/src/Owin.Security.Providers.Typeform/Provider/TypeformReturnEndpointContext.cs new file mode 100644 index 0000000..eb01f46 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Provider/TypeformReturnEndpointContext.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.Typeform +{ + /// + /// Provides context information to middleware providers. + /// + public class TypeformReturnEndpointContext : ReturnEndpointContext + { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public TypeformReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/src/Owin.Security.Providers.Typeform/Resources.Designer.cs b/src/Owin.Security.Providers.Typeform/Resources.Designer.cs new file mode 100644 index 0000000..4f437dd --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Resources.Designer.cs @@ -0,0 +1,81 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace Owin.Security.Providers.Typeform { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + var temp = new global::System.Resources.ResourceManager("Owin.Security.Providers.Typeform.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized string similar to The '{0}' option must be provided.. + /// + internal static string Exception_OptionMustBeProvided { + get { + return ResourceManager.GetString("Exception_OptionMustBeProvided", resourceCulture); + } + } + + /// + /// Looks up a localized string similar to An ICertificateValidator cannot be specified at the same time as an HttpMessageHandler unless it is a WebRequestHandler.. + /// + internal static string Exception_ValidatorHandlerMismatch { + get { + return ResourceManager.GetString("Exception_ValidatorHandlerMismatch", resourceCulture); + } + } + } +} diff --git a/src/Owin.Security.Providers.Typeform/Resources.resx b/src/Owin.Security.Providers.Typeform/Resources.resx new file mode 100644 index 0000000..2a19bea --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/Resources.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + The '{0}' option must be provided. + + + An ICertificateValidator cannot be specified at the same time as an HttpMessageHandler unless it is a WebRequestHandler. + + \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/TypeformAuthenticationExtensions.cs b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationExtensions.cs new file mode 100644 index 0000000..c3622eb --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationExtensions.cs @@ -0,0 +1,29 @@ +using System; + +namespace Owin.Security.Providers.Typeform +{ + public static class TypeformAuthenticationExtensions + { + public static IAppBuilder UseTypeformAuthentication(this IAppBuilder app, + TypeformAuthenticationOptions options) + { + if (app == null) + throw new ArgumentNullException(nameof(app)); + if (options == null) + throw new ArgumentNullException(nameof(options)); + + app.Use(typeof(TypeformAuthenticationMiddleware), app, options); + + return app; + } + + public static IAppBuilder UseTypeformAuthentication(this IAppBuilder app, string clientId, string clientSecret) + { + return app.UseTypeformAuthentication(new TypeformAuthenticationOptions + { + ClientId = clientId, + ClientSecret = clientSecret + }); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/TypeformAuthenticationHandler.cs b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationHandler.cs new file mode 100644 index 0000000..1a491bd --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationHandler.cs @@ -0,0 +1,219 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Threading.Tasks; +using System.Web; +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.Typeform +{ + public class TypeformAuthenticationHandler : AuthenticationHandler + { + private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; + private const string AuthorizationEndpoint = "https://api.typeform.com/oauth/authorize"; + private const string TokenEndpoint = "https://api.typeform.com/oauth/token"; + + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + + public TypeformAuthenticationHandler(HttpClient httpClient, ILogger logger) + { + _httpClient = httpClient; + _logger = logger; + } + + protected override async Task AuthenticateCoreAsync() + { + var properties = new AuthenticationProperties(); + + 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); + } + + 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("code", code), + new KeyValuePair("redirect_uri", redirectUri), + new KeyValuePair("client_id", Options.ClientId), + new KeyValuePair("client_secret", Options.ClientSecret), + new KeyValuePair("grant_type", "authorization_code") + }; + + // Request the token + var requestMessage = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint); + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + requestMessage.Content = new FormUrlEncodedContent(body); + var tokenResponse = await _httpClient.SendAsync(requestMessage, Request.CallCancelled); + tokenResponse.EnsureSuccessStatusCode(); + string content = await tokenResponse.Content.ReadAsStringAsync(); + + var response = JsonConvert.DeserializeObject(content); + string accessToken = response["access_token"].Value(); + + var context = new TypeformAuthenticatedContext(Context, accessToken) + { + Identity = new ClaimsIdentity( + Options.AuthenticationType, + ClaimsIdentity.DefaultNameClaimType, + ClaimsIdentity.DefaultRoleClaimType) + }; + + if (!string.IsNullOrEmpty(context.UserId)) + { + context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, 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, ex); + } + 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) return Task.FromResult(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); + + var state = Options.StateDataFormat.Protect(properties); + + var authorizationEndpoint = + $"{AuthorizationEndpoint}?response_type={"code"}&client_id={Options.ClientId}&redirect_uri={HttpUtility.UrlEncode(redirectUri)}&state={Uri.EscapeDataString(state)}"; + + if (Options.Scope != null && Options.Scope.Count > 0) + { + authorizationEndpoint += $"&scope={string.Join(" ", Options.Scope)}"; + } + + if (Options.Prompt != null) + { + authorizationEndpoint += $"&prompt={Options.Prompt}"; + } + + 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) return false; + // 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 TypeformReturnEndpointContext(Context, ticket) + { + SignInAsAuthenticationType = Options.SignInAsAuthenticationType, + RedirectUri = ticket.Properties.RedirectUri + }; + + await Options.Provider.ReturnEndpoint(context); + + if (context.SignInAsAuthenticationType != null && + context.Identity != null) + { + var 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) return context.IsRequestCompleted; + var 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; + } + } +} diff --git a/src/Owin.Security.Providers.Typeform/TypeformAuthenticationMiddleware.cs b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationMiddleware.cs new file mode 100644 index 0000000..09d8837 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationMiddleware.cs @@ -0,0 +1,83 @@ +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; + +namespace Owin.Security.Providers.Typeform +{ + public class TypeformAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public TypeformAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, + TypeformAuthenticationOptions 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 TypeformAuthenticationProvider(); + + if (Options.StateDataFormat == null) + { + var dataProtector = app.CreateDataProtector( + typeof(TypeformAuthenticationMiddleware).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, + }; + _httpClient.DefaultRequestHeaders.ExpectContinue = false; + } + + /// + /// Provides the object for processing + /// authentication-related requests. + /// + /// + /// An configured with the + /// supplied to the constructor. + /// + protected override AuthenticationHandler CreateHandler() + { + return new TypeformAuthenticationHandler(_httpClient, _logger); + } + + private static HttpMessageHandler ResolveHttpMessageHandler(TypeformAuthenticationOptions options) + { + var handler = options.BackchannelHttpHandler ?? new WebRequestHandler(); + + // If they provided a validator, apply it or fail. + if (options.BackchannelCertificateValidator == null) return handler; + // 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; + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/TypeformAuthenticationOptions.cs b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationOptions.cs new file mode 100644 index 0000000..8f1b11c --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/TypeformAuthenticationOptions.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; + +namespace Owin.Security.Providers.Typeform +{ + public class TypeformAuthenticationOptions : AuthenticationOptions + { + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to Typeform. + /// + /// + /// 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 Typeform. + /// 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 Typeform. + /// + /// + /// 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-Typeform". + /// + 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 Typeform supplied Client ID + /// + public string ClientId { get; set; } + + /// + /// Gets or sets the Typeform supplied Client Secret + /// + public string ClientSecret { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public ITypeformAuthenticationProvider Provider { get; set; } + + /// + /// A list of permissions to request. + /// + public IList Scope { get; private set; } + + /// + /// Specifies how the authorization server prompts the user for reauthentication and reapproval. This parameter is optional. + /// The only values Typeform supports are: + /// login—The authorization server must prompt the user for reauthentication, forcing the user to log in again. + /// consent—The authorization server must prompt the user for reapproval before returning information to the client. + /// It is valid to pass both values, separated by a space, to require the user to both log in and reauthorize. + /// + public string Prompt { get; 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; } + + /// + /// Initializes a new + /// + public TypeformAuthenticationOptions() : base("Typeform") + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-typeform"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = new List(); + BackchannelTimeout = TimeSpan.FromSeconds(60); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Typeform/packages.config b/src/Owin.Security.Providers.Typeform/packages.config new file mode 100644 index 0000000..cbfe6a2 --- /dev/null +++ b/src/Owin.Security.Providers.Typeform/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file