diff --git a/Owin.Security.Providers/Owin.Security.Providers.csproj b/Owin.Security.Providers/Owin.Security.Providers.csproj index 34714d3..e43b426 100644 --- a/Owin.Security.Providers/Owin.Security.Providers.csproj +++ b/Owin.Security.Providers/Owin.Security.Providers.csproj @@ -68,6 +68,19 @@ True Resources.resx + + + + + + + + + + + + + diff --git a/Owin.Security.Providers/Yahoo/Constants.cs b/Owin.Security.Providers/Yahoo/Constants.cs new file mode 100644 index 0000000..327c544 --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Constants.cs @@ -0,0 +1,9 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +namespace Owin.Security.Providers.Yahoo +{ + internal static class Constants + { + public const string DefaultAuthenticationType = "Yahoo"; + } +} diff --git a/Owin.Security.Providers/Yahoo/Messages/AccessToken.cs b/Owin.Security.Providers/Yahoo/Messages/AccessToken.cs new file mode 100644 index 0000000..468866f --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Messages/AccessToken.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +namespace Owin.Security.Providers.Yahoo.Messages +{ + /// + /// Yahoo access token + /// + public class AccessToken : RequestToken + { + /// + /// Gets or sets the Yahoo User ID + /// + public string UserId { get; set; } + } +} diff --git a/Owin.Security.Providers/Yahoo/Messages/RequestToken.cs b/Owin.Security.Providers/Yahoo/Messages/RequestToken.cs new file mode 100644 index 0000000..a0e9d8c --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Messages/RequestToken.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin.Security; + +namespace Owin.Security.Providers.Yahoo.Messages +{ + /// + /// Yahoo request token + /// + public class RequestToken + { + /// + /// Gets or sets the Yahoo token + /// + public string Token { get; set; } + + /// + /// Gets or sets the Yahoo token secret + /// + public string TokenSecret { get; set; } + + public bool CallbackConfirmed { get; set; } + + /// + /// Gets or sets a property bag for common authentication properties + /// + public AuthenticationProperties Properties { get; set; } + } +} diff --git a/Owin.Security.Providers/Yahoo/Messages/RequestTokenSerializer.cs b/Owin.Security.Providers/Yahoo/Messages/RequestTokenSerializer.cs new file mode 100644 index 0000000..1aa9325 --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Messages/RequestTokenSerializer.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.DataHandler.Serializer; + +namespace Owin.Security.Providers.Yahoo.Messages +{ + /// + /// Serializes and deserializes Yahoo request and access tokens so that they can be used by other application components. + /// + public class RequestTokenSerializer : IDataSerializer + { + private const int FormatVersion = 1; + + /// + /// Serialize a request token + /// + /// The token to serialize + /// A byte array containing the serialized token + [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Dispose is idempotent")] + 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(); + } + } + } + + /// + /// Deserializes a request token + /// + /// A byte array containing the serialized token + /// The Yahoo request token + [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Dispose is idempotent")] + public virtual RequestToken Deserialize(byte[] data) + { + using (var memory = new MemoryStream(data)) + { + using (var reader = new BinaryReader(memory)) + { + return Read(reader); + } + } + } + + /// + /// Writes a Yahoo request token as a series of bytes. Used by the method. + /// + /// The writer to use in writing the token + /// The token to write + 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); + } + + /// + /// Reads a Yahoo request token from a series of bytes. Used by the method. + /// + /// The reader to use in reading the token bytes + /// The token + 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 }; + } + } +} diff --git a/Owin.Security.Providers/Yahoo/Messages/Serializers.cs b/Owin.Security.Providers/Yahoo/Messages/Serializers.cs new file mode 100644 index 0000000..7e48160 --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Messages/Serializers.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin.Security.DataHandler.Serializer; + +namespace Owin.Security.Providers.Yahoo.Messages +{ + /// + /// Provides access to a request token serializer + /// + public static class Serializers + { + static Serializers() + { + RequestToken = new RequestTokenSerializer(); + } + + /// + /// Gets or sets a statically-avaliable serializer object. The value for this property will be by default. + /// + public static IDataSerializer RequestToken { get; set; } + } +} diff --git a/Owin.Security.Providers/Yahoo/Provider/IYahooAuthenticationProvider.cs b/Owin.Security.Providers/Yahoo/Provider/IYahooAuthenticationProvider.cs new file mode 100644 index 0000000..8a8594f --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Provider/IYahooAuthenticationProvider.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface IYahooAuthenticationProvider + { + /// + /// Invoked whenever Yahoo succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(YahooAuthenticatedContext context); + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + Task ReturnEndpoint(YahooReturnEndpointContext context); + } +} diff --git a/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticatedContext.cs b/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticatedContext.cs new file mode 100644 index 0000000..1836ab8 --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticatedContext.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System.Security.Claims; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; +using Newtonsoft.Json.Linq; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Contains information about the login session as well as the user . + /// + public class YahooAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The JSON serialized user + /// Yahoo user ID + /// Yahoo access token + /// Yahoo access token secret + public YahooAuthenticatedContext( + IOwinContext context, + JObject user, + string userId, + string accessToken, + string accessTokenSecret) + : base(context) + { + User = user; + UserId = userId; + NickName = TryGetValue(user, "nickname"); + AccessToken = accessToken; + AccessTokenSecret = accessTokenSecret; + } + + /// + /// Gets the JSON-serialized user + /// + /// + /// Contains the LinkedIn user obtained from the endpoint http://social.yahooapis.com/v1/user/{guid}/profile/usercard + /// + public JObject User { get; private set; } + + /// + /// Gets the Yahoo user ID + /// + public string UserId { get; private set; } + + /// + /// Gets the Yaho0 nickname + /// + public string NickName { get; private set; } + + /// + /// Gets the Yahoo access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Yahoo access token secret + /// + public string AccessTokenSecret { get; private set; } + + /// + /// Gets the representing the user + /// + public ClaimsIdentity Identity { get; set; } + + /// + /// Gets or sets a property bag for common authentication properties + /// + public AuthenticationProperties Properties { get; set; } + + private static string TryGetValue(JObject user, string propertyName) + { + JToken value; + return user.TryGetValue(propertyName, out value) ? value.ToString() : null; + } + } +} diff --git a/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticationProvider.cs b/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticationProvider.cs new file mode 100644 index 0000000..9e66d2a --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Provider/YahooAuthenticationProvider.cs @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Default implementation. + /// + public class YahooAuthenticationProvider : IYahooAuthenticationProvider + { + /// + /// Initializes a + /// + public YahooAuthenticationProvider() + { + OnAuthenticated = context => Task.FromResult(null); + OnReturnEndpoint = context => Task.FromResult(null); + } + + /// + /// Gets or sets the function that is invoked when the Authenticated method is invoked. + /// + public Func OnAuthenticated { get; set; } + + /// + /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. + /// + public Func OnReturnEndpoint { get; set; } + + /// + /// Invoked whenever Yahoo succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(YahooAuthenticatedContext context) + { + return OnAuthenticated(context); + } + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + public virtual Task ReturnEndpoint(YahooReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} diff --git a/Owin.Security.Providers/Yahoo/Provider/YahooReturnEndpointContext.cs b/Owin.Security.Providers/Yahoo/Provider/YahooReturnEndpointContext.cs new file mode 100644 index 0000000..bf6486f --- /dev/null +++ b/Owin.Security.Providers/Yahoo/Provider/YahooReturnEndpointContext.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Provides context information to middleware providers. + /// + public class YahooReturnEndpointContext : ReturnEndpointContext + { + /// + /// Initializes a new . + /// + /// OWIN environment + /// The authentication ticket + public YahooReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/Owin.Security.Providers/Yahoo/YahooAuthenticationExtensions.cs b/Owin.Security.Providers/Yahoo/YahooAuthenticationExtensions.cs new file mode 100644 index 0000000..805e5c2 --- /dev/null +++ b/Owin.Security.Providers/Yahoo/YahooAuthenticationExtensions.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Extension methods for using + /// + public static class YahooAuthenticationExtensions + { + /// + /// Authenticate users using Yahoo + /// + /// The passed to the configuration method + /// Middleware configuration options + /// The updated + public static IAppBuilder UseYahooAuthentication(this IAppBuilder app, YahooAuthenticationOptions options) + { + if (app == null) + { + throw new ArgumentNullException("app"); + } + if (options == null) + { + throw new ArgumentNullException("options"); + } + + app.Use(typeof(YahooAuthenticationMiddleware), app, options); + return app; + } + + /// + /// Authenticate users using Yahoo + /// + /// The passed to the configuration method + /// The Yahoo-issued consumer key + /// The Yahoo-issued consumer secret + /// The updated + public static IAppBuilder UseYahooAuthentication( + this IAppBuilder app, + string consumerKey, + string consumerSecret) + { + return UseYahooAuthentication( + app, + new YahooAuthenticationOptions + { + ConsumerKey = consumerKey, + ConsumerSecret = consumerSecret, + }); + } + } +} diff --git a/Owin.Security.Providers/Yahoo/YahooAuthenticationHandler.cs b/Owin.Security.Providers/Yahoo/YahooAuthenticationHandler.cs new file mode 100644 index 0000000..cd4b40e --- /dev/null +++ b/Owin.Security.Providers/Yahoo/YahooAuthenticationHandler.cs @@ -0,0 +1,431 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Runtime.InteropServices; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +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 Newtonsoft.Json.Linq; +using Owin.Security.Providers.Yahoo.Messages; + +namespace Owin.Security.Providers.Yahoo +{ + internal class YahooAuthenticationHandler : AuthenticationHandler + { + private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + private const string StateCookie = "__YahooState"; + private const string RequestTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_request_token"; + private const string AuthenticationEndpoint = "https://api.login.yahoo.com/oauth/v2/request_auth?oauth_token="; + private const string AccessTokenEndpoint = "https://api.login.yahoo.com/oauth/v2/get_token"; + + private readonly HttpClient _httpClient; + private readonly ILogger _logger; + + public YahooAuthenticationHandler(HttpClient httpClient, ILogger logger) + { + _httpClient = httpClient; + _logger = logger; + } + + public override async Task InvokeAsync() + { + if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) + { + return await InvokeReturnPathAsync(); + } + return false; + } + + protected override async Task AuthenticateCoreAsync() + { + AuthenticationProperties properties = null; + try + { + IReadableStringCollection query = Request.Query; + string protectedRequestToken = Request.Cookies[StateCookie]; + + RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken); + + if (requestToken == null) + { + _logger.WriteWarning("Invalid state"); + return null; + } + + properties = requestToken.Properties; + + string 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); + } + + string oauthVerifier = query.Get("oauth_verifier"); + if (string.IsNullOrWhiteSpace(oauthVerifier)) + { + _logger.WriteWarning("Missing or blank oauth_verifier"); + return new AuthenticationTicket(null, properties); + } + + AccessToken accessToken = await ObtainAccessTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, requestToken, oauthVerifier); + + JObject userCard = await ObtainUserCard(Options.ConsumerKey, Options.ConsumerSecret, accessToken, oauthVerifier); + + var context = new YahooAuthenticatedContext(Context, userCard, accessToken.UserId, accessToken.Token, accessToken.TokenSecret); + + context.Identity = new ClaimsIdentity( + new[] + { + new Claim(ClaimTypes.NameIdentifier, context.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), + new Claim(ClaimTypes.Name, context.NickName, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), + new Claim("urn:yahoo:userid", context.UserId, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType), + new Claim("urn:yahoo:nickname", context.NickName, "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); + } + } + + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "MemoryStream.Dispose is idempotent")] + protected override async Task ApplyResponseChallengeAsync() + { + if (Response.StatusCode != 401) + { + return; + } + + AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); + + if (challenge != null) + { + string requestPrefix = Request.Scheme + "://" + Request.Host; + string callBackUrl = requestPrefix + RequestPathBase + Options.CallbackPath; + + AuthenticationProperties extra = challenge.Properties; + if (string.IsNullOrEmpty(extra.RedirectUri)) + { + extra.RedirectUri = requestPrefix + Request.PathBase + Request.Path + Request.QueryString; + } + + RequestToken requestToken = await ObtainRequestTokenAsync(Options.ConsumerKey, Options.ConsumerSecret, callBackUrl, extra); + + if (requestToken.CallbackConfirmed) + { + string yahooAuthenticationEndpoint = AuthenticationEndpoint + requestToken.Token; + + var cookieOptions = new CookieOptions + { + HttpOnly = true, + Secure = Request.IsSecure + }; + + Response.StatusCode = 302; + Response.Cookies.Append(StateCookie, Options.StateDataFormat.Protect(requestToken), cookieOptions); + Response.Headers.Set("Location", yahooAuthenticationEndpoint); + } + else + { + _logger.WriteError("requestToken CallbackConfirmed!=true"); + } + } + } + + public async Task InvokeReturnPathAsync() + { + AuthenticationTicket model = await AuthenticateAsync(); + if (model == null) + { + _logger.WriteWarning("Invalid return state, unable to redirect."); + Response.StatusCode = 500; + return true; + } + + var context = new YahooReturnEndpointContext(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) + { + ClaimsIdentity 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 ObtainRequestTokenAsync(string consumerKey, string consumerSecret, string callBackUri, AuthenticationProperties properties) + { + // http://developer.yahoo.com/oauth/guide/oauth-requesttoken.html + + _logger.WriteVerbose("ObtainRequestToken"); + + string nonce = Guid.NewGuid().ToString("N"); + + var authorizationParts = new SortedDictionary + { + { "oauth_callback", callBackUri }, + { "oauth_consumer_key", consumerKey }, + { "oauth_nonce", nonce }, + { "oauth_signature_method", "HMAC-SHA1" }, + { "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--; + string parameterString = parameterBuilder.ToString(); + + var canonicalizedRequestBuilder = new StringBuilder(); + canonicalizedRequestBuilder.Append(HttpMethod.Post.Method); + canonicalizedRequestBuilder.Append("&"); + canonicalizedRequestBuilder.Append(Uri.EscapeDataString(RequestTokenEndpoint)); + canonicalizedRequestBuilder.Append("&"); + canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString)); + + string 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()); + + HttpResponseMessage response = await _httpClient.SendAsync(request, Request.CallCancelled); + response.EnsureSuccessStatusCode(); + string responseText = await response.Content.ReadAsStringAsync(); + + IFormCollection 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 ObtainAccessTokenAsync(string consumerKey, string consumerSecret, RequestToken token, string verifier) + { + // http://developer.yahoo.com/oauth/guide/oauth-accesstoken.html + + _logger.WriteVerbose("ObtainAccessToken"); + + string nonce = Guid.NewGuid().ToString("N"); + + var authorizationParts = new SortedDictionary + { + { "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--; + string 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)); + + string signature = ComputeSignature(consumerSecret, token.TokenSecret, 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, AccessTokenEndpoint); + request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); + + var formPairs = new List>() + { + new KeyValuePair("oauth_verifier", verifier) + }; + + request.Content = new FormUrlEncodedContent(formPairs); + + HttpResponseMessage 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 + } + + string responseText = await response.Content.ReadAsStringAsync(); + + IFormCollection responseParameters = WebHelpers.ParseForm(responseText); + + return new AccessToken + { + Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), + TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), + UserId = Uri.UnescapeDataString(responseParameters["xoauth_yahoo_guid"]) + }; + } + + private async Task ObtainUserCard(string consumerKey, string consumerSecret, AccessToken token, string verifier) + { + // http://developer.yahoo.com/social/rest_api_guide/usercard-resource.html + + _logger.WriteVerbose("ObtainAccessToken"); + + string nonce = Guid.NewGuid().ToString("N"); + string requestUrl = string.Format("http://social.yahooapis.com/v1/user/{0}/profile/usercard", token.UserId); + + var authorizationParts = new SortedDictionary + { + { "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--; + string parameterString = parameterBuilder.ToString(); + + var canonicalizedRequestBuilder = new StringBuilder(); + canonicalizedRequestBuilder.Append(HttpMethod.Get.Method); + canonicalizedRequestBuilder.Append("&"); + canonicalizedRequestBuilder.Append(Uri.EscapeDataString(requestUrl)); + canonicalizedRequestBuilder.Append("&"); + canonicalizedRequestBuilder.Append(Uri.EscapeDataString(parameterString)); + + string signature = ComputeSignature(consumerSecret, token.TokenSecret, 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.Get, requestUrl); + request.Headers.Add("Authorization", authorizationHeaderBuilder.ToString()); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + HttpResponseMessage 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 + } + + string responseText = await response.Content.ReadAsStringAsync(); + JObject responseObject = JObject.Parse(responseText); + JObject userCard = responseObject.GetValue("profile").ToObject(); + + return userCard; + } + + private static string GenerateTimeStamp() + { + TimeSpan 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))); + byte[] hash = algorithm.ComputeHash(Encoding.ASCII.GetBytes(signatureData)); + return Convert.ToBase64String(hash); + } + } + } +} diff --git a/Owin.Security.Providers/Yahoo/YahooAuthenticationMiddleware.cs b/Owin.Security.Providers/Yahoo/YahooAuthenticationMiddleware.cs new file mode 100644 index 0000000..de4593a --- /dev/null +++ b/Owin.Security.Providers/Yahoo/YahooAuthenticationMiddleware.cs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Logging; +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.Yahoo.Messages; +using AppBuilderSecurityExtensions = Microsoft.Owin.Security.AppBuilderSecurityExtensions; +using Owin.Security.Providers.Properties; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// OWIN middleware for authenticating users using Yahoo + /// + [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Middleware are not disposable.")] + public class YahooAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly ILogger _logger; + private readonly HttpClient _httpClient; + + /// + /// Initializes a + /// + /// The next middleware in the OWIN pipeline to invoke + /// The OWIN application + /// Configuration options for the middleware + public YahooAuthenticationMiddleware( + OwinMiddleware next, + IAppBuilder app, + YahooAuthenticationOptions options) + : base(next, options) + { + _logger = app.CreateLogger(); + + 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 YahooAuthenticationProvider(); + } + if (Options.StateDataFormat == null) + { + IDataProtector dataProtector = app.CreateDataProtector( + typeof(YahooAuthenticationMiddleware).FullName, + Options.AuthenticationType, "v1"); + Options.StateDataFormat = new SecureDataFormat( + Serializers.RequestToken, + dataProtector, + TextEncodings.Base64Url); + } + if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType)) + { + Options.SignInAsAuthenticationType = AppBuilderSecurityExtensions.GetDefaultSignInAsAuthenticationType(app); + } + + _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 Yahoo middleware"); + _httpClient.DefaultRequestHeaders.ExpectContinue = false; + } + + /// + /// Provides the object for processing authentication-related requests. + /// + /// An configured with the supplied to the constructor. + protected override AuthenticationHandler CreateHandler() + { + return new YahooAuthenticationHandler(_httpClient, _logger); + } + + [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Managed by caller")] + private static HttpMessageHandler ResolveHttpMessageHandler(YahooAuthenticationOptions options) + { + HttpMessageHandler 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; + } + } +} diff --git a/Owin.Security.Providers/Yahoo/YahooAuthenticationOptions.cs b/Owin.Security.Providers/Yahoo/YahooAuthenticationOptions.cs new file mode 100644 index 0000000..1f35a0a --- /dev/null +++ b/Owin.Security.Providers/Yahoo/YahooAuthenticationOptions.cs @@ -0,0 +1,101 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Owin.Security.Providers.Yahoo.Messages; + +namespace Owin.Security.Providers.Yahoo +{ + /// + /// Options for the Yahoo authentication middleware. + /// + public class YahooAuthenticationOptions : AuthenticationOptions + { + /// + /// Initializes a new instance of the class. + /// + [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", + MessageId = "Owin.Security.Yahoo.YahooAuthenticationOptions.set_Caption(System.String)", Justification = "Not localizable")] + public YahooAuthenticationOptions() + : base(Constants.DefaultAuthenticationType) + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-yahoo"); + AuthenticationMode = AuthenticationMode.Passive; + BackchannelTimeout = TimeSpan.FromSeconds(60); + BackchannelCertificateValidator = null; + } + + /// + /// Gets or sets the consumer key used to communicate with Yahoo. + /// + /// The consumer key used to communicate with Yahoo. + public string ConsumerKey { get; set; } + + /// + /// Gets or sets the consumer secret used to sign requests to Yahoo. + /// + /// The consumer secret used to sign requests to Yahoo. + public string ConsumerSecret { get; set; } + + /// + /// Gets or sets timeout value in milliseconds for back channel communications with Yahoo. + /// + /// + /// The back channel timeout. + /// + public TimeSpan BackchannelTimeout { get; set; } + + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to Yahoo. + /// + /// + /// The pinned certificate validator. + /// + /// If this property is null then the default certificate checks are performed, + /// validating the subject name and if the signing chain is a trusted party. + public ICertificateValidator BackchannelCertificateValidator { get; set; } + + /// + /// The HttpMessageHandler used to communicate with Yahoo. + /// This cannot be set at the same time as BackchannelCertificateValidator unless the value + /// can be downcast to a WebRequestHandler. + /// + public HttpMessageHandler BackchannelHttpHandler { get; set; } + + /// + /// Get or sets the text that the user can display on a sign in user interface. + /// + public string Caption + { + get { return Description.Caption; } + set { Description.Caption = value; } + } + + /// + /// 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-yahoo". + /// + public PathString CallbackPath { get; set; } + + /// + /// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user . + /// + public string SignInAsAuthenticationType { get; set; } + + /// + /// Gets or sets the type used to secure data handled by the middleware. + /// + public ISecureDataFormat StateDataFormat { get; set; } + + /// + /// Gets or sets the used to handle authentication events. + /// + public IYahooAuthenticationProvider Provider { get; set; } + } +} diff --git a/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833.mdf b/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833.mdf index c2ad122..b2d4b79 100644 Binary files a/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833.mdf and b/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833.mdf differ diff --git a/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833_log.ldf b/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833_log.ldf index b76402c..673645b 100644 Binary files a/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833_log.ldf and b/OwinOAuthProvidersDemo/App_Data/aspnet-OwinOAuthProvidersDemo-20131113093833_log.ldf differ diff --git a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs index c59874b..1376c31 100644 --- a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs +++ b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs @@ -3,6 +3,7 @@ using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using Owin.Security.Providers.LinkedIn; +using Owin.Security.Providers.Yahoo; namespace OwinOAuthProvidersDemo { @@ -35,7 +36,11 @@ namespace OwinOAuthProvidersDemo //app.UseGoogleAuthentication(); - app.UseLinkedInAuthentication("", ""); + //app.UseLinkedInAuthentication("", ""); + + //app.UseYahooAuthentication( + // "", + // ""); } } } \ No newline at end of file diff --git a/OwinOAuthProvidersDemo/Scripts/_references.js b/OwinOAuthProvidersDemo/Scripts/_references.js index a13d947..0b3a95c 100644 --- a/OwinOAuthProvidersDemo/Scripts/_references.js +++ b/OwinOAuthProvidersDemo/Scripts/_references.js @@ -1,5 +1,7 @@ -/// -/// -/// +/// /// +/// +/// +/// +/// ///