diff --git a/OwinOAuthProviders.sln b/OwinOAuthProviders.sln index 1d462ce..81b5545 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.25420.1 +# Visual Studio 15 +VisualStudioVersion = 15.0.26730.16 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 @@ -108,6 +108,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.Eve EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Owin.Security.Providers.WSO2", "src\Owin.Security.Providers.WSO2\Owin.Security.Providers.WSO2.csproj", "{8FD3A9CB-E684-42C0-A8BF-7746FDD3D43C}" 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.Podbean", "src\Owin.Security.Providers.Podbean\Owin.Security.Providers.Podbean.csproj", "{A7B95FD4-08AD-499F-B574-07560CC2A63F}" EndProject Global @@ -337,6 +339,7 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {EDFDB942-6583-4AD9-A868-B354B5BF07FC} EndGlobalSection EndGlobal diff --git a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs index b1bf7d8..2879b4a 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.Evernote; using Owin.Security.Providers.PayPal; +using Owin.Security.Providers.ArcGISPortal; namespace OwinOAuthProvidersDemo { @@ -155,6 +156,12 @@ namespace OwinOAuthProvidersDemo // clientId: "", // clientSecret: ""); + //app.UseArcGISPortalAuthentication(new ArcGISPortalAuthenticationOptions( + // "My ArcGIS Portal", + // "https://arcgisportal.mydomain.com/", + // "", + // "")); + //app.UseWordPressAuthentication( // clientId: "", // clientSecret: ""); diff --git a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj index 723cc9d..1211eb5 100644 --- a/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj +++ b/OwinOAuthProvidersDemo/OwinOAuthProvidersDemo.csproj @@ -259,6 +259,10 @@ {4fd7b873-1994-4990-aa40-c37060121494} Owin.Security.Providers.OpenIDBase + + {18547ca4-d7d3-43c2-81c2-a21fc8151a93} + Owin.Security.Providers.ArcGISPortal + {8a49faef-d365-4d25-942c-1cad03845a5e} Owin.Security.Providers.ArcGISOnline diff --git a/README.md b/README.md index 9bcbf4d..cdb7d36 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ Provides a set of extra authentication providers for OWIN ([Project Katana](http://katanaproject.codeplex.com/)). This project includes providers for: - OAuth - ArcGISOnline + - ArcGISPortal - Asana - Backlog - Battle.net diff --git a/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationExtensions.cs b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationExtensions.cs new file mode 100644 index 0000000..115201f --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationExtensions.cs @@ -0,0 +1,20 @@ +using System; + +namespace Owin.Security.Providers.ArcGISPortal +{ + public static class ArcGISPortalAuthenticationExtensions + { + public static IAppBuilder UseArcGISPortalAuthentication(this IAppBuilder app, + ArcGISPortalAuthenticationOptions options) + { + if (app == null) + throw new ArgumentNullException(nameof(app)); + if (options == null) + throw new ArgumentNullException(nameof(options)); + + app.Use(typeof(ArcGISPortalAuthenticationMiddleware), app, options); + + return app; + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationHandler.cs b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationHandler.cs new file mode 100644 index 0000000..8a32cbe --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationHandler.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +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; + +namespace Owin.Security.Providers.ArcGISPortal +{ + public class ArcGISPortalAuthenticationHandler : AuthenticationHandler + { + private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; + + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + private readonly string _host; + + public ArcGISPortalAuthenticationHandler(HttpClient httpClient, ILogger logger, string host) + { + _httpClient = httpClient; + _logger = logger; + _host = host; + } + + 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) + }; + + // Request the token + var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint); + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + requestMessage.Content = new FormUrlEncodedContent(body); + var tokenResponse = await _httpClient.SendAsync(requestMessage); + tokenResponse.EnsureSuccessStatusCode(); + var text = await tokenResponse.Content.ReadAsStringAsync(); + + // Deserializes the token response + dynamic response = JsonConvert.DeserializeObject(text); + var accessToken = (string)response.access_token; + var refreshToken = (string)response.refresh_token; + + // Get the ArcGISPortal user + var userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint + "?f=json&token=" + Uri.EscapeDataString(accessToken)); + userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + var userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled); + userResponse.EnsureSuccessStatusCode(); + text = await userResponse.Content.ReadAsStringAsync(); + var user = JsonConvert.DeserializeObject(text); + + var context = new ArcGISPortalAuthenticatedContext(Context, user, accessToken, refreshToken, _host) + { + 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.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.Name)) + { + context.Identity.AddClaim(new Claim("urn:ArcGISPortal:name", context.Name, XmlSchemaString, Options.AuthenticationType)); + } + if (!string.IsNullOrEmpty(context.Link)) + { + context.Identity.AddClaim(new Claim("urn:ArcGISPortal:url", context.Link, 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; + } + + GenerateCorrelationId(properties); + var state = Options.StateDataFormat.Protect(properties); + // comma separated + var scope = string.Join(",", Options.Scope); + + var authorizationEndpoint = + Options.Endpoints.AuthorizationEndpoint + + "?client_id=" + Uri.EscapeDataString(Options.ClientId) + + "&response_type=" + Uri.EscapeDataString(scope) + + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + + "&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) 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 ArcGISPortalReturnEndpointContext(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.ArcGISPortal/ArcGISPortalAuthenticationMiddleware.cs b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationMiddleware.cs new file mode 100644 index 0000000..007df37 --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationMiddleware.cs @@ -0,0 +1,87 @@ +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.ArcGISPortal +{ + public class ArcGISPortalAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public ArcGISPortalAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, + ArcGISPortalAuthenticationOptions options) + : base(next, options) + { + if (string.IsNullOrWhiteSpace(Options.Host)) + throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, + Resources.Exception_OptionMustBeProvided, "Host")); + 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 ArcGISPortalAuthenticationProvider(); + + if (Options.StateDataFormat == null) + { + var dataProtector = app.CreateDataProtector( + typeof(ArcGISPortalAuthenticationMiddleware).FullName, + Options.AuthenticationType, "v2"); + 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.UserAgent.ParseAdd("Microsoft Owin ArcGISPortal middleware"); + _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 ArcGISPortalAuthenticationHandler(_httpClient, _logger, Options.Host); + } + + private static HttpMessageHandler ResolveHttpMessageHandler(ArcGISPortalAuthenticationOptions 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.ArcGISPortal/ArcGISPortalAuthenticationOptions.cs b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationOptions.cs new file mode 100644 index 0000000..e1a843c --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/ArcGISPortalAuthenticationOptions.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; + +namespace Owin.Security.Providers.ArcGISPortal +{ + public class ArcGISPortalAuthenticationOptions : AuthenticationOptions + { + public class ArcGISPortalAuthenticationEndpoints + { + /// + /// Endpoint which is used to redirect users to request ArcGISPortal access + /// + /// + /// Defaults to https://www.arcgis.com/sharing/rest/oauth2/authorize/ + /// + public string AuthorizationEndpoint { get; set; } + + /// + /// Endpoint which is used to exchange code for access token + /// + /// + /// Defaults to https://www.arcgis.com/sharing/rest/oauth2/token/ + /// + public string TokenEndpoint { get; set; } + + /// + /// Endpoint which is used to obtain user information after authentication + /// + /// + /// Defaults to https://www.arcgis.com/sharing/rest/community/self + /// + public string UserInfoEndpoint { get; set; } + } + + private const string AuthenticationTypeNameDefault = "ArcGIS Portal"; + + private const string AuthorizationEndPoint = "arcgis/sharing/rest/oauth2/authorize/"; + private const string TokenEndpoint = "arcgis/sharing/rest/oauth2/token/"; + private const string UserInfoEndpoint = "arcgis/sharing/rest/community/self"; + + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to ArcGISPortal. + /// + /// + /// 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 ArcGISPortal. + /// 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 ArcGISPortal. + /// + /// + /// 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-ArcGISPortal". + /// + 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 ArcGIS Portal Authentication Type Name + /// Displayed to the user as the login option, and allows multiple ArcGIS Portal OAuth providers to be configured for use in the same application. + /// + public string AuthenticationTypeName { get; set; } + + /// + /// Gets or sets the ArcGIS Portal Host (where the portal is installed e.g. https://arcgisportal.domain.com) + /// + public string Host { get; set; } + + /// + /// Gets or sets the ArcGISPortal supplied Client ID + /// + public string ClientId { get; set; } + + /// + /// Gets or sets the ArcGISPortal supplied Client Secret + /// + public string ClientSecret { get; set; } + + /// + /// Gets the sets of OAuth endpoints used to authenticate against ArcGISPortal. Overriding these endpoints allows you to use ArcGISPortal Enterprise for + /// authentication. + /// + public ArcGISPortalAuthenticationEndpoints Endpoints { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public IArcGISPortalAuthenticationProvider Provider { get; set; } + + /// + /// A list of permissions to request. + /// + public IList Scope { get; protected 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 ArcGISPortalAuthenticationOptions(string host, string clientId, string clientSecret) : this(AuthenticationTypeNameDefault, host, clientId, clientSecret) {} + + /// + /// Initializes a new + /// + public ArcGISPortalAuthenticationOptions(string authenticationTypeName, string host, string clientId, string clientSecret) : base(authenticationTypeName) + { + AuthenticationTypeName = authenticationTypeName; + Host = host; + ClientId = clientId; + ClientSecret = clientSecret; + + AuthenticationType = AuthenticationTypeName; + Caption = AuthenticationTypeName; + + CallbackPath = new PathString("/signin-arcgis-portal"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = new List + { + "code" + }; + BackchannelTimeout = TimeSpan.FromSeconds(60); + + Uri hostUri = new Uri(Host); + Endpoints = new ArcGISPortalAuthenticationEndpoints + { + AuthorizationEndpoint = new Uri(hostUri, AuthorizationEndPoint).ToString(), + TokenEndpoint = new Uri(hostUri, TokenEndpoint).ToString(), + UserInfoEndpoint = new Uri(hostUri, UserInfoEndpoint).ToString() + }; + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.ArcGISPortal/Owin.Security.Providers.ArcGISPortal.csproj b/src/Owin.Security.Providers.ArcGISPortal/Owin.Security.Providers.ArcGISPortal.csproj new file mode 100644 index 0000000..dd0e59f --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Owin.Security.Providers.ArcGISPortal.csproj @@ -0,0 +1,82 @@ + + + + + Debug + AnyCPU + {18547CA4-D7D3-43C2-81C2-A21FC8151A93} + Library + Properties + Owin.Security.Providers.ArcGISPortal + Owin.Security.Providers.ArcGISPortal + v4.5 + 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 + + + ..\..\packages\Microsoft.Owin.Security.3.0.1\lib\net45\Microsoft.Owin.Security.dll + + + ..\..\packages\Newtonsoft.Json.8.0.3\lib\net45\Newtonsoft.Json.dll + + + ..\..\packages\Owin.1.0\lib\net40\Owin.dll + + + + + + + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + ResXFileCodeGenerator + Resources.Designer.cs + + + + + + + \ No newline at end of file diff --git a/src/Owin.Security.Providers.ArcGISPortal/Properties/AssemblyInfo.cs b/src/Owin.Security.Providers.ArcGISPortal/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..f83e4fe --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Owin.Security.Providers.ArcGISPortal")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Owin.Security.Providers.ArcGISPortal")] +[assembly: AssemblyCopyright("Copyright © 2017")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("18547ca4-d7d3-43c2-81c2-a21fc8151a93")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalAuthenticatedContext.cs b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalAuthenticatedContext.cs new file mode 100644 index 0000000..749070b --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalAuthenticatedContext.cs @@ -0,0 +1,81 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System.Security.Claims; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; +using Owin.Security.Providers.ArcGISPortal.Provider; +using System; + +namespace Owin.Security.Providers.ArcGISPortal +{ + /// + /// Contains information about the login session as well as the user . + /// + public class ArcGISPortalAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The ArcGIS Portal user + /// ArcGIS Portal Access token + /// ArcGIS Portal Refresh token + /// ArcGIS Portal Host + public ArcGISPortalAuthenticatedContext(IOwinContext context, ArcGISPortalUser user, string accessToken, string refreshToken, string host) + : base(context) + { + Uri hostUri = new Uri(host); + + AccessToken = accessToken; + RefreshToken = refreshToken; + Id = user.Username; + Name = user.FullName; + Link = new Uri(hostUri, "arcgis/sharing/rest/community/users/" + Id).ToString(); + UserName = Id; + Email = user.Email; + } + + /// + /// Gets the ArcGIS Portal access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the ArcGIS Portal refresh token + /// + public string RefreshToken { get; private set; } + + /// + /// Gets the ArcGIS Portal user ID + /// + public string Id { get; } + + /// + /// Gets the user's name + /// + public string Name { get; private set; } + + /// + /// Gets the user's email + /// + public string Email { get; private set; } + + public string Link { get; private set; } + + /// + /// Gets the ArcGIS Portal username + /// + public string UserName { 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.ArcGISPortal/Provider/ArcGISPortalAuthenticationProvider.cs b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalAuthenticationProvider.cs new file mode 100644 index 0000000..8de3095 --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalAuthenticationProvider.cs @@ -0,0 +1,50 @@ +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.ArcGISPortal +{ + /// + /// Default implementation. + /// + public class ArcGISPortalAuthenticationProvider : IArcGISPortalAuthenticationProvider + { + /// + /// Initializes a + /// + public ArcGISPortalAuthenticationProvider() + { + 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 ArcGISPortal successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(ArcGISPortalAuthenticatedContext 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(ArcGISPortalReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalReturnEndpointContext.cs b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalReturnEndpointContext.cs new file mode 100644 index 0000000..82fb55d --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalReturnEndpointContext.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.ArcGISPortal +{ + /// + /// Provides context information to middleware providers. + /// + public class ArcGISPortalReturnEndpointContext : ReturnEndpointContext + { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public ArcGISPortalReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalUser.cs b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalUser.cs new file mode 100644 index 0000000..1131a9b --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Provider/ArcGISPortalUser.cs @@ -0,0 +1,9 @@ +namespace Owin.Security.Providers.ArcGISPortal.Provider +{ + public class ArcGISPortalUser + { + public string Username { get; set; } + public string FullName { get; set; } + public string Email { get; set; } + } +} diff --git a/src/Owin.Security.Providers.ArcGISPortal/Provider/IArcGISPortalAuthenticationProvider.cs b/src/Owin.Security.Providers.ArcGISPortal/Provider/IArcGISPortalAuthenticationProvider.cs new file mode 100644 index 0000000..e84ad31 --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/Provider/IArcGISPortalAuthenticationProvider.cs @@ -0,0 +1,24 @@ +using System.Threading.Tasks; + +namespace Owin.Security.Providers.ArcGISPortal +{ + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface IArcGISPortalAuthenticationProvider + { + /// + /// Invoked whenever ArcGISPortal successfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(ArcGISPortalAuthenticatedContext 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(ArcGISPortalReturnEndpointContext context); + } +} \ No newline at end of file diff --git a/src/Owin.Security.Providers.ArcGISPortal/Resources.Designer.cs b/src/Owin.Security.Providers.ArcGISPortal/Resources.Designer.cs new file mode 100644 index 0000000..21a66b4 --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/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.ArcGISPortal { + 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", "15.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)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Owin.Security.Providers.ArcGISPortal.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.ArcGISPortal/Resources.resx b/src/Owin.Security.Providers.ArcGISPortal/Resources.resx new file mode 100644 index 0000000..2a19bea --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/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.ArcGISPortal/packages.config b/src/Owin.Security.Providers.ArcGISPortal/packages.config new file mode 100644 index 0000000..cbfe6a2 --- /dev/null +++ b/src/Owin.Security.Providers.ArcGISPortal/packages.config @@ -0,0 +1,7 @@ + + + + + + + \ No newline at end of file