Adds Yahoo middleware

This commit is contained in:
Jerrie Pelser
2013-11-13 15:04:21 +07:00
parent 9e5212050a
commit f8eadbba5e
18 changed files with 1088 additions and 4 deletions

View File

@@ -68,6 +68,19 @@
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Yahoo\Constants.cs" />
<Compile Include="Yahoo\Messages\AccessToken.cs" />
<Compile Include="Yahoo\Messages\RequestToken.cs" />
<Compile Include="Yahoo\Messages\RequestTokenSerializer.cs" />
<Compile Include="Yahoo\Messages\Serializers.cs" />
<Compile Include="Yahoo\Provider\IYahooAuthenticationProvider.cs" />
<Compile Include="Yahoo\Provider\YahooAuthenticatedContext.cs" />
<Compile Include="Yahoo\Provider\YahooAuthenticationProvider.cs" />
<Compile Include="Yahoo\Provider\YahooReturnEndpointContext.cs" />
<Compile Include="Yahoo\YahooAuthenticationExtensions.cs" />
<Compile Include="Yahoo\YahooAuthenticationHandler.cs" />
<Compile Include="Yahoo\YahooAuthenticationMiddleware.cs" />
<Compile Include="Yahoo\YahooAuthenticationOptions.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Properties\Resources.resx">

View File

@@ -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";
}
}

View File

@@ -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
{
/// <summary>
/// Yahoo access token
/// </summary>
public class AccessToken : RequestToken
{
/// <summary>
/// Gets or sets the Yahoo User ID
/// </summary>
public string UserId { get; set; }
}
}

View File

@@ -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
{
/// <summary>
/// Yahoo request token
/// </summary>
public class RequestToken
{
/// <summary>
/// Gets or sets the Yahoo token
/// </summary>
public string Token { get; set; }
/// <summary>
/// Gets or sets the Yahoo token secret
/// </summary>
public string TokenSecret { get; set; }
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,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
{
/// <summary>
/// Serializes and deserializes Yahoo 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>
[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();
}
}
}
/// <summary>
/// Deserializes a request token
/// </summary>
/// <param name="data">A byte array containing the serialized token</param>
/// <returns>The Yahoo request token</returns>
[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);
}
}
}
/// <summary>
/// Writes a Yahoo 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 Yahoo 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,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
{
/// <summary>
/// Provides access to a request token serializer
/// </summary>
public static class Serializers
{
static Serializers()
{
RequestToken = new RequestTokenSerializer();
}
/// <summary>
/// Gets or sets a statically-avaliable 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,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
{
/// <summary>
/// Specifies callback methods which the <see cref="YahooAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IYahooAuthenticationProvider
{
/// <summary>
/// Invoked whenever Yahoo succesfully 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(YahooAuthenticatedContext 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(YahooReturnEndpointContext context);
}
}

View File

@@ -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
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class YahooAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="YahooAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="user">The JSON serialized user</param>
/// <param name="userId">Yahoo user ID</param>
/// <param name="accessToken">Yahoo access token</param>
/// <param name="accessTokenSecret">Yahoo access token secret</param>
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;
}
/// <summary>
/// Gets the JSON-serialized user
/// </summary>
/// <remarks>
/// Contains the LinkedIn user obtained from the endpoint http://social.yahooapis.com/v1/user/{guid}/profile/usercard
/// </remarks>
public JObject User { get; private set; }
/// <summary>
/// Gets the Yahoo user ID
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Gets the Yaho0 nickname
/// </summary>
public string NickName { get; private set; }
/// <summary>
/// Gets the Yahoo access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the Yahoo 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; }
private static string TryGetValue(JObject user, string propertyName)
{
JToken value;
return user.TryGetValue(propertyName, out value) ? value.ToString() : null;
}
}
}

View File

@@ -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
{
/// <summary>
/// Default <see cref="IYahooAuthenticationProvider"/> implementation.
/// </summary>
public class YahooAuthenticationProvider : IYahooAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="YahooAuthenticationProvider"/>
/// </summary>
public YahooAuthenticationProvider()
{
OnAuthenticated = context => Task.FromResult<object>(null);
OnReturnEndpoint = context => Task.FromResult<object>(null);
}
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<YahooAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<YahooReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever Yahoo succesfully 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(YahooAuthenticatedContext 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(YahooReturnEndpointContext context)
{
return OnReturnEndpoint(context);
}
}
}

View File

@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.Yahoo
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class YahooReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
/// Initializes a new <see cref="YahooReturnEndpointContext"/>.
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public YahooReturnEndpointContext(
IOwinContext context,
AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@@ -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
{
/// <summary>
/// Extension methods for using <see cref="YahooAuthenticationMiddleware"/>
/// </summary>
public static class YahooAuthenticationExtensions
{
/// <summary>
/// Authenticate users using Yahoo
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="options">Middleware configuration options</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
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;
}
/// <summary>
/// Authenticate users using Yahoo
/// </summary>
/// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
/// <param name="consumerKey">The Yahoo-issued consumer key</param>
/// <param name="consumerSecret">The Yahoo-issued consumer secret</param>
/// <returns>The updated <see cref="IAppBuilder"/></returns>
public static IAppBuilder UseYahooAuthentication(
this IAppBuilder app,
string consumerKey,
string consumerSecret)
{
return UseYahooAuthentication(
app,
new YahooAuthenticationOptions
{
ConsumerKey = consumerKey,
ConsumerSecret = consumerSecret,
});
}
}
}

View File

@@ -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<YahooAuthenticationOptions>
{
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<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
{
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<bool> 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<RequestToken> 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<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 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<AccessToken> 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<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--;
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<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("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<JObject> 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<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--;
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<JObject>();
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);
}
}
}
}

View File

@@ -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
{
/// <summary>
/// OWIN middleware for authenticating users using Yahoo
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "Middleware are not disposable.")]
public class YahooAuthenticationMiddleware : AuthenticationMiddleware<YahooAuthenticationOptions>
{
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
/// <summary>
/// Initializes a <see cref="YahooAuthenticationMiddleware"/>
/// </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 YahooAuthenticationMiddleware(
OwinMiddleware next,
IAppBuilder app,
YahooAuthenticationOptions options)
: base(next, options)
{
_logger = app.CreateLogger<YahooAuthenticationMiddleware>();
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<RequestToken>(
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;
}
/// <summary>
/// Provides the <see cref="AuthenticationHandler"/> object for processing authentication-related requests.
/// </summary>
/// <returns>An <see cref="AuthenticationHandler"/> configured with the <see cref="YahooAuthenticationOptions"/> supplied to the constructor.</returns>
protected override AuthenticationHandler<YahooAuthenticationOptions> 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;
}
}
}

View File

@@ -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
{
/// <summary>
/// Options for the Yahoo authentication middleware.
/// </summary>
public class YahooAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Initializes a new instance of the <see cref="YahooAuthenticationOptions"/> class.
/// </summary>
[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;
}
/// <summary>
/// Gets or sets the consumer key used to communicate with Yahoo.
/// </summary>
/// <value>The consumer key used to communicate with Yahoo.</value>
public string ConsumerKey { get; set; }
/// <summary>
/// Gets or sets the consumer secret used to sign requests to Yahoo.
/// </summary>
/// <value>The consumer secret used to sign requests to Yahoo.</value>
public string ConsumerSecret { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with Yahoo.
/// </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 Yahoo.
/// </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 Yahoo.
/// 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-yahoo".
/// </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="IYahooAuthenticationProvider"/> used to handle authentication events.
/// </summary>
public IYahooAuthenticationProvider Provider { get; set; }
}
}

View File

@@ -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(
// "",
// "");
}
}
}

View File

@@ -1,5 +1,7 @@
/// <reference path="jquery-2.0.3.js" />
/// <autosync enabled="true" />
/// <reference path="modernizr-2.6.2.js" />
/// <autosync enabled="true" />
/// <reference path="bootstrap.js" />
/// <reference path="jquery-2.0.3.js" />
/// <reference path="jquery.validate.js" />
/// <reference path="jquery.validate.unobtrusive.js" />
/// <reference path="modernizr-2.6.2.js" />
/// <reference path="respond.js" />