diff --git a/OwinOAuthProviders.sln b/OwinOAuthProviders.sln index 6141d54..1b5edd5 100644 --- a/OwinOAuthProviders.sln +++ b/OwinOAuthProviders.sln @@ -1,6 +1,6 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 -VisualStudioVersion = 14.0.24720.0 +VisualStudioVersion = 14.0.25123.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.ArcGISOnline", "src\Owin.Security.Providers.ArcGISOnline\Owin.Security.Providers.ArcGISOnline.csproj", "{8A49FAEF-D365-4D25-942C-1CAD03845A5E}" EndProject @@ -94,6 +94,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.Orc EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OwinOAuthProvidersDemo", "OwinOAuthProvidersDemo\OwinOAuthProvidersDemo.csproj", "{5A438007-0C90-4DAC-BAA1-54A32164067F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.Discord", "src\Owin.Security.Providers.Discord\Owin.Security.Providers.Discord.csproj", "{4BE728EB-778A-41AF-8DEA-0C7159711D44}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -284,6 +286,10 @@ Global {5A438007-0C90-4DAC-BAA1-54A32164067F}.Debug|Any CPU.Build.0 = Debug|Any CPU {5A438007-0C90-4DAC-BAA1-54A32164067F}.Release|Any CPU.ActiveCfg = Release|Any CPU {5A438007-0C90-4DAC-BAA1-54A32164067F}.Release|Any CPU.Build.0 = Release|Any CPU + {4BE728EB-778A-41AF-8DEA-0C7159711D44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4BE728EB-778A-41AF-8DEA-0C7159711D44}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4BE728EB-778A-41AF-8DEA-0C7159711D44}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4BE728EB-778A-41AF-8DEA-0C7159711D44}.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 4608e33..d4fd146 100755 --- a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs +++ b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs @@ -4,6 +4,7 @@ using Microsoft.Owin.Security.Cookies; using Owin; //using Owin.Security.Providers.Orcid; +//using Owin.Security.Providers.Discord; namespace OwinOAuthProvidersDemo { @@ -276,6 +277,8 @@ namespace OwinOAuthProvidersDemo //app.UseDoYouBuzzAuthentication("", ""); //app.("", ""); //app.UseOrcidAuthentication("",""); + + //app.UseDiscordAuthentication("", ""); } } } \ No newline at end of file diff --git a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj index 2d2c708..1b10843 100644 --- a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj +++ b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj @@ -248,6 +248,12 @@ + + + {4be728eb-778a-41af-8dea-0c7159711d44} + Owin.Security.Providers.Discord + + 10.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) diff --git a/src/Owin.Security.Providers.Discord/Constants.cs b/src/Owin.Security.Providers.Discord/Constants.cs new file mode 100644 index 0000000..790ca97 --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Constants.cs @@ -0,0 +1,7 @@ +namespace Owin.Security.Providers.Discord +{ + internal static class Constants + { + public const string DefaultAuthenticationType = "Discord"; + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/DiscordAuthenticationExtensions.cs b/src/Owin.Security.Providers.Discord/DiscordAuthenticationExtensions.cs new file mode 100644 index 0000000..ce5d36d --- /dev/null +++ b/src/Owin.Security.Providers.Discord/DiscordAuthenticationExtensions.cs @@ -0,0 +1,29 @@ +using System; + +namespace Owin.Security.Providers.Discord +{ + public static class DiscordAuthenticationExtensions + { + public static IAppBuilder UseDiscordAuthentication(this IAppBuilder app, + DiscordAuthenticationOptions options) + { + if (app == null) + throw new ArgumentNullException(nameof(app)); + if (options == null) + throw new ArgumentNullException(nameof(options)); + + app.Use(typeof(DiscordAuthenticationMiddleware), app, options); + + return app; + } + + public static IAppBuilder UseDiscordAuthentication(this IAppBuilder app, string clientId, string clientSecret) + { + return app.UseDiscordAuthentication(new DiscordAuthenticationOptions + { + ClientId = clientId, + ClientSecret = clientSecret + }); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/DiscordAuthenticationHandler.cs b/src/Owin.Security.Providers.Discord/DiscordAuthenticationHandler.cs new file mode 100644 index 0000000..926e268 --- /dev/null +++ b/src/Owin.Security.Providers.Discord/DiscordAuthenticationHandler.cs @@ -0,0 +1,248 @@ +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; +using Owin.Security.Providers.Discord.Provider; + +namespace Owin.Security.Providers.Discord +{ + public class DiscordAuthenticationHandler : AuthenticationHandler + { + private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; + private const string TokenEndpoint = "https://discordapp.com/api/oauth2/token"; + private const string UserInfoEndpoint = "https://discordapp.com/api/users/@me"; + + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + + public DiscordAuthenticationHandler(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); + } + + 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) + }; + var request = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint); + request.Content = new FormUrlEncodedContent(body); + + // Request the token + var tokenResponse = + await _httpClient.SendAsync(request); + tokenResponse.EnsureSuccessStatusCode(); + var text = await tokenResponse.Content.ReadAsStringAsync(); + + // Deserializes the token response + dynamic response = JsonConvert.DeserializeObject(text); + var accessToken = (string)response.access_token; + var expires = (string)response.expires_in; + var refreshToken = (string)response.refresh_token; + + // Get the Discord user + var userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint); + userRequest.Headers.Add("Authorization", "Bearer " + Uri.EscapeDataString(accessToken) + ""); + var graphResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled); + graphResponse.EnsureSuccessStatusCode(); + text = await graphResponse.Content.ReadAsStringAsync(); + var user = JObject.Parse(text); + + var context = new DiscordAuthenticatedContext(Context, user, accessToken, expires, refreshToken) + { + Identity = new ClaimsIdentity( + Options.AuthenticationType, + ClaimsIdentity.DefaultNameClaimType, + ClaimsIdentity.DefaultRoleClaimType) + }; + if (!string.IsNullOrEmpty(context.Id)) + { + context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserName, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.UserName)) + { + context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.UserName, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.Email)) + { + context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.Avatar)) + { + context.Identity.AddClaim(new Claim("urn:discord:avatar", context.Avatar, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.Discriminator)) + { + context.Identity.AddClaim(new Claim("urn:discord:discriminator", context.Discriminator, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.AccessToken)) + { + context.Identity.AddClaim(new Claim("urn:discord:accesstoken", context.AccessToken, XmlSchemaString, Options.AuthenticationType)); + } + context.Identity.AddClaim(new Claim("urn:discord:verified", context.Verified.ToString(), 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) 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); + + // comma separated + var scope = string.Join(" ", Options.Scope); + + var state = Options.StateDataFormat.Protect(properties); + + var authorizationEndpoint = + "https://discordapp.com/api/oauth2/authorize" + + "?response_type=code" + + "&client_id=" + Uri.EscapeDataString(Options.ClientId) + + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + + "&scope=" + Uri.EscapeDataString(scope) + + "&state=" + Uri.EscapeDataString(state) + + "&duration=permanent"; + + 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 DiscordReturnEndpointContext(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; + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/DiscordAuthenticationMiddleware.cs b/src/Owin.Security.Providers.Discord/DiscordAuthenticationMiddleware.cs new file mode 100644 index 0000000..de98ebf --- /dev/null +++ b/src/Owin.Security.Providers.Discord/DiscordAuthenticationMiddleware.cs @@ -0,0 +1,75 @@ +using System; +using System.Globalization; +using System.Net; +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.Discord.Provider; + +namespace Owin.Security.Providers.Discord +{ + public class DiscordAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public DiscordAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, + DiscordAuthenticationOptions options) + : base(next, options) + { + if (string.IsNullOrWhiteSpace(Options.ClientId)) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, + "Option must be provided {0}", "ClientId")); + if (string.IsNullOrWhiteSpace(Options.ClientSecret)) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, + "Option must be provided {0}", "ClientSecret")); + + _logger = app.CreateLogger(); + + if (Options.Provider == null) + Options.Provider = new DiscordAuthenticationProvider(); + + if (Options.StateDataFormat == null) + { + var dataProtector = app.CreateDataProtector( + typeof(DiscordAuthenticationMiddleware).FullName, + Options.AuthenticationType, "v1"); + Options.StateDataFormat = new PropertiesDataFormat(dataProtector); + } + + if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType)) + Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(); + + _httpClient = new HttpClient(ResolveHttpMessageHandler()) + { + 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 DiscordAuthenticationHandler(_httpClient, _logger); + } + + private HttpClientHandler ResolveHttpMessageHandler() + { + return new HttpClientHandler + { + Credentials = new NetworkCredential(Options.ClientId, Options.ClientSecret) + }; + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/DiscordAuthenticationOptions.cs b/src/Owin.Security.Providers.Discord/DiscordAuthenticationOptions.cs new file mode 100644 index 0000000..9497e7a --- /dev/null +++ b/src/Owin.Security.Providers.Discord/DiscordAuthenticationOptions.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Owin.Security.Providers.Discord.Provider; + +namespace Owin.Security.Providers.Discord +{ + public class DiscordAuthenticationOptions : AuthenticationOptions + { + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to Discord. + /// + /// + /// 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 Discord. + /// 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 Discord. + /// + /// + /// 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-Discord". + /// + 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 Discord supplied Client ID + /// + public string ClientId { get; set; } + + /// + /// Gets or sets the Discord supplied Client Secret + /// + public string ClientSecret { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public IDiscordAuthenticationProvider 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; } + + /// + /// Initializes a new + /// + public DiscordAuthenticationOptions() + : base("Discord") + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-discord"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = new List + { + "identify", + "email" + }; + BackchannelTimeout = TimeSpan.FromSeconds(60); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/Owin.Security.Providers.Discord.csproj b/src/Owin.Security.Providers.Discord/Owin.Security.Providers.Discord.csproj new file mode 100644 index 0000000..c6a336d --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Owin.Security.Providers.Discord.csproj @@ -0,0 +1,103 @@ + + + + + Debug + AnyCPU + {4BE728EB-778A-41AF-8DEA-0C7159711D44} + Library + Properties + Owin.Security.Providers.Discord + Owin.Security.Providers.Discord + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\..\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.Discord/Properties/AssemblyInfo.cs b/src/Owin.Security.Providers.Discord/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c7c2c51 --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Properties/AssemblyInfo.cs @@ -0,0 +1,15 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyTitle("Owin.Security.Providers.Discord")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Owin.Security.Providers.Discord")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] +[assembly: ComVisible(false)] +[assembly: Guid("5d0f8dfb-2057-48a2-8eef-8f09645e8b4e")] +[assembly: AssemblyVersion("2.0.0.0")] +[assembly: AssemblyFileVersion("2.0.0.0")] diff --git a/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticatedContext.cs b/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticatedContext.cs new file mode 100644 index 0000000..07bf436 --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticatedContext.cs @@ -0,0 +1,111 @@ +// 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.Discord.Provider +{ + /// + /// Contains information about the login session as well as the user . + /// + public class DiscordAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The JSON-serialized user + /// Discord Access token + /// Seconds until expiration + /// + public DiscordAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string expires, string refreshToken) + : base(context) + { + User = user; + AccessToken = accessToken; + RefreshToken = refreshToken; + int expiresValue; + if (int.TryParse(expires, NumberStyles.Integer, CultureInfo.InvariantCulture, out expiresValue)) + { + ExpiresIn = TimeSpan.FromSeconds(expiresValue); + } + Id = TryGetValue(user, "id"); + UserName = TryGetValue(user, "username"); + Discriminator = TryGetValue(user, "discriminator"); + Avatar = TryGetValue(user, "avatar"); + Email = TryGetValue(user, "email"); + Verified = TryGetValue(user, "verified") == "true"; + } + + public string RefreshToken { get; set; } + + /// + /// Gets the JSON-serialized user + /// + /// + /// Contains the Discord user + /// + public JObject User { get; private set; } + + /// + /// Gets the Discord access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Discord access token expiration time + /// + public TimeSpan? ExpiresIn { get; set; } + + /// + /// Gets the Discord user ID + /// + public string Id { get; private set; } + + /// + /// Gets the Discord user discriminator + /// + public string Discriminator { get; private set; } + + /// + /// Gets the Discord user avatar + /// + public string Avatar { get; private set; } + + /// + /// Gets the Discord user email + /// + public string Email { get; private set; } + + /// + /// Gets the Discord username + /// + public string UserName { get; private set; } + + /// + /// Gets whether the user is verified or not. + /// + public bool Verified { get; private set; } = false; + + /// + /// 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; + } + } +} diff --git a/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticationProvider.cs b/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticationProvider.cs new file mode 100644 index 0000000..39f881d --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Provider/DiscordAuthenticationProvider.cs @@ -0,0 +1,50 @@ +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Discord.Provider +{ + /// + /// Default implementation. + /// + public class DiscordAuthenticationProvider : IDiscordAuthenticationProvider + { + /// + /// Initializes a + /// + public DiscordAuthenticationProvider() + { + 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 Discord successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(DiscordAuthenticatedContext 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(DiscordReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/Provider/DiscordReturnEndpointContext.cs b/src/Owin.Security.Providers.Discord/Provider/DiscordReturnEndpointContext.cs new file mode 100644 index 0000000..d998f80 --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Provider/DiscordReturnEndpointContext.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.Discord.Provider +{ + /// + /// Provides context information to middleware providers. + /// + public class DiscordReturnEndpointContext : ReturnEndpointContext + { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public DiscordReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/src/Owin.Security.Providers.Discord/Provider/IDiscordAuthenticationProvider.cs b/src/Owin.Security.Providers.Discord/Provider/IDiscordAuthenticationProvider.cs new file mode 100644 index 0000000..39c013d --- /dev/null +++ b/src/Owin.Security.Providers.Discord/Provider/IDiscordAuthenticationProvider.cs @@ -0,0 +1,24 @@ +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Discord.Provider +{ + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface IDiscordAuthenticationProvider + { + /// + /// Invoked whenever Discord successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(DiscordAuthenticatedContext 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(DiscordReturnEndpointContext context); + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.Discord/Resources.Designer.cs b/src/Owin.Security.Providers.Discord/Resources.Designer.cs new file mode 100644 index 0000000..712ce7c --- /dev/null +++ b/src/Owin.Security.Providers.Discord/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.Discord { + 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.Discord.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.Discord/Resources.resx b/src/Owin.Security.Providers.Discord/Resources.resx new file mode 100644 index 0000000..2a19bea --- /dev/null +++ b/src/Owin.Security.Providers.Discord/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.Discord/packages.config b/src/Owin.Security.Providers.Discord/packages.config new file mode 100644 index 0000000..a35e97b --- /dev/null +++ b/src/Owin.Security.Providers.Discord/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file