Add new provider DoYouBuzz

Add new french provider DoYouBuzz, a website which hosts CVs
This commit is contained in:
Yoann Blossier
2016-02-11 09:53:17 +01:00
parent fb0f78c250
commit 1a5b85eebe
18 changed files with 1155 additions and 0 deletions

View File

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

View File

@@ -0,0 +1,28 @@
using System;
namespace Owin.Security.Providers.DoYouBuzz
{
public static class DoYouBuzzAuthenticationExtensions
{
public static IAppBuilder UseDoYouBuzzAuthentication(this IAppBuilder app, DoYouBuzzAuthenticationOptions options)
{
if (app == null)
throw new ArgumentNullException("app");
if (options == null)
throw new ArgumentNullException("options");
app.Use(typeof(DoYouBuzzAuthenticationMiddleware), app, options);
return app;
}
public static IAppBuilder UseDoYouBuzzAuthentication(this IAppBuilder app, string consumerKey, string consumerSecret)
{
return app.UseDoYouBuzzAuthentication(new DoYouBuzzAuthenticationOptions
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret
});
}
}
}

View File

@@ -0,0 +1,434 @@
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 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 System.Xml;
using Newtonsoft.Json;
using Owin.Security.Providers.DoYouBuzz.Messages;
using Formatting = Newtonsoft.Json.Formatting;
namespace Owin.Security.Providers.DoYouBuzz
{
internal class DoYouBuzzAuthenticationHandler : AuthenticationHandler<DoYouBuzzAuthenticationOptions>
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const string StateCookie = "__DoYouBuzzState";
private const string RequestTokenEndpoint = "http://www.doyoubuzz.com/fr/oauth/requestToken";
private const string AuthenticationEndpoint = "http://www.doyoubuzz.com/fr/oauth/authorize?oauth_token=";
private const string AccessTokenEndpoint = "http://www.doyoubuzz.com/fr/oauth/accessToken";
private const string UserInfoEndpoint = "https://api.doyoubuzz.com/user";
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
public DoYouBuzzAuthenticationHandler(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 DoYouBuzzAuthenticatedContext(Context, accessToken.UserId, accessToken.Token, accessToken.TokenSecret)
{
Identity = new ClaimsIdentity(
new[]
{
new Claim(ClaimTypes.NameIdentifier, accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
new Claim("urn:DoYouBuzz:userid", accessToken.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType),
},
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType),
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 doYouBuzzAuthenticationEndpoint = AuthenticationEndpoint + requestToken.Token;
var cookieOptions = new CookieOptions
{
HttpOnly = true,
Secure = Request.IsSecure
};
Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions);
var redirectContext = new DoYouBuzzApplyRedirectContext(
Context, Options,
extra, doYouBuzzAuthenticationEndpoint);
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 DoYouBuzzReturnEndpointContext(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.DoYouBuzz.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);
var accessToken = new AccessToken
{
Token = Uri.UnescapeDataString(responseParameters["oauth_token"]),
TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]),
UserId = "",
};
var userInfo = GetUserInfo(consumerKey, consumerSecret, accessToken);
accessToken.UserId = userInfo.Id.ToString();
return accessToken;
}
private async Task<AccessToken> GetUserInfo(string consumerKey, string consumerSecret, AccessToken token)
{
_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_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(UserInfoEndpoint));
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, UserInfoEndpoint);
request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString());
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 document = new XmlDocument();
document.LoadXml(responseText);
var json = JsonConvert.SerializeXmlNode(document, Formatting.None);
var userInfo = JsonConvert.DeserializeObject<UserInfo>(json);
return new AccessToken
{
Token = token.Token,
TokenSecret = token.TokenSecret,
UserId = userInfo.Id.ToString(),
};
}
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,97 @@
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 System;
using System.Globalization;
using System.Net.Http;
using Owin.Security.Providers.DoYouBuzz.Messages;
using Owin.Security.Providers.Properties;
namespace Owin.Security.Providers.DoYouBuzz
{
/// <summary>
/// OWIN middleware for authenticating users using DoYouBuzz
/// </summary>
public class DoYouBuzzAuthenticationMiddleware : AuthenticationMiddleware<DoYouBuzzAuthenticationOptions>
{
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a <see cref="DoYouBuzzAuthenticationMiddleware"/>
/// </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 DoYouBuzzAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, DoYouBuzzAuthenticationOptions options)
: base(next, options)
{
_logger = app.CreateLogger<DoYouBuzzAuthenticationMiddleware>();
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"));
}
if (Options.Provider == null)
{
Options.Provider = new DoYouBuzzAuthenticationProvider();
}
if (Options.StateDataFormat == null)
{
var dataProtector = app.CreateDataProtector(typeof(DoYouBuzzAuthenticationMiddleware).FullName, Options.AuthenticationType, "v1");
Options.StateDataFormat = new SecureDataFormat<RequestToken>(Serializers.RequestToken, dataProtector, TextEncodings.Base64Url);
}
if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType))
{
Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
}
_httpClient = new HttpClient(ResolveHttpMessageHandler(Options));
_httpClient.Timeout = Options.BackchannelTimeout;
_httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
_httpClient.DefaultRequestHeaders.Accept.ParseAdd("*/*");
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin DoYouBuzz 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="DoYouBuzzAuthenticationOptions"/> supplied to the constructor.</returns>
protected override AuthenticationHandler<DoYouBuzzAuthenticationOptions> CreateHandler()
{
return new DoYouBuzzAuthenticationHandler(_httpClient, _logger);
}
private static HttpMessageHandler ResolveHttpMessageHandler(DoYouBuzzAuthenticationOptions 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;
}
}
}

View File

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

View File

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

View File

@@ -0,0 +1,30 @@
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.DoYouBuzz.Messages
{
/// <summary>
/// DoYouBuzz request token
/// </summary>
public class RequestToken
{
/// <summary>
/// Gets or sets the DoYouBuzz token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Gets or sets the DoYouBuzz 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.DoYouBuzz.Messages
{
/// <summary>
/// Serializes and deserializes DoYouBuzz 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 DoYouBuzz 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 DoYouBuzz 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 DoYouBuzz 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,45 @@
using System;
using Newtonsoft.Json;
namespace Owin.Security.Providers.DoYouBuzz.Messages
{
[Serializable]
[JsonArray("resume")]
internal class Resume
{
/// <summary>
/// The unique identifier
/// </summary>
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// The title
/// </summary>
[JsonProperty("title")]
public string Title { get; set; }
/// <summary>
/// Indicates if this is the user's main resume
/// </summary>
[JsonProperty("main")]
public bool Main { get; set; }
/// <summary>
/// <para>The culture of the resume</para>
/// <para>
/// The possible values are
/// <list type="disc">
/// <item>fr_FR</item>
/// <item>en_US</item>
/// <item>en_UK</item>
/// <item>it_IT</item>
/// <item>es_ES</item>
/// <item>de_DE</item>
/// </list>
/// </para>
/// </summary>
[JsonProperty("culture")]
public string Culture { get; set; }
}
}

View File

@@ -0,0 +1,20 @@
using Microsoft.Owin.Security.DataHandler.Serializer;
namespace Owin.Security.Providers.DoYouBuzz.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,57 @@
using System;
using Newtonsoft.Json;
namespace Owin.Security.Providers.DoYouBuzz.Messages
{
[Serializable]
internal class UserInfo
{
/// <summary>
/// The unique identifier
/// </summary>
[JsonProperty("id")]
public int Id { get; set; }
/// <summary>
/// The last name
/// </summary>
[JsonProperty("lastname")]
public string LastName { get; set; }
/// <summary>
/// The first name
/// </summary>
[JsonProperty("firstname")]
public string FirstName { get; set; }
/// <summary>
/// The slug of the user's profile (append to http://www.doyoubuzz.com/ to get the user's main resume url)
/// </summary>
[JsonProperty("slug")]
public string Slug { get; set; }
/// <summary>
/// The registration date
/// </summary>
[JsonProperty("registeredAt")]
public DateTime RegisteredAt { get; set; }
/// <summary>
/// Indicates if the user is a Premium DoYouBuzz user
/// </summary>
[JsonProperty("premium")]
public bool Premium { get; set; }
/// <summary>
/// The email verified
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// The user's resumes
/// </summary>
[JsonProperty("resumes")]
public Resume[] Resumes { get; set; }
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.DoYouBuzz
{
/// <summary>
/// Context passed when a Challenge causes a redirect to authorize endpoint in the DoYouBuzz middleware
/// </summary>
public class DoYouBuzzApplyRedirectContext : BaseContext<DoYouBuzzAuthenticationOptions>
{
/// <summary>
/// Creates a new context object.
/// </summary>
/// <param name="context">The OWIN request context</param>
/// <param name="options">The DoYouBuzz middleware options</param>
/// <param name="properties">The authentication properties of the challenge</param>
/// <param name="redirectUri">The initial redirect URI</param>
public DoYouBuzzApplyRedirectContext(IOwinContext context, DoYouBuzzAuthenticationOptions 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.DoYouBuzz
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class DoYouBuzzAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="DoYouBuzzAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="userId">DoYouBuzz user ID</param>
/// <param name="accessToken">DoYouBuzz access token</param>
/// <param name="accessTokenSecret">DoYouBuzz access token secret</param>
public DoYouBuzzAuthenticatedContext(IOwinContext context, string userId, string accessToken, string accessTokenSecret)
: base(context)
{
UserId = userId;
AccessToken = accessToken;
AccessTokenSecret = accessTokenSecret;
}
/// <summary>
/// Gets the DoYouBuzz user ID
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Gets the DoYouBuzz access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the DoYouBuzz 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.DoYouBuzz
{
/// <summary>
/// Default <see cref="IDoYouBuzzAuthenticationProvider"/> implementation.
/// </summary>
public class DoYouBuzzAuthenticationProvider : IDoYouBuzzAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="DoYouBuzzAuthenticationProvider"/>
/// </summary>
public DoYouBuzzAuthenticationProvider()
{
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<DoYouBuzzAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<DoYouBuzzReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Gets or sets the delegate that is invoked when the ApplyRedirect method is invoked.
/// </summary>
public Action<DoYouBuzzApplyRedirectContext> OnApplyRedirect { get; set; }
/// <summary>
/// Invoked whenever DoYouBuzz 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(DoYouBuzzAuthenticatedContext 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(DoYouBuzzReturnEndpointContext context)
{
return OnReturnEndpoint(context);
}
/// <summary>
/// Called when a Challenge causes a redirect to authorize endpoint in the DoYouBuzz middleware
/// </summary>
/// <param name="context">Contains redirect URI and <see cref="AuthenticationProperties"/> of the challenge </param>
public virtual void ApplyRedirect(DoYouBuzzApplyRedirectContext 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.DoYouBuzz
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class DoYouBuzzReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
/// Initializes a new <see cref="DoYouBuzzReturnEndpointContext"/>.
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public DoYouBuzzReturnEndpointContext(IOwinContext context, AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

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

View File

@@ -113,6 +113,22 @@
<Compile Include="DeviantArt\DeviantAuthenticationHandler.cs" /> <Compile Include="DeviantArt\DeviantAuthenticationHandler.cs" />
<Compile Include="DeviantArt\DeviantAuthenticationMiddleware.cs" /> <Compile Include="DeviantArt\DeviantAuthenticationMiddleware.cs" />
<Compile Include="DeviantArt\DeviantAuthenticationOptions.cs" /> <Compile Include="DeviantArt\DeviantAuthenticationOptions.cs" />
<Compile Include="DoYouBuzz\Constants.cs" />
<Compile Include="DoYouBuzz\DoYouBuzzAuthenticationHandler.cs" />
<Compile Include="DoYouBuzz\DoYouBuzzAuthenticationMiddleware.cs" />
<Compile Include="DoYouBuzz\DoYouBuzzAuthenticationOptions.cs" />
<Compile Include="DoYouBuzz\Messages\AccessToken.cs" />
<Compile Include="DoYouBuzz\Messages\RequestToken.cs" />
<Compile Include="DoYouBuzz\Messages\RequestTokenSerializer.cs" />
<Compile Include="DoYouBuzz\Messages\Resume.cs" />
<Compile Include="DoYouBuzz\Messages\Serializer.cs" />
<Compile Include="DoYouBuzz\Messages\UserInfo.cs" />
<Compile Include="DoYouBuzz\Provider\DoYouBuzzApplyRedirectContext.cs" />
<Compile Include="DoYouBuzz\Provider\DoYouBuzzAuthenticatedContext.cs" />
<Compile Include="DoYouBuzz\Provider\DoYouBuzzAuthenticationProvider.cs" />
<Compile Include="DoYouBuzz\Provider\DoYouBuzzReturnEndpointContext.cs" />
<Compile Include="DoYouBuzz\Provider\IDoYouBuzzAuthenticationProvider.cs" />
<Compile Include="DoYouBuzz\DoYouBuzzAuthenticationExtensions.cs" />
<Compile Include="Dropbox\DropboxAuthenticationExtensions.cs" /> <Compile Include="Dropbox\DropboxAuthenticationExtensions.cs" />
<Compile Include="Dropbox\DropboxAuthenticationHandler.cs" /> <Compile Include="Dropbox\DropboxAuthenticationHandler.cs" />
<Compile Include="Dropbox\DropboxAuthenticationMiddleware.cs" /> <Compile Include="Dropbox\DropboxAuthenticationMiddleware.cs" />

View File

@@ -38,6 +38,7 @@ using Owin.Security.Providers.Wargaming;
using Owin.Security.Providers.WordPress; using Owin.Security.Providers.WordPress;
using Owin.Security.Providers.Yahoo; using Owin.Security.Providers.Yahoo;
using Owin.Security.Providers.Backlog; using Owin.Security.Providers.Backlog;
using Owin.Security.Providers.DoYouBuzz;
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; using Owin.Security.Providers.Onshape;
@@ -314,6 +315,8 @@ namespace OwinOAuthProvidersDemo
//app.UseVKontakteAuthentication("", ""); //app.UseVKontakteAuthentication("", "");
//app.UseXingAuthentication("", ""); //app.UseXingAuthentication("", "");
//app.UseDoYouBuzzAuthentication("", "");
} }
} }
} }