Add new provider : Xing

Add Xing provider to authenticate with german professional social
network account
This commit is contained in:
Yoann Blossier
2016-01-06 16:19:36 +01:00
parent 344336b536
commit 92e67e5eef
19 changed files with 993 additions and 1 deletions

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" /> <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup> <PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
@@ -11,6 +12,7 @@
<AssemblyName>Owin.Security.Providers</AssemblyName> <AssemblyName>Owin.Security.Providers</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp>05a3d3f8</NuGetPackageImportStamp>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols> <DebugSymbols>true</DebugSymbols>
@@ -415,6 +417,20 @@
<Compile Include="WordPress\Provider\WordPressAuthenticationProvider.cs" /> <Compile Include="WordPress\Provider\WordPressAuthenticationProvider.cs" />
<Compile Include="WordPress\Provider\WordPressReturnEndpointContext.cs" /> <Compile Include="WordPress\Provider\WordPressReturnEndpointContext.cs" />
<Compile Include="WordPress\Provider\IWordPressAuthenticationProvider.cs" /> <Compile Include="WordPress\Provider\IWordPressAuthenticationProvider.cs" />
<Compile Include="Xing\Constants.cs" />
<Compile Include="Xing\Messages\AccessToken.cs" />
<Compile Include="Xing\Messages\RequestToken.cs" />
<Compile Include="Xing\Messages\RequestTokenSerializer.cs" />
<Compile Include="Xing\Messages\Serializer.cs" />
<Compile Include="Xing\Provider\IXingAuthenticationProvider.cs" />
<Compile Include="Xing\Provider\XingApplyRedirectContext.cs" />
<Compile Include="Xing\Provider\XingAuthenticatedContext.cs" />
<Compile Include="Xing\Provider\XingAuthenticationProvider.cs" />
<Compile Include="Xing\Provider\XingReturnEndpointContext.cs" />
<Compile Include="Xing\XingAuthenticationExtensions.cs" />
<Compile Include="Xing\XingAuthenticationHandler.cs" />
<Compile Include="Xing\XingAuthenticationMiddleware.cs" />
<Compile Include="Xing\XingAuthenticationOptions.cs" />
<Compile Include="Yahoo\Constants.cs" /> <Compile Include="Yahoo\Constants.cs" />
<Compile Include="Yahoo\Messages\AccessToken.cs" /> <Compile Include="Yahoo\Messages\AccessToken.cs" />
<Compile Include="Yahoo\Messages\RequestToken.cs" /> <Compile Include="Yahoo\Messages\RequestToken.cs" />
@@ -448,8 +464,16 @@
<None Include="app.config" /> <None Include="app.config" />
<None Include="packages.config" /> <None Include="packages.config" />
</ItemGroup> </ItemGroup>
<ItemGroup /> <ItemGroup>
<Folder Include="DoYouBuzz\" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />
</Target>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it. <!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild"> <Target Name="BeforeBuild">

View File

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

View File

@@ -0,0 +1,13 @@
namespace Owin.Security.Providers.Xing.Messages
{
/// <summary>
/// Xing access token
/// </summary>
public class AccessToken : RequestToken
{
/// <summary>
/// Gets or sets the Xing User ID
/// </summary>
public string UserId { get; set; }
}
}

View File

@@ -0,0 +1,30 @@
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.Xing.Messages
{
/// <summary>
/// Xing request token
/// </summary>
public class RequestToken
{
/// <summary>
/// Gets or sets the Xing token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Gets or sets the Xing token secret
/// </summary>
public string TokenSecret { get; set; }
/// <summary>
/// Indicates that callback is confirmed or not
/// </summary>
public bool CallbackConfirmed { get; set; }
/// <summary>
/// Gets or sets a property bag for common authentication properties
/// </summary>
public AuthenticationProperties Properties { get; set; }
}
}

View File

@@ -0,0 +1,101 @@
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler.Serializer;
using System;
using System.IO;
namespace Owin.Security.Providers.Xing.Messages
{
/// <summary>
/// Serializes and deserializes Xing request and access tokens so that they can be used by other application components.
/// </summary>
public class RequestTokenSerializer : IDataSerializer<RequestToken>
{
private const int FormatVersion = 1;
/// <summary>
/// Serialize a request token
/// </summary>
/// <param name="model">The token to serialize</param>
/// <returns>A byte array containing the serialized token</returns>
public virtual byte[] Serialize(RequestToken model)
{
using (var memory = new MemoryStream())
{
using (var writer = new BinaryWriter(memory))
{
Write(writer, model);
writer.Flush();
return memory.ToArray();
}
}
}
/// <summary>
/// Deserializes a request token
/// </summary>
/// <param name="data">A byte array containing the serialized token</param>
/// <returns>The Xing request token</returns>
public virtual RequestToken Deserialize(byte[] data)
{
using (var memory = new MemoryStream(data))
{
using (var reader = new BinaryReader(memory))
{
return Read(reader);
}
}
}
/// <summary>
/// Writes a Xing request token as a series of bytes. Used by the <see cref="Serialize"/> method.
/// </summary>
/// <param name="writer">The writer to use in writing the token</param>
/// <param name="token">The token to write</param>
public static void Write(BinaryWriter writer, RequestToken token)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
if (token == null)
{
throw new ArgumentNullException("token");
}
writer.Write(FormatVersion);
writer.Write(token.Token);
writer.Write(token.TokenSecret);
writer.Write(token.CallbackConfirmed);
PropertiesSerializer.Write(writer, token.Properties);
}
/// <summary>
/// Reads a Xing request token from a series of bytes. Used by the <see cref="Deserialize"/> method.
/// </summary>
/// <param name="reader">The reader to use in reading the token bytes</param>
/// <returns>The token</returns>
public static RequestToken Read(BinaryReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
if (reader.ReadInt32() != FormatVersion)
{
return null;
}
string token = reader.ReadString();
string tokenSecret = reader.ReadString();
bool callbackConfirmed = reader.ReadBoolean();
AuthenticationProperties properties = PropertiesSerializer.Read(reader);
if (properties == null)
{
return null;
}
return new RequestToken { Token = token, TokenSecret = tokenSecret, CallbackConfirmed = callbackConfirmed, Properties = properties };
}
}
}

View File

@@ -0,0 +1,20 @@
using Microsoft.Owin.Security.DataHandler.Serializer;
namespace Owin.Security.Providers.Xing.Messages
{
/// <summary>
/// Provides access to a request token serializer
/// </summary>
public static class Serializers
{
static Serializers()
{
RequestToken = new RequestTokenSerializer();
}
/// <summary>
/// Gets or sets a statically-available serializer object. The value for this property will be <see cref="RequestTokenSerializer"/> by default.
/// </summary>
public static IDataSerializer<RequestToken> RequestToken { get; set; }
}
}

View File

@@ -0,0 +1,31 @@
using System.Threading.Tasks;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.Xing.Provider
{
/// <summary>
/// Specifies callback methods which the <see cref="XingAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IXingAuthenticationProvider
{
/// <summary>
/// Invoked whenever Xing 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(XingAuthenticatedContext 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(XingReturnEndpointContext context);
/// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the Xing middleware
/// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
void ApplyRedirect(XingApplyRedirectContext context);
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.Xing.Provider
{
/// <summary>
/// Context passed when a Challenge causes a redirect to authorize endpoint in the Xing middleware
/// </summary>
public class XingApplyRedirectContext : BaseContext<XingAuthenticationOptions>
{
/// <summary>
/// Creates a new context object.
/// </summary>
/// <param name="context">The OWIN request context</param>
/// <param name="options">The Xing middleware options</param>
/// <param name="properties">The authentication properties of the challenge</param>
/// <param name="redirectUri">The initial redirect URI</param>
public XingApplyRedirectContext(IOwinContext context, XingAuthenticationOptions options, AuthenticationProperties properties, string redirectUri)
: base(context, options)
{
RedirectUri = redirectUri;
Properties = properties;
}
/// <summary>
/// Gets the URI used for the redirect operation.
/// </summary>
public string RedirectUri { get; private set; }
/// <summary>
/// Gets the authentication properties of the challenge
/// </summary>
public AuthenticationProperties Properties { get; private set; }
}
}

View File

@@ -0,0 +1,53 @@
using System.Security.Claims;
using Microsoft.Owin.Security.Provider;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.Xing.Provider
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class XingAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="XingAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="userId">Xing user ID</param>
/// <param name="accessToken">Xing access token</param>
/// <param name="accessTokenSecret">Xing access token secret</param>
public XingAuthenticatedContext(IOwinContext context, string userId, string accessToken, string accessTokenSecret)
: base(context)
{
UserId = userId;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSecret;
}
/// <summary>
/// Gets the Xing user ID
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Gets the Xing access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the Xing access token secret
/// </summary>
public string AccessTokenSecret { 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; }
}
}

View File

@@ -0,0 +1,67 @@
using System;
using System.Threading.Tasks;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.Xing.Provider
{
/// <summary>
/// Default <see cref="IXingAuthenticationProvider"/> implementation.
/// </summary>
public class XingAuthenticationProvider : IXingAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="XingAuthenticationProvider"/>
/// </summary>
public XingAuthenticationProvider()
{
OnAuthenticated = context => Task.FromResult<object>(null);
OnReturnEndpoint = context => Task.FromResult<object>(null);
OnApplyRedirect = context =>
context.Response.Redirect(context.RedirectUri);
}
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<XingAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<XingReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked.
/// </summary>
public Action<XingApplyRedirectContext> OnApplyRedirect { get; set; }
/// <summary>
/// Invoked whenever Xing 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(XingAuthenticatedContext 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(XingReturnEndpointContext context)
{
return OnReturnEndpoint(context);
}
/// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the Xing middleware
/// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
public virtual void ApplyRedirect(XingApplyRedirectContext context)
{
OnApplyRedirect(context);
}
}
}

View File

@@ -0,0 +1,22 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.Xing.Provider
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class XingReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
/// Initializes a new <see cref="XingReturnEndpointContext"/>.
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public XingReturnEndpointContext(IOwinContext context, AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace Owin.Security.Providers.Xing
{
public static class XingAuthenticationExtensions
{
public static IAppBuilder UseXingAuthentication(this IAppBuilder app, XingAuthenticationOptions options)
{
if (app == null)
throw new ArgumentNullException(nameof(app));
if (options == null)
throw new ArgumentNullException(nameof(options));
app.Use(typeof(XingAuthenticationMiddleware), app, options);
return app;
}
public static IAppBuilder UseXingAuthentication(this IAppBuilder app, string consumerKey, string consumerSecret)
{
return app.UseXingAuthentication(new XingAuthenticationOptions
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret
});
}
}
}

View File

@@ -0,0 +1,355 @@
using Microsoft.Owin;
using Microsoft.Owin.Helpers;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.Xing.Messages;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Owin.Security.Providers.Xing.Provider;
namespace Owin.Security.Providers.Xing
{
internal class XingAuthenticationHandler : AuthenticationHandler<XingAuthenticationOptions>
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const string StateCookie = "__XingState";
private const string RequestTokenEndpoint = "https://api.xing.com/v1/request_token";
private const string AuthenticationEndpoint = "https://api.xing.com/v1/authorize?oauth_token=";
private const string AccessTokenEndpoint = "https://api.xing.com/v1/access_token";
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
public XingAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
}
public override async Task<bool> InvokeAsync()
{
if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
return await InvokeReturnPathAsync();
}
return false;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
try
{
var query = Request.Query;
var protectedRequestToken = Request.Cookies[StateCookie];
var requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken);
if (requestToken == null)
{
_logger.WriteWarning("Invalid state");
return null;
}
properties = requestToken.Properties;
var returnedToken = query.Get("oauth_token");
if (string.IsNullOrWhiteSpace(returnedToken))
{
_logger.WriteWarning("Missing oauth_token");
return new AuthenticationTicket(null, properties);
}
if (returnedToken != requestToken.Token)
{
_logger.WriteWarning("Unmatched token");
return new AuthenticationTicket(null, properties);
}
var oauthVerifier = query.Get("oauth_verifier");
if (string.IsNullOrWhiteSpace(oauthVerifier))
{
_logger.WriteWarning("Missing or blank oauth_verifier");
return new AuthenticationTicket(null, properties);
}
var accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier);
var context = new XingAuthenticatedContext(Context, accessToken.UserId, accessToken.Token, accessToken.TokenSecret);
context.Identity = new ClaimsIdentity(
new[]
{
new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
new Claim("urn:xing:userid", accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
},
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
context.Properties = requestToken.Properties;
Response.Cookies.Delete(StateCookie);
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
_logger.WriteError("Authentication failed", ex);
return new AuthenticationTicket(null, properties);
}
}
protected override async Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return;
}
var challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if (challenge != null)
{
var requestPrefix = Request.Scheme + "://" + Request.Host;
var callBackUrl = requestPrefix + RequestPathBase + Options.CallbackPath;
var extra = challenge.Properties;
if (string.IsNullOrEmpty(extra.RedirectUri))
{
extra.RedirectUri = requestPrefix + Request.PathBase + Request.Path + Request.QueryString;
}
var requestToken = await ObtainRequestTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, callBackUrl, extra);
if (requestToken.CallbackConfirmed)
{
var xingAuthenticationEndpoint = AuthenticationEndpoint + requestToken.Token;
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsSecure
};
Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions);
var redirectContext = new XingApplyRedirectContext(
Context, Options,
extra, xingAuthenticationEndpoint);
Options.Provider.ApplyRedirect(redirectContext);
}
else
{
_logger.WriteError("requestToken CallbackConfirmed!=true");
}
}
}
public async Task<bool> InvokeReturnPathAsync()
{
var model = await AuthenticateAsync();
if (model == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new XingReturnEndpointContext(Context, model)
{
SignInAsAuthenticationType = Options.SignInAsAuthenticationType,
RedirectUri = model.Properties.RedirectUri
};
model.Properties.RedirectUri = null;
await Options.Provider.ReturnEndpoint(context);
if (context.SignInAsAuthenticationType != null && context.Identity != null)
{
var signInIdentity = context.Identity;
if (!string.Equals(signInIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
signInIdentity = new ClaimsIdentity(signInIdentity.Claims, context.SignInAsAuthenticationType, signInIdentity.NameClaimType, signInIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, signInIdentity);
}
if (!context.IsRequestCompleted && context.RedirectUri != null)
{
if (context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
context.RedirectUri = WebUtilities.AddQueryString(context.RedirectUri, "error", "access_denied");
}
Response.Redirect(context.RedirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
private async Task<RequestToken> ObtainRequestTokenAsync(string consumerKey, string consumerSecret, string callBackUri, AuthenticationProperties properties)
{
_logger.WriteVerbose("ObtainRequestToken");
var nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_callback", callBackUri },
{ "oauth_consumer_key", consumerKey },
{ "oauth_nonce", nonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_timestamp", GenerateTimeStamp() },
{ "oauth_version", "1.0" }
};
var canonicalizedRequestBuilder = new StringBuilder();
canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(RequestTokenEndpoint));
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(GetParameters(authorizationParts)));
var signature = ComputeSignature(consumerSecret, null, canonicalizedRequestBuilder.ToString());
authorizationParts.Add("oauth_signature", signature);
var authorizationHeaderBuilder = new StringBuilder();
authorizationHeaderBuilder.Append("OAuth ");
foreach (var authorizationPart in authorizationParts)
{
authorizationHeaderBuilder.AppendFormat("{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
}
authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;
var request = new HttpRequestMessage(HttpMethod.Post, RequestTokenEndpoint);
request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());
var response = await _httpClient.SendAsync(request, Request.CallCancelled);
response.EnsureSuccessStatusCode();
var responseText = await response.Content.ReadAsStringAsync();
var responseParameters = WebHelpers.ParseForm(responseText);
if (string.Equals(responseParameters["oauth_callback_confirmed"], "true", StringComparison.InvariantCulture))
{
return new RequestToken { Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), CallbackConfirmed = true, Properties = properties };
}
return new RequestToken();
}
private async Task<AccessToken> ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier)
{
//https://dev.xing.com/docs/authentication
_logger.WriteVerbose("ObtainAccessToken");
var nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_consumer_key", consumerKey },
{ "oauth_nonce", nonce },
{ "oauth_signature_method", "HMAC-SHA1" },
{ "oauth_token", token.Token },
{ "oauth_timestamp", GenerateTimeStamp() },
{ "oauth_verifier", verifier },
{ "oauth_version", "1.0" },
};
var parameterBuilder = new StringBuilder();
foreach (var authorizationKey in authorizationParts)
{
parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(authorizationKey.Key), Uri.EscapeDataString(authorizationKey.Value));
}
parameterBuilder.Length--;
var parameterString = parameterBuilder.ToString();
var canonicalizedRequestBuilder = new StringBuilder();
canonicalizedRequestBuilder.Append(HttpMethod.Post.Method);
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(AccessTokenEndpoint));
canonicalizedRequestBuilder.Append("&");
canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString));
var signature = ComputeSignature(consumerSecret, token.TokenSecret, canonicalizedRequestBuilder.ToString());
authorizationParts.Add("oauth_signature", signature);
authorizationParts.Remove("oauth_verifier");
var authorizationHeaderBuilder = new StringBuilder();
authorizationHeaderBuilder.Append("OAuth ");
foreach (var authorizationPart in authorizationParts)
{
authorizationHeaderBuilder.AppendFormat(
"{0}=\"{1}\", ", authorizationPart.Key, Uri.EscapeDataString(authorizationPart.Value));
}
authorizationHeaderBuilder.Length = authorizationHeaderBuilder.Length - 2;
var request = new HttpRequestMessage(HttpMethod.Post, AccessTokenEndpoint);
request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());
var formPairs = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("oauth_verifier", verifier)
};
request.Content = new FormUrlEncodedContent(formPairs);
var response = await _httpClient.SendAsync(request, Request.CallCancelled);
if (!response.IsSuccessStatusCode)
{
_logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode);
response.EnsureSuccessStatusCode(); // throw
}
var responseText = await response.Content.ReadAsStringAsync();
var responseParameters = WebHelpers.ParseForm(responseText);
return new AccessToken
{
Token = Uri.UnescapeDataString(responseParameters["oauth_token"]),
TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]),
UserId = Uri.UnescapeDataString(responseParameters["user_id"]),
};
}
private static string GetParameters(SortedDictionary<string, string> parameters)
{
var parameterBuilder = new StringBuilder();
foreach (var param in parameters)
{
parameterBuilder.AppendFormat("{0}={1}&", Uri.EscapeDataString(param.Key), Uri.EscapeDataString(param.Value));
}
parameterBuilder.Length--;
return parameterBuilder.ToString();
}
private static string GenerateTimeStamp()
{
var secondsSinceUnixEpocStart = DateTime.UtcNow - Epoch;
return Convert.ToInt64(secondsSinceUnixEpocStart.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
private static string ComputeSignature(string consumerSecret, string tokenSecret, string signatureData)
{
using (var algorithm = new HMACSHA1())
{
algorithm.Key = Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}&{1}", Uri.EscapeDataString(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? string.Empty : Uri.EscapeDataString(tokenSecret)));
var hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(signatureData));
return Convert.ToBase64String(hash);
}
}
}
}

View File

@@ -0,0 +1,105 @@
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataHandler.Encoder;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.Xing.Messages;
using System;
using System.Globalization;
using System.Net.Http;
using Owin.Security.Providers.Properties;
using Owin.Security.Providers.Xing.Provider;
namespace Owin.Security.Providers.Xing
{
/// <summary>
/// OWIN middleware for authenticating users using Xing
/// </summary>
public class XingAuthenticationMiddleware : AuthenticationMiddleware<XingAuthenticationOptions>
{
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
/// <summary>
/// Initializes a <see cref="XingAuthenticationMiddleware"/>
/// </summary>
/// <param name="next">The next middleware in the OWIN pipeline to invoke</param>
/// <param name="app">The OWIN application</param>
/// <param name="options">Configuration options for the middleware</param>
public XingAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, XingAuthenticationOptions options)
: base(next, options)
{
_logger = app.CreateLogger<XingAuthenticationMiddleware>();
if (string.IsNullOrWhiteSpace(Options.ConsumerSecret))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ConsumerSecret"));
}
if (string.IsNullOrWhiteSpace(Options.ConsumerKey))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ConsumerKey"));
}
SetDefaults(app);
_httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
{
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024*1024*10
};
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("*/*");
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin Xing middleware");
_httpClient.DefaultRequestHeaders.ExpectContinue = false;
}
/// <summary>
/// Provides the <see cref="AuthenticationHandler"/> object for processing authentication-related requests.
/// </summary>
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="XingAuthenticationOptions"/> supplied to the constructor.</returns>
protected override AuthenticationHandler<XingAuthenticationOptions> CreateHandler()
{
return new XingAuthenticationHandler(_httpClient, _logger);
}
private static HttpMessageHandler ResolveHttpMessageHandler(XingAuthenticationOptions options)
{
var handler = options.BackchannelHttpHandler ?? new WebRequestHandler();
// Set the cert validate callback
var webRequestHandler = handler as WebRequestHandler;
if (webRequestHandler == null)
{
if (options.BackchannelCertificateValidator != null)
{
throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch);
}
}
else if (options.BackchannelCertificateValidator != null)
{
webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
}
return handler;
}
private void SetDefaults(IAppBuilder app)
{
if (Options.Provider == null)
{
Options.Provider = new XingAuthenticationProvider();
}
if (Options.StateDataFormat == null)
{
var dataProtector = app.CreateDataProtector(typeof(XingAuthenticationMiddleware).FullName, Options.AuthenticationType, "v1");
Options.StateDataFormat = new SecureDataFormat<RequestToken>(Serializers.RequestToken, dataProtector, TextEncodings.Base64Url);
}
if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType))
{
Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
}
}
}
}

View File

@@ -0,0 +1,96 @@
using System;
using System.Net.Http;
using Owin.Security.Providers.Xing.Messages;
using Microsoft.Owin.Security;
using Microsoft.Owin;
using Owin.Security.Providers.Xing.Provider;
namespace Owin.Security.Providers.Xing
{
/// <summary>
/// Options for the Xing authentication middleware.
/// </summary>
public class XingAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="XingAuthenticationOptions"/> class.
/// </summary>
public XingAuthenticationOptions()
: base(Constants.DefaultAuthenticationType)
{
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-xing");
AuthenticationMode = AuthenticationMode.Passive;
BackchannelTimeout = TimeSpan.FromSeconds(60);
}
/// <summary>
/// Gets or sets the consumer key used to communicate with Xing.
/// </summary>
/// <value>The consumer key used to communicate with Xing.</value>
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the consumer secret used to sign requests to Xing.
/// </summary>
/// <value>The consumer secret used to sign requests to Xing.</value>
public string ConsumerSecret { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with Xing.
/// </summary>
/// <value>
/// The back channel timeout.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to Xing.
/// </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 Xing.
/// 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>
/// 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>
/// 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-Xing".
/// </summary>
public PathString CallbackPath { 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<RequestToken> StateDataFormat { get; set; }
/// <summary>
/// Gets or sets the <see cref="IXingAuthenticationProvider"/> used to handle authentication events.
/// </summary>
public IXingAuthenticationProvider Provider { get; set; }
}
}

View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<packages> <packages>
<package id="Microsoft.Net.Compilers" version="1.1.1" targetFramework="net45" developmentDependency="true" />
<package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" /> <package id="Microsoft.Owin" version="2.1.0" targetFramework="net45" />
<package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" /> <package id="Microsoft.Owin.Security" version="2.1.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" /> <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />

View File

@@ -42,6 +42,7 @@ using Owin.Security.Providers.Vimeo;
using Owin.Security.Providers.Fitbit; using Owin.Security.Providers.Fitbit;
using Owin.Security.Providers.Onshape; using Owin.Security.Providers.Onshape;
using Owin.Security.Providers.VKontakte; using Owin.Security.Providers.VKontakte;
using Owin.Security.Providers.Xing;
namespace OwinOAuthProvidersDemo namespace OwinOAuthProvidersDemo
{ {
@@ -311,6 +312,8 @@ namespace OwinOAuthProvidersDemo
//}); //});
//app.UseVKontakteAuthentication("", ""); //app.UseVKontakteAuthentication("", "");
//app.UseXingAuthentication("", "");
} }
} }
} }