adding the onshape provider

This commit is contained in:
Tathagata Chakraborty
2015-09-14 15:43:24 +05:30
parent e35b98c8a4
commit c9f9d3f92f
11 changed files with 644 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
namespace Owin.Security.Providers.OnShape
{
internal static class Constants
{
public const string DefaultAuthenticationType = "OnShape";
}
}

View File

@@ -0,0 +1,29 @@
using System;
namespace Owin.Security.Providers.OnShape
{
public static class OnShapeAuthenticationExtensions
{
public static IAppBuilder UseOnShapeAuthentication(this IAppBuilder app,
OnShapeAuthenticationOptions options)
{
if (app == null)
throw new ArgumentNullException("app");
if (options == null)
throw new ArgumentNullException("options");
app.Use(typeof(OnShapeAuthenticationMiddleware), app, options);
return app;
}
public static IAppBuilder UseOnShapeAuthentication(this IAppBuilder app, string appKey, string appSecret)
{
return app.UseOnShapeAuthentication(new OnShapeAuthenticationOptions
{
AppKey = appKey,
AppSecret = appSecret
});
}
}
}

View File

@@ -0,0 +1,247 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
namespace Owin.Security.Providers.OnShape
{
public class OnShapeAuthenticationHandler : AuthenticationHandler<OnShapeAuthenticationOptions>
{
private const string StateCookie = "_OnShapeState";
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string TokenEndpoint = "https://partner.dev.onshape.com/oauth/token";
private const string UserInfoEndpoint = "https://partner.dev.onshape.com/api/users/current";
private readonly ILogger logger;
private readonly HttpClient httpClient;
public OnShapeAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
this.httpClient = httpClient;
this.logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("code");
if (values != null && values.Count == 1)
{
code = values[0];
}
state = Request.Cookies[StateCookie];
properties = Options.StateDataFormat.Unprotect(state);
if (properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, logger))
{
return new AuthenticationTicket(null, properties);
}
// Check for error
if (Request.Query.Get("error") != null)
return new AuthenticationTicket(null, properties);
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
// Build up the body for the token request
var body = new List<KeyValuePair<string, string>>();
body.Add(new KeyValuePair<string, string>("grant_type", "authorization_code"));
body.Add(new KeyValuePair<string, string>("code", code));
body.Add(new KeyValuePair<string, string>("redirect_uri", redirectUri));
body.Add(new KeyValuePair<string, string>("client_id", Options.AppKey));
body.Add(new KeyValuePair<string, string>("client_secret", Options.AppSecret));
// Request the token
//HttpResponseMessage tokenResponse =
// await httpClient.PostAsync(TokenEndpoint, new FormUrlEncodedContent(body));
// Get token
var tokenRequest = new HttpRequestMessage(HttpMethod.Post, TokenEndpoint);
tokenRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
tokenRequest.Content = new FormUrlEncodedContent(body);
HttpResponseMessage tokenResponse = await httpClient.SendAsync(tokenRequest, Request.CallCancelled);
tokenResponse.EnsureSuccessStatusCode();
string text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
string accessToken = (string)response.access_token;
// Get the OnShape user
//HttpResponseMessage graphResponse = await httpClient.GetAsync(
// UserInfoEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);
string tokenType = (string)response.token_type;
var userRequest = new HttpRequestMessage(HttpMethod.Get, UserInfoEndpoint);
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//userRequest.Headers.Authorization = new AuthenticationHeaderValue(tokenType, Uri.EscapeDataString(accessToken));
userRequest.Headers.Authorization = new AuthenticationHeaderValue(tokenType, accessToken);
HttpResponseMessage graphResponse = await httpClient.SendAsync(userRequest, Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
var context = new OnShapeAuthenticatedContext(Context, user, accessToken);
context.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.Name))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, 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<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if (string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
string authorizationEndpoint =
"https://partner.dev.onshape.com/oauth/authorize" +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.AppKey) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri);
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsSecure
};
Response.StatusCode = 302;
Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(properties), cookieOptions);
Response.Headers.Set("Location", authorizationEndpoint);
}
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
// TODO: error responses
AuthenticationTicket ticket = await AuthenticateAsync();
if (ticket == null)
{
logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new OnShapeReturnEndpointContext(Context, ticket);
context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType;
context.RedirectUri = ticket.Properties.RedirectUri;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
ClaimsIdentity grantIdentity = context.Identity;
if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
string redirectUri = context.RedirectUri;
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
return false;
}
}
}

View File

@@ -0,0 +1,82 @@
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.OnShape
{
public class OnShapeAuthenticationMiddleware : AuthenticationMiddleware<OnShapeAuthenticationOptions>
{
private readonly HttpClient httpClient;
private readonly ILogger logger;
public OnShapeAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
OnShapeAuthenticationOptions options)
: base(next, options)
{
if (String.IsNullOrWhiteSpace(Options.AppKey))
throw new ArgumentException("AppKey must be provided");
if (String.IsNullOrWhiteSpace(Options.AppSecret))
throw new ArgumentException("AppSecret must be provided");
logger = app.CreateLogger<OnShapeAuthenticationMiddleware>();
if (Options.Provider == null)
Options.Provider = new OnShapeAuthenticationProvider();
if (Options.StateDataFormat == null)
{
IDataProtector dataProtector = app.CreateDataProtector(
typeof (OnShapeAuthenticationMiddleware).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
};
}
/// <summary>
/// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing
/// authentication-related requests.
/// </summary>
/// <returns>
/// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the
/// <see cref="T:Owin.Security.Providers.OnShape.OnShapeAuthenticationOptions" /> supplied to the constructor.
/// </returns>
protected override AuthenticationHandler<OnShapeAuthenticationOptions> CreateHandler()
{
return new OnShapeAuthenticationHandler(httpClient, logger);
}
private HttpMessageHandler ResolveHttpMessageHandler(OnShapeAuthenticationOptions options)
{
HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler();
// If they provided a validator, apply it or fail.
if (options.BackchannelCertificateValidator != null)
{
// Set the cert validate callback
var webRequestHandler = handler as WebRequestHandler;
if (webRequestHandler == null)
{
throw new InvalidOperationException("Validator Handler Mismatch");
}
webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
}
return handler;
}
}
}

View File

@@ -0,0 +1,92 @@
using System;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.OnShape
{
public class OnShapeAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to OnShape
/// </summary>
/// <value>
/// The pinned certificate validator.
/// </value>
/// <remarks>
/// 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.
/// </remarks>
public ICertificateValidator BackchannelCertificateValidator { get; set; }
/// <summary>
/// The HttpMessageHandler used to communicate with OnShape.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with OnShape.
/// </summary>
/// <value>
/// The back channel timeout in milliseconds.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// 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-OnShape".
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string Caption
{
get { return Description.Caption; }
set { Description.Caption = value; }
}
/// <summary>
/// Gets or sets the OnShape supplied Application Key
/// </summary>
public string AppKey { get; set; }
/// <summary>
/// Gets or sets the OnShape supplied Application Secret
/// </summary>
public string AppSecret { get; set; }
/// <summary>
/// Gets or sets the <see cref="IOnShapeAuthenticationProvider" /> used in the authentication events
/// </summary>
public IOnShapeAuthenticationProvider Provider { get; set; }
/// <summary>
/// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user
/// <see cref="System.Security.Claims.ClaimsIdentity" />.
/// </summary>
public string SignInAsAuthenticationType { get; set; }
/// <summary>
/// Gets or sets the type used to secure data handled by the middleware.
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
/// <summary>
/// Initializes a new <see cref="OnShapeAuthenticationOptions" />
/// </summary>
public OnShapeAuthenticationOptions()
: base("OnShape")
{
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/oauthRedirect");
AuthenticationMode = AuthenticationMode.Passive;
BackchannelTimeout = TimeSpan.FromSeconds(60);
}
}
}

View File

@@ -0,0 +1,24 @@
using System.Threading.Tasks;
namespace Owin.Security.Providers.OnShape
{
/// <summary>
/// Specifies callback methods which the <see cref="OnShapeAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IOnShapeAuthenticationProvider
{
/// <summary>
/// Invoked whenever OnShape successfully authenticates a user
/// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task Authenticated(OnShapeAuthenticatedContext context);
/// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary>
/// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
Task ReturnEndpoint(OnShapeReturnEndpointContext context);
}
}

View File

@@ -0,0 +1,73 @@
// 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.OnShape
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class OnShapeAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="OnShapeAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="user">The JSON-serialized user</param>
/// <param name="accessToken">OnShape Access token</param>
public OnShapeAuthenticatedContext(IOwinContext context, JObject user, string accessToken)
: base(context)
{
AccessToken = accessToken;
User = user;
Id = TryGetValue(user, "id");
Name = TryGetValue(user, "name");
}
/// <summary>
/// Gets the JSON-serialized user
/// </summary>
/// <remarks>
/// Contains the OnShape user obtained from the endpoint https://api.OnShape.com/1/account/info
/// </remarks>
public JObject User { get; private set; }
/// <summary>
/// Gets the OnShape OAuth access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the OnShape user ID
/// </summary>
public string Id { get; private set; }
/// <summary>
/// The name of the user
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the <see cref="ClaimsIdentity"/> representing the user
/// </summary>
public ClaimsIdentity Identity { get; set; }
/// <summary>
/// Gets or sets a property bag for common authentication properties
/// </summary>
public AuthenticationProperties Properties { get; set; }
private static string TryGetValue(JObject user, string propertyName)
{
JToken value;
return user.TryGetValue(propertyName, out value) ? value.ToString() : null;
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Threading.Tasks;
namespace Owin.Security.Providers.OnShape
{
/// <summary>
/// Default <see cref="IOnShapeAuthenticationProvider"/> implementation.
/// </summary>
public class OnShapeAuthenticationProvider : IOnShapeAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="OnShapeAuthenticationProvider"/>
/// </summary>
public OnShapeAuthenticationProvider()
{
OnAuthenticated = context => Task.FromResult<object>(null);
OnReturnEndpoint = context => Task.FromResult<object>(null);
}
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<OnShapeAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<OnShapeReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever OnShape successfully authenticates a user
/// </summary>
/// <param name="context">Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.</param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task Authenticated(OnShapeAuthenticatedContext context)
{
return OnAuthenticated(context);
}
/// <summary>
/// Invoked prior to the <see cref="System.Security.Claims.ClaimsIdentity"/> being saved in a local cookie and the browser being redirected to the originally requested URL.
/// </summary>
/// <param name="context"></param>
/// <returns>A <see cref="Task"/> representing the completed operation.</returns>
public virtual Task ReturnEndpoint(OnShapeReturnEndpointContext context)
{
return OnReturnEndpoint(context);
}
}
}

View File

@@ -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.OnShape
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class OnShapeReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
///
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public OnShapeReturnEndpointContext(
IOwinContext context,
AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@@ -223,6 +223,15 @@
<Compile Include="LinkedIn\Provider\LinkedInAuthenticationProvider.cs" /> <Compile Include="LinkedIn\Provider\LinkedInAuthenticationProvider.cs" />
<Compile Include="LinkedIn\Provider\LinkedInReturnEndpointContext.cs" /> <Compile Include="LinkedIn\Provider\LinkedInReturnEndpointContext.cs" />
<Compile Include="LinkedIn\Provider\ILinkedInAuthenticationProvider.cs" /> <Compile Include="LinkedIn\Provider\ILinkedInAuthenticationProvider.cs" />
<Compile Include="OnShape\Constants.cs" />
<Compile Include="OnShape\OnShapeAuthenticationExtensions.cs" />
<Compile Include="OnShape\OnShapeAuthenticationHandler.cs" />
<Compile Include="OnShape\OnShapeAuthenticationMiddleware.cs" />
<Compile Include="OnShape\OnShapeAuthenticationOptions.cs" />
<Compile Include="OnShape\Provider\IOnShapeAuthenticationProvider.cs" />
<Compile Include="OnShape\Provider\OnShapeAuthenticatedContext.cs" />
<Compile Include="OnShape\Provider\OnShapeAuthenticationProvider.cs" />
<Compile Include="OnShape\Provider\OnShapeReturnEndpointContext.cs" />
<Compile Include="OpenID\Constants.cs" /> <Compile Include="OpenID\Constants.cs" />
<Compile Include="OpenID\Extensions\OpenIDSimpleRegistrationAuthenticationContextExtensions.cs" /> <Compile Include="OpenID\Extensions\OpenIDSimpleRegistrationAuthenticationContextExtensions.cs" />
<Compile Include="OpenID\Extensions\OpenIDSimpleRegistrationExtension.cs" /> <Compile Include="OpenID\Extensions\OpenIDSimpleRegistrationExtension.cs" />

View File

@@ -40,6 +40,7 @@ using Owin.Security.Providers.Yahoo;
using Owin.Security.Providers.Backlog; using Owin.Security.Providers.Backlog;
using Owin.Security.Providers.Vimeo; using Owin.Security.Providers.Vimeo;
using Owin.Security.Providers.Fitbit; using Owin.Security.Providers.Fitbit;
using Owin.Security.Providers.OnShape;
namespace OwinOAuthProvidersDemo namespace OwinOAuthProvidersDemo
{ {
@@ -294,6 +295,10 @@ namespace OwinOAuthProvidersDemo
// ClientId = "", // ClientId = "",
// ClientSecret = "" // ClientSecret = ""
//}); //});
//app.UseOnShapeAuthentication(
// appKey: "",
// appSecret: "");
} }
} }
} }