merge commit

This commit is contained in:
Tommy Parnell
2015-04-19 22:54:56 -04:00
45 changed files with 2096 additions and 95 deletions

View File

@@ -2,7 +2,7 @@
<package >
<metadata>
<id>Owin.Security.Providers</id>
<version>1.15.0</version>
<version>1.17.1</version>
<authors>Jerrie Pelser and contributors</authors>
<owners>Jerrie Pelser</owners>
<licenseUrl>http://opensource.org/licenses/MIT</licenseUrl>
@@ -12,15 +12,17 @@
Adds additional OAuth providers for OWIN to use with ASP.NET
</description>
<summary>
Additional OAuth providers for Katana (OWIN). Includes providers for LinkedIn, Yahoo, Google+, GitHub, Reddit, Instagram, StackExchange, SalesForce, TripIt, Buffer, ArcGIS, Dropbox, Wordpress, Battle.NET, Twitch and Yammer
Also adds generic OpenID 2.0 providers as well as a Steam-specific implementatio
Additional OAuth providers for Katana (OWIN). Includes providers for LinkedIn, Yahoo, Google+, GitHub, Reddit, Instagram, StackExchange, SalesForce, TripIt, Buffer, ArcGIS, Dropbox, Wordpress, Battle.NET, Twitch, Yammer, Flickr and PayPal.
Also adds generic OpenID 2.0 providers as well implementations for Steam and Wargaming.
</summary>
<releaseNotes>
Version 1.15
Version 1.17
Added
- Added Eve Online Provider (Thank you Mariusz Zieliński - https://github.com/mariozski)
- Added SoundCloud Provider
- Added Flickr, Paypal and Wargaming providers
Fixes
- Fixes issue with LinkedIn provider not working due to changes on LinkedIn side
</releaseNotes>
<copyright>Copyright 2013, 2014</copyright>
<tags>owin katana oauth LinkedIn Yahoo Google+ GitHub Reddit Instagram StackExchange SalesForce TripIt Buffer ArcGIS Dropbox Wordpress Battle.NET Yammer OpenID Steam Twitch</tags>

View File

@@ -16,52 +16,57 @@ namespace Owin.Security.Providers.BattleNet
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private readonly string _tokenEndpoint = "https://eu.battle.net/oauth/token";
private readonly string _accountUserIdEndpoint = "https://eu.api.battle.net/account/user/id";
private readonly string _accountUserBattleTagEndpoint = "https://eu.api.battle.net/account/user/battletag";
private readonly string _oauthAuthEndpoint = "https://eu.battle.net/oauth/authorize";
private string tokenEndpoint = "https://eu.battle.net/oauth/token";
private string accountUserIdEndpoint = "https://eu.api.battle.net/account/user/id";
private string accountUserBattleTagEndpoint = "https://eu.api.battle.net/account/user/battletag";
private string oauthAuthEndpoint = "https://eu.battle.net/oauth/authorize";
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
private readonly ILogger logger;
private readonly HttpClient httpClient;
public BattleNetAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
_httpClient = httpClient;
_logger = logger;
this.httpClient = httpClient;
this.logger = logger;
}
protected override Task InitializeCoreAsync()
{
switch (Options.Region)
{
case Region.China:
_tokenEndpoint = "https://cn.battle.net/oauth/token";
_accountUserIdEndpoint = "https://cn.api.battle.net/account/user/id";
_accountUserBattleTagEndpoint = "https://cn.api.battle.net/account/user/battletag";
_oauthAuthEndpoint = "https://cn.battle.net/oauth/authorize";
tokenEndpoint = "https://cn.battle.net/oauth/token";
accountUserIdEndpoint = "https://cn.api.battle.net/account/user/id";
accountUserBattleTagEndpoint = "https://cn.api.battle.net/account/user/battletag";
oauthAuthEndpoint = "https://cn.battle.net/oauth/authorize";
break;
case Region.Korea:
_tokenEndpoint = "https://kr.battle.net/oauth/token";
_accountUserIdEndpoint = "https://kr.api.battle.net/account/user/id";
_accountUserBattleTagEndpoint = "https://kr.api.battle.net/account/user/battletag";
_oauthAuthEndpoint = "https://kr.battle.net/oauth/authorize";
tokenEndpoint = "https://kr.battle.net/oauth/token";
accountUserIdEndpoint = "https://kr.api.battle.net/account/user/id";
accountUserBattleTagEndpoint = "https://kr.api.battle.net/account/user/battletag";
oauthAuthEndpoint = "https://kr.battle.net/oauth/authorize";
break;
case Region.Taiwan:
_tokenEndpoint = "https://tw.battle.net/oauth/token";
_accountUserIdEndpoint = "https://tw.api.battle.net/account/user/id";
_accountUserBattleTagEndpoint = "https://tw.api.battle.net/account/user/battletag";
_oauthAuthEndpoint = "https://tw.battle.net/oauth/authorize";
tokenEndpoint = "https://tw.battle.net/oauth/token";
accountUserIdEndpoint = "https://tw.api.battle.net/account/user/id";
accountUserBattleTagEndpoint = "https://tw.api.battle.net/account/user/battletag";
oauthAuthEndpoint = "https://tw.battle.net/oauth/authorize";
break;
case Region.Europe:
_tokenEndpoint = "https://eu.battle.net/oauth/token";
_accountUserIdEndpoint = "https://eu.api.battle.net/account/user/id";
_accountUserBattleTagEndpoint = "https://eu.api.battle.net/account/user/battletag";
_oauthAuthEndpoint = "https://eu.battle.net/oauth/authorize";
tokenEndpoint = "https://eu.battle.net/oauth/token";
accountUserIdEndpoint = "https://eu.api.battle.net/account/user/id";
accountUserBattleTagEndpoint = "https://eu.api.battle.net/account/user/battletag";
oauthAuthEndpoint = "https://eu.battle.net/oauth/authorize";
break;
default:
_tokenEndpoint = "https://us.battle.net/oauth/token";
_accountUserIdEndpoint = "https://us.api.battle.net/account/user/id";
_accountUserBattleTagEndpoint = "https://us.api.battle.net/account/user/battletag";
_oauthAuthEndpoint = "https://us.battle.net/oauth/authorize";
tokenEndpoint = "https://us.battle.net/oauth/token";
accountUserIdEndpoint = "https://us.api.battle.net/account/user/id";
accountUserBattleTagEndpoint = "https://us.api.battle.net/account/user/battletag";
oauthAuthEndpoint = "https://us.battle.net/oauth/authorize";
break;
}
return Task.FromResult(true);
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
@@ -92,7 +97,7 @@ namespace Owin.Security.Providers.BattleNet
}
// OAuth2 10.12 CSRF
if (!ValidateCorrelationId(properties, _logger))
if (!ValidateCorrelationId(properties, logger))
{
return new AuthenticationTicket(null, properties);
}
@@ -115,7 +120,7 @@ namespace Owin.Security.Providers.BattleNet
};
// Request the token
var tokenResponse = await _httpClient.PostAsync(_tokenEndpoint, new FormUrlEncodedContent(body));
var tokenResponse = await httpClient.PostAsync(tokenEndpoint, new FormUrlEncodedContent(body));
tokenResponse.EnsureSuccessStatusCode();
var text = await tokenResponse.Content.ReadAsStringAsync();
@@ -125,13 +130,13 @@ namespace Owin.Security.Providers.BattleNet
var expires = (string)response.expires_in;
// Get WoW User Id
var graphResponse = await _httpClient.GetAsync(_accountUserIdEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);
var graphResponse = await httpClient.GetAsync(accountUserIdEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
var userId = JObject.Parse(text);
// Get WoW BattleTag
graphResponse = await _httpClient.GetAsync(_accountUserBattleTagEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);
graphResponse = await httpClient.GetAsync(accountUserBattleTagEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken), Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
text = await graphResponse.Content.ReadAsStringAsync();
var battleTag = JObject.Parse(text);
@@ -166,7 +171,7 @@ namespace Owin.Security.Providers.BattleNet
}
catch (Exception ex)
{
_logger.WriteError(ex.Message);
logger.WriteError(ex.Message);
}
return new AuthenticationTicket(null, properties);
}
@@ -212,7 +217,7 @@ namespace Owin.Security.Providers.BattleNet
var state = Options.StateDataFormat.Protect(properties);
var authorizationEndpoint =
_oauthAuthEndpoint +
oauthAuthEndpoint +
"?response_type=code" +
"&client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
@@ -244,7 +249,7 @@ namespace Owin.Security.Providers.BattleNet
var ticket = await AuthenticateAsync();
if (ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}

View File

@@ -13,8 +13,8 @@ namespace Owin.Security.Providers.BattleNet
{
public class BattleNetAuthenticationMiddleware : AuthenticationMiddleware<BattleNetAuthenticationOptions>
{
private readonly HttpClient _httpClient;
private readonly ILogger _logger;
private readonly HttpClient httpClient;
private readonly ILogger logger;
public BattleNetAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, BattleNetAuthenticationOptions options)
: base(next, options)
@@ -26,7 +26,7 @@ namespace Owin.Security.Providers.BattleNet
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Resources.Exception_OptionMustBeProvided, "ClientSecret"));
_logger = app.CreateLogger<BattleNetAuthenticationMiddleware>();
logger = app.CreateLogger<BattleNetAuthenticationMiddleware>();
if (Options.Provider == null)
Options.Provider = new BattleNetAuthenticationProvider();
@@ -42,7 +42,7 @@ namespace Owin.Security.Providers.BattleNet
if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
_httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
{
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024 * 1024 * 10
@@ -59,7 +59,7 @@ namespace Owin.Security.Providers.BattleNet
/// </returns>
protected override AuthenticationHandler<BattleNetAuthenticationOptions> CreateHandler()
{
return new BattleNetAuthenticationHandler(_httpClient, _logger);
return new BattleNetAuthenticationHandler(httpClient, logger);
}
private static HttpMessageHandler ResolveHttpMessageHandler(BattleNetAuthenticationOptions options)

View File

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

View File

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

View File

@@ -0,0 +1,367 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
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.Flickr.Messages;
namespace Owin.Security.Providers.Flickr
{
internal class FlickrAuthenticationHandler : AuthenticationHandler<FlickrAuthenticationOptions>
{
private static readonly DateTime Epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const string StateCookie = "__FlickrState";
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private const string RequestTokenEndpoint = "https://www.flickr.com/services/oauth/request_token";
private const string AuthenticationEndpoint = "https://www.flickr.com/services/oauth/authorize?oauth_token=";
private const string AccessTokenEndpoint = "https://www.flickr.com/services/oauth/access_token";
private readonly HttpClient httpClient;
private readonly ILogger logger;
public FlickrAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
this.httpClient = httpClient;
this.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.AppKey, Options.AppSecret, requestToken, oauthVerifier);
var context = new FlickrAuthenticatedContext(Context, accessToken);
context.Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,
ClaimsIdentity.DefaultRoleClaimType);
if (!String.IsNullOrEmpty(context.UserId))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId,
XmlSchemaString, Options.AuthenticationType));
}
if(!String.IsNullOrEmpty(context.UserName))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName,
XmlSchemaString, Options.AuthenticationType));
}
if (!String.IsNullOrEmpty(context.FullName))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.FullName,
XmlSchemaString, Options.AuthenticationType));
}
context.Properties = requestToken.Properties;
Response.Cookies.Delete(StateCookie);
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch (Exception ex)
{
logger.WriteError("Authentication failed", ex);
return new AuthenticationTicket(null, properties);
}
}
protected override async Task ApplyResponseChallengeAsync()
{
if (Response.StatusCode != 401)
{
return;
}
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.AppKey, Options.AppSecret, callBackUrl, extra);
if (requestToken.CallbackConfirmed)
{
string FlickrAuthenticationEndpoint = AuthenticationEndpoint + requestToken.Token + "&perms=" + Options.Scope;
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", FlickrAuthenticationEndpoint);
}
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 FlickrReturnEndpointContext(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 AppKey, string AppSecret, string callBackUri, AuthenticationProperties properties)
{
logger.WriteVerbose("ObtainRequestToken");
string nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_callback", callBackUri },
{ "oauth_consumer_key", AppKey },
{ "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(AppSecret, 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 AppKey, string AppSecret, RequestToken token, string verifier)
{
logger.WriteVerbose("ObtainAccessToken");
string nonce = Guid.NewGuid().ToString("N");
var authorizationParts = new SortedDictionary<string, string>
{
{ "oauth_consumer_key", AppKey },
{ "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(AppSecret, 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["user_nsid"]),
UserName = Uri.UnescapeDataString(responseParameters["username"]),
FullName = Uri.UnescapeDataString(responseParameters["fullname"]),
};
}
private static string GenerateTimeStamp()
{
TimeSpan secondsSinceUnixEpocStart = DateTime.UtcNow - Epoch;
return Convert.ToInt64(secondsSinceUnixEpocStart.TotalSeconds).ToString(CultureInfo.InvariantCulture);
}
private static string ComputeSignature(string AppSecret, string tokenSecret, string signatureData)
{
using (var algorithm = new HMACSHA1())
{
algorithm.Key = Encoding.ASCII.GetBytes(
string.Format(CultureInfo.InvariantCulture,
"{0}&{1}",
Uri.EscapeDataString(AppSecret),
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,90 @@
using System;
using System.Globalization;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.Properties;
using Owin.Security.Providers.Flickr.Messages;
using Microsoft.Owin.Security.DataHandler.Encoder;
namespace Owin.Security.Providers.Flickr
{
public class FlickrAuthenticationMiddleware : AuthenticationMiddleware<FlickrAuthenticationOptions>
{
private readonly HttpClient httpClient;
private readonly ILogger logger;
public FlickrAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
FlickrAuthenticationOptions options)
: base(next, options)
{
if (String.IsNullOrWhiteSpace(Options.AppKey))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Resources.Exception_OptionMustBeProvided, "AppKey"));
if (String.IsNullOrWhiteSpace(Options.AppSecret))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Resources.Exception_OptionMustBeProvided, "AppSecret"));
logger = app.CreateLogger<FlickrAuthenticationMiddleware>();
if (Options.Provider == null)
Options.Provider = new FlickrAuthenticationProvider();
if (Options.StateDataFormat == null)
{
IDataProtector dataProtector = app.CreateDataProtector(
typeof(FlickrAuthenticationMiddleware).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))
{
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024*1024*10
};
}
/// <summary>
/// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing
/// authentication-related requests.
/// </summary>
/// <returns>
/// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the
/// <see cref="T:Owin.Security.Providers.Flickr.FlickrAuthenticationOptions" /> supplied to the constructor.
/// </returns>
protected override AuthenticationHandler<FlickrAuthenticationOptions> CreateHandler()
{
return new FlickrAuthenticationHandler(httpClient, logger);
}
private HttpMessageHandler ResolveHttpMessageHandler(FlickrAuthenticationOptions options)
{
HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler();
// If they provided a validator, apply it or fail.
if (options.BackchannelCertificateValidator != null)
{
// Set the cert validate callback
var webRequestHandler = handler as WebRequestHandler;
if (webRequestHandler == null)
{
throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch);
}
webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
}
return handler;
}
}
}

View File

@@ -0,0 +1,99 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Owin.Security.Providers.Flickr.Messages;
namespace Owin.Security.Providers.Flickr {
public class FlickrAuthenticationOptions : AuthenticationOptions
{
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to Flickr.
/// </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 Flickr.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with Flickr.
/// </summary>
/// <value>
/// The back channel timeout in milliseconds.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// Default value is "/signin-Flickr".
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string Caption
{
get { return Description.Caption; }
set { Description.Caption = value; }
}
/// <summary>
/// Gets or sets the Flickr supplied App Key
/// </summary>
public string AppKey { get; set; }
/// <summary>
/// Gets or sets the Flickr supplied App Secret
/// </summary>
public string AppSecret { get; set; }
/// <summary>
/// Gets or sets the <see cref="IFlickrAuthenticationProvider" /> used in the authentication events
/// </summary>
public IFlickrAuthenticationProvider Provider { get; set; }
/// <summary>
/// A list of permissions to request.
/// </summary>
public string Scope { 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>
/// Initializes a new <see cref="FlickrAuthenticationOptions" />
/// </summary>
public FlickrAuthenticationOptions()
: base("Flickr")
{
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-flickr");
AuthenticationMode = AuthenticationMode.Passive;
Scope = "read";
BackchannelTimeout = TimeSpan.FromSeconds(60);
}
}
}

View File

@@ -0,0 +1,25 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace Owin.Security.Providers.Flickr.Messages
{
/// <summary>
/// Flickr access token
/// </summary>
public class AccessToken : RequestToken
{
/// <summary>
/// Gets or sets the Flickr User ID
/// </summary>
public string UserId { get; set; }
/// <summary>
/// Gets or sets the Flickr User Name
/// </summary>
public string UserName { get; set; }
/// <summary>
/// Gets or sets the Flickr User Full Name
/// </summary>
public string FullName { 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.Flickr.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.Flickr.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.Flickr.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,66 @@
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
using Newtonsoft.Json.Linq;
using Owin.Security.Providers.Flickr.Messages;
namespace Owin.Security.Providers.Flickr {
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class FlickrAuthenticatedContext : BaseContext {
/// <summary>
/// Initializes a <see cref="FlickrAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="accessToken">Flick access toke</param>
public FlickrAuthenticatedContext(IOwinContext context, AccessToken accessToken)
: base(context)
{
FullName = accessToken.FullName;
UserId = accessToken.UserId;
UserName = accessToken.UserName;
AccessToken = accessToken.Token;
AccessTokenSecret = accessToken.TokenSecret;
}
/// <summary>
/// Gets user full name
/// </summary>
public string FullName { get; private set; }
/// <summary>
/// Gets the Flickr user ID
/// </summary>
public string UserId { get; private set; }
/// <summary>
/// Gets the Flickr username
/// </summary>
public string UserName { get; private set; }
/// <summary>
/// Gets the Flickr access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the Flickr 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,45 @@
using System;
using System.Threading.Tasks;
namespace Owin.Security.Providers.Flickr {
/// <summary>
/// Default <see cref="IFlickrAuthenticationProvider"/> implementation.
/// </summary>
public class FlickrAuthenticationProvider : IFlickrAuthenticationProvider {
/// <summary>
/// Initializes a <see cref="FlickrAuthenticationProvider"/>
/// </summary>
public FlickrAuthenticationProvider() {
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<FlickrAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<FlickrReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever Flickr 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(FlickrAuthenticatedContext 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(FlickrReturnEndpointContext context) {
return OnReturnEndpoint(context);
}
}
}

View File

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

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Owin.Security.Providers.Flickr {
/// <summary>
/// Specifies callback methods which the <see cref="FlickrAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IFlickrAuthenticationProvider {
/// <summary>
/// Invoked whenever Flickr 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(FlickrAuthenticatedContext 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(FlickrReturnEndpointContext context);
}
}

View File

@@ -20,6 +20,8 @@ namespace Owin.Security.Providers.Foursquare
private const string GraphApiEndpoint = "https://api.foursquare.com/v2/users/self";
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private static readonly DateTime VersionDate = new DateTime(2015, 3, 19);
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
@@ -103,7 +105,7 @@ namespace Owin.Security.Providers.Foursquare
return new AuthenticationTicket(null, properties);
}
var graphResponse = await this._httpClient.GetAsync(GraphApiEndpoint + "?oauth_token=" + Uri.EscapeDataString(accessToken) + "&m=foursquare&v=" + DateTime.Today.ToString("yyyyyMMdd"), this.Request.CallCancelled);
var graphResponse = await this._httpClient.GetAsync(GraphApiEndpoint + "?oauth_token=" + Uri.EscapeDataString(accessToken) + "&m=foursquare&v=" + VersionDate.ToString("yyyyyMMdd"), this.Request.CallCancelled);
graphResponse.EnsureSuccessStatusCode();
var accountstring = await graphResponse.Content.ReadAsStringAsync();
@@ -174,17 +176,13 @@ namespace Owin.Security.Providers.Foursquare
// OAuth2 10.12 CSRF
this.GenerateCorrelationId(extra);
// OAuth2 3.3 space separated
var scope = string.Join(" ", this.Options.Scope);
var state = this.Options.StateDataFormat.Protect(extra);
var authorizationEndpoint = AuthorizationEndpoint +
"?client_id=" + Uri.EscapeDataString(this.Options.ClientId) +
"&response_type=code" +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&state=" + Uri.EscapeDataString(state) +
"&scope=" + Uri.EscapeDataString(scope);
"&state=" + Uri.EscapeDataString(state);
this.Response.Redirect(authorizationEndpoint);
}

View File

@@ -51,6 +51,14 @@ namespace Owin.Security.Providers.Foursquare
this._httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
}
/// <summary>
/// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing
/// authentication-related requests.
/// </summary>
/// <returns>
/// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the
/// <see cref="T:Owin.Security.Providers.Foursquare.FoursquareAuthenticationOptions" /> supplied to the constructor.
/// </returns>
protected override AuthenticationHandler<FoursquareAuthenticationOptions> CreateHandler()
{
return new FoursquareAuthenticationHandler(this._httpClient, this._logger);

View File

@@ -18,7 +18,6 @@ namespace Owin.Security.Providers.Foursquare
this.CallbackPath = "/signin-foursquare";
this.AuthenticationMode = AuthenticationMode.Passive;
this.BackchannelTimeout = TimeSpan.FromSeconds(60);
this.Scope = new List<String>();
}
/// <summary>
@@ -82,11 +81,6 @@ namespace Owin.Security.Providers.Foursquare
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
/// <summary>
/// A list of permissions to request.
/// </summary>
public IList<string> Scope { get; private set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>

View File

@@ -7,8 +7,17 @@ using Newtonsoft.Json.Linq;
namespace Owin.Security.Providers.Foursquare.Provider
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class FoursquareAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="FoursquareAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="user">The JSON-serialized user</param>
/// <param name="accessToken">Foursquare Access token</param>
public FoursquareAuthenticatedContext(IOwinContext context, JObject user, string accessToken)
: base(context)
{
@@ -32,15 +41,15 @@ namespace Owin.Security.Providers.Foursquare.Provider
this.LastName = TryGetValue(user, "lastName");
this.Name = this.FirstName + " " + this.LastName;
this.Gender = TryGetValue(user, "gender");
this.Photo = TryGetValue(user, "photo");
this.Photo = (JObject)user["photo"];
this.Friends = TryGetValue(user, "friends");
this.HomeCity = TryGetValue(user, "homeCity");
this.Bio = TryGetValue(user, "bio");
this.Contact = TryGetValue(user, "contact");
this.Phone = TryGetValue(JObject.Parse(this.Contact), "phone");
this.Email = TryGetValue(JObject.Parse(this.Contact), "email");
this.Twitter = TryGetValue(JObject.Parse(this.Contact), "twitter");
this.Facebook = TryGetValue(JObject.Parse(this.Contact), "facebook");
this.Contact = (JObject)user["contact"];
this.Phone = TryGetValue(Contact, "phone");
this.Email = TryGetValue(Contact, "email");
this.Twitter = TryGetValue(Contact, "twitter");
this.Facebook = TryGetValue(Contact, "facebook");
this.Badges = TryGetValue(user, "badges");
this.Mayorships = TryGetValue(user, "mayorships");
this.Checkins = TryGetValue(user, "checkins");
@@ -49,29 +58,104 @@ namespace Owin.Security.Providers.Foursquare.Provider
this.Link = "https://foursquare.com/user/" + this.Id;
}
/// <summary>
/// Gets the JSON-serialized user
/// </summary>
/// <remarks>
/// Contains the Foursquare user obtained from the User Info endpoint https://api.foursquare.com/v2/users/self
/// </remarks>
public JObject User { get; private set; }
/// <summary>
/// Gets the Foursquare access token
/// </summary>
public string AccessToken { get; private set; }
/// <summary>
/// Gets the Foursquare user ID
/// </summary>
public string Id { get; private set; }
/// <summary>
/// Gets the user's first name
/// </summary>
public string FirstName { get; private set; }
/// <summary>
/// Gets the user's last name
/// </summary>
public string LastName { get; private set; }
/// <summary>
/// Gets the user's full name
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the user's gender
/// </summary>
public string Gender { get; private set; }
public string Photo { get; private set; }
/// <summary>
/// Gets the user's photo
/// </summary>
public JObject Photo { get; private set; }
/// <summary>
/// Gets the user's friends
/// </summary>
public string Friends { get; private set; }
/// <summary>
/// Gets the user's home city
/// </summary>
public string HomeCity { get; private set; }
/// <summary>
/// Gets the user's biography
/// </summary>
public string Bio { get; private set; }
public string Contact { get; private set; }
/// <summary>
/// Gets the user's contact
/// </summary>
public JObject Contact { get; private set; }
/// <summary>
/// Gets the user's phone
/// </summary>
public string Phone { get; private set; }
/// <summary>
/// Gets the user's email
/// </summary>
public string Email { get; private set; }
/// <summary>
/// Gets the user's Twitter handle
/// </summary>
public string Twitter { get; private set; }
/// <summary>
/// Gets the user's Facebook id
/// </summary>
public string Facebook { get; private set; }
/// <summary>
/// Gets the user's badges
/// </summary>
public string Badges { get; private set; }
/// <summary>
/// Gets the user's mayorships
/// </summary>
public string Mayorships { get; private set; }
/// <summary>
/// Gets the user's checkins
/// </summary>
public string Checkins { get; private set; }
/// <summary>
/// Gets the user's photos
/// </summary>
public string Photos { get; private set; }
/// <summary>
/// Gets the user's scores
/// </summary>
public string Scores { get; private set; }
/// <summary>
/// Gets the user's link
/// </summary>
public string Link { 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)

View File

@@ -3,23 +3,45 @@ using System.Threading.Tasks;
namespace Owin.Security.Providers.Foursquare.Provider
{
/// <summary>
/// Default <see cref="IFoursquareAuthenticationProvider"/> implementation.
/// </summary>
public class FoursquareAuthenticationProvider : IFoursquareAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="FoursquareAuthenticationProvider"/>
/// </summary>
public FoursquareAuthenticationProvider()
{
this.OnAuthenticated = context => Task.FromResult<object>(null);
this.OnReturnEndpoint = context => Task.FromResult<object>(null);
}
/// <summary>
/// Gets or sets the function that is invoked when the Authenticated method is invoked.
/// </summary>
public Func<FoursquareAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<FoursquareReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever Foursquare 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(FoursquareAuthenticatedContext context)
{
return this.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(FoursquareReturnEndpointContext context)
{
return this.OnReturnEndpoint(context);

View File

@@ -4,6 +4,9 @@ using Microsoft.Owin.Security.Provider;
namespace Owin.Security.Providers.Foursquare.Provider
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class FoursquareReturnEndpointContext : ReturnEndpointContext
{
/// <summary>

View File

@@ -2,10 +2,23 @@
namespace Owin.Security.Providers.Foursquare.Provider
{
/// <summary>
/// Specifies callback methods which the <see cref="FoursquareAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IFoursquareAuthenticationProvider
{
/// <summary>
/// Invoked whenever Foursquare 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(FoursquareAuthenticatedContext 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(FoursquareReturnEndpointContext context);
}
}

View File

@@ -48,6 +48,9 @@ namespace Owin.Security.Providers.LinkedIn
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024*1024*10
};
// Fix for LinkedIn Expect: 100- continue issue
httpClient.DefaultRequestHeaders.ExpectContinue = false;
}
/// <summary>

View File

@@ -112,6 +112,19 @@
<Compile Include="EveOnline\Provider\EveOnlineAuthenticationProvider.cs" />
<Compile Include="EveOnline\Provider\EveOnlineReturnEndpointContext.cs" />
<Compile Include="EveOnline\Provider\IEveOnlineAuthenticationProvider.cs" />
<Compile Include="Flickr\Constants.cs" />
<Compile Include="Flickr\FlickrAuthenticationOptions.cs" />
<Compile Include="Flickr\FlickrAuthenticationExtensions.cs" />
<Compile Include="Flickr\FlickrAuthenticationHandler.cs" />
<Compile Include="Flickr\FlickrAuthenticationMiddleware.cs" />
<Compile Include="Flickr\Messages\AccessToken.cs" />
<Compile Include="Flickr\Messages\RequestToken.cs" />
<Compile Include="Flickr\Messages\RequestTokenSerializer.cs" />
<Compile Include="Flickr\Messages\Serializers.cs" />
<Compile Include="Flickr\Provider\FlickrAuthenticatedContext.cs" />
<Compile Include="Flickr\Provider\FlickrAuthenticationProvider.cs" />
<Compile Include="Flickr\Provider\IFlickrAuthenticationProvider.cs" />
<Compile Include="Flickr\Provider\FlickrReturnEndpointContext.cs" />
<Compile Include="Foursquare\Constants.cs" />
<Compile Include="Foursquare\FoursquareAuthenticationExtensions.cs" />
<Compile Include="Foursquare\FoursquareAuthenticationHandler.cs" />
@@ -182,6 +195,15 @@
<Compile Include="OpenID\Provider\OpenIDAuthenticatedContext.cs" />
<Compile Include="OpenID\Provider\OpenIDAuthenticationProvider.cs" />
<Compile Include="OpenID\Provider\OpenIDReturnEndpointContext.cs" />
<Compile Include="PayPal\Constants.cs" />
<Compile Include="PayPal\PayPalAuthenticationExtensions.cs" />
<Compile Include="PayPal\PayPalAuthenticationHandler.cs" />
<Compile Include="PayPal\PayPalAuthenticationMiddleware.cs" />
<Compile Include="PayPal\PayPalAuthenticationOptions.cs" />
<Compile Include="PayPal\Provider\IPayPalAuthenticationProvider.cs" />
<Compile Include="PayPal\Provider\PayPalAuthenticatedContext.cs" />
<Compile Include="PayPal\Provider\PayPalAuthenticationProvider.cs" />
<Compile Include="PayPal\Provider\PayPalReturnEndpointContext.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
@@ -261,6 +283,11 @@
<Compile Include="Untappd\UntappdAuthenticationHandler.cs" />
<Compile Include="Untappd\UntappdAuthenticationMiddleware.cs" />
<Compile Include="Untappd\UntappdAuthenticationOptions.cs" />
<Compile Include="Wargaming\Constants.cs" />
<Compile Include="Wargaming\WargamingAccountAuthenticationExtensions.cs" />
<Compile Include="Wargaming\WargamingAuthenticationHandler.cs" />
<Compile Include="Wargaming\WargamingAuthenticationOptions.cs" />
<Compile Include="Wargaming\WargamingAuthenticationMiddleware.cs" />
<Compile Include="WordPress\WordPressAuthenticationExtensions.cs" />
<Compile Include="WordPress\WordPressAuthenticationHandler.cs" />
<Compile Include="WordPress\WordPressAuthenticationMiddleware.cs" />

View File

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

View File

@@ -0,0 +1,29 @@
using System;
namespace Owin.Security.Providers.PayPal
{
public static class PayPalAuthenticationExtensions
{
public static IAppBuilder UsePayPalAuthentication(this IAppBuilder app,
PayPalAuthenticationOptions options)
{
if (app == null)
throw new ArgumentNullException("app");
if (options == null)
throw new ArgumentNullException("options");
app.Use(typeof(PayPalAuthenticationMiddleware), app, options);
return app;
}
public static IAppBuilder UsePayPalAuthentication(this IAppBuilder app, string clientId, string clientSecret, bool isSandbox=false)
{
return app.UsePayPalAuthentication(new PayPalAuthenticationOptions(isSandbox)
{
ClientId = clientId,
ClientSecret = clientSecret
});
}
}
}

View File

@@ -0,0 +1,238 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Owin;
using Microsoft.Owin.Infrastructure;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Infrastructure;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
namespace Owin.Security.Providers.PayPal
{
public class PayPalAuthenticationHandler : AuthenticationHandler<PayPalAuthenticationOptions>
{
private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
private readonly ILogger _logger;
private readonly HttpClient _httpClient;
public PayPalAuthenticationHandler(HttpClient httpClient, ILogger logger)
{
this._httpClient = httpClient;
this._logger = logger;
}
protected override async Task<AuthenticationTicket> AuthenticateCoreAsync()
{
AuthenticationProperties properties = null;
string error = "Unknown";
try
{
string code = null;
string state = null;
IReadableStringCollection query = Request.Query;
IList<string> values = query.GetValues("code");
if(values != null && values.Count == 1)
{
code = values[0];
}
values = query.GetValues("error");
if(values != null && values.Count == 1)
{
error = values[0];
}
values = query.GetValues("state");
if(values != null && values.Count == 1)
{
state = values[0];
}
properties = Options.StateDataFormat.Unprotect(state);
if(properties == null)
{
return null;
}
// OAuth2 10.12 CSRF
if(!ValidateCorrelationId(properties, _logger))
{
return new AuthenticationTicket(null, properties);
}
string requestPrefix = Request.Scheme + "://" + Request.Host;
string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath;
// Request the token
var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint);
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Options.ClientId, Options.ClientSecret))));
requestMessage.Content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>>{
new KeyValuePair<string, string>("grant_type", "authorization_code"),
new KeyValuePair<string, string>("code", code),
new KeyValuePair<string, string>("redirect_uri", redirectUri),
});
var tokenResponse = await _httpClient.SendAsync(requestMessage);
tokenResponse.EnsureSuccessStatusCode();
var text = await tokenResponse.Content.ReadAsStringAsync();
// Deserializes the token response
var response = JsonConvert.DeserializeObject<dynamic>(text);
var accessToken = (string)response.access_token;
var refreshToken = (string)response.refresh_token;
// Get the PayPal user
var userRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserInfoEndpoint);
userRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
userRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var userResponse = await _httpClient.SendAsync(userRequest, Request.CallCancelled);
userResponse.EnsureSuccessStatusCode();
text = await userResponse.Content.ReadAsStringAsync();
var user = JObject.Parse(text);
var context = new PayPalAuthenticatedContext(Context, user, accessToken, refreshToken)
{
Identity = new ClaimsIdentity(Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType)
};
if(!string.IsNullOrEmpty(context.Id))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType));
}
if(!string.IsNullOrEmpty(context.Email))
{
context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email, XmlSchemaString, Options.AuthenticationType));
}
if(!string.IsNullOrEmpty(context.Name))
{
context.Identity.AddClaim(new Claim("urn:paypal:name", context.Name, XmlSchemaString, Options.AuthenticationType));
}
context.Properties = properties;
await Options.Provider.Authenticated(context);
return new AuthenticationTicket(context.Identity, context.Properties);
}
catch(Exception ex)
{
_logger.WriteError(ex.Message + " : " + error);
}
return new AuthenticationTicket(null, properties);
}
protected override Task ApplyResponseChallengeAsync()
{
if(Response.StatusCode != 401)
{
return Task.FromResult<object>(null);
}
AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode);
if(challenge != null)
{
string baseUri =
Request.Scheme +
Uri.SchemeDelimiter +
Request.Host +
Request.PathBase;
string currentUri =
baseUri +
Request.Path +
Request.QueryString;
string redirectUri =
baseUri +
Options.CallbackPath;
AuthenticationProperties properties = challenge.Properties;
if(string.IsNullOrEmpty(properties.RedirectUri))
{
properties.RedirectUri = currentUri;
}
// OAuth2 10.12 CSRF
GenerateCorrelationId(properties);
// comma separated
string scope = string.Join(" ", Options.Scope);
string state = Options.StateDataFormat.Protect(properties);
string authorizationEndpoint =
Options.Endpoints.AuthorizationEndpoint +
"?client_id=" + Uri.EscapeDataString(Options.ClientId) +
"&redirect_uri=" + Uri.EscapeDataString(redirectUri) +
"&scope=" + Uri.EscapeDataString(scope) +
"&response_type=code" +
"&state=" + Uri.EscapeDataString(state);
Response.Redirect(authorizationEndpoint);
}
return Task.FromResult<object>(null);
}
public override async Task<bool> InvokeAsync()
{
return await InvokeReplyPathAsync();
}
private async Task<bool> InvokeReplyPathAsync()
{
if(Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path)
{
AuthenticationTicket ticket = await AuthenticateAsync();
if(ticket == null)
{
_logger.WriteWarning("Invalid return state, unable to redirect.");
Response.StatusCode = 500;
return true;
}
var context = new PayPalReturnEndpointContext(Context, ticket)
{
SignInAsAuthenticationType = Options.SignInAsAuthenticationType,
RedirectUri = ticket.Properties.RedirectUri
};
await Options.Provider.ReturnEndpoint(context);
if(context.SignInAsAuthenticationType != null &&
context.Identity != null)
{
ClaimsIdentity grantIdentity = context.Identity;
if(!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal))
{
grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType);
}
Context.Authentication.SignIn(context.Properties, grantIdentity);
}
if(!context.IsRequestCompleted && context.RedirectUri != null)
{
string redirectUri = context.RedirectUri;
if(context.Identity == null)
{
// add a redirect hint that sign-in failed in some way
redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied");
}
Response.Redirect(redirectUri);
context.RequestCompleted();
}
return context.IsRequestCompleted;
}
return false;
}
}
}

View File

@@ -0,0 +1,87 @@
using System;
using System.Globalization;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.Properties;
namespace Owin.Security.Providers.PayPal
{
public class PayPalAuthenticationMiddleware : AuthenticationMiddleware<PayPalAuthenticationOptions>
{
private readonly HttpClient httpClient;
private readonly ILogger logger;
public PayPalAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
PayPalAuthenticationOptions options)
: base(next, options)
{
if (String.IsNullOrWhiteSpace(Options.ClientId))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Resources.Exception_OptionMustBeProvided, "ClientId"));
if (String.IsNullOrWhiteSpace(Options.ClientSecret))
throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
Resources.Exception_OptionMustBeProvided, "ClientSecret"));
logger = app.CreateLogger<PayPalAuthenticationMiddleware>();
if (Options.Provider == null)
Options.Provider = new PayPalAuthenticationProvider();
if (Options.StateDataFormat == null)
{
IDataProtector dataProtector = app.CreateDataProtector(
typeof (PayPalAuthenticationMiddleware).FullName,
Options.AuthenticationType, "v1");
Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
}
if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
{
Timeout = Options.BackchannelTimeout,
MaxResponseContentBufferSize = 1024*1024*10,
};
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin PayPal middleware");
httpClient.DefaultRequestHeaders.ExpectContinue = false;
}
/// <summary>
/// Provides the <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> object for processing
/// authentication-related requests.
/// </summary>
/// <returns>
/// An <see cref="T:Microsoft.Owin.Security.Infrastructure.AuthenticationHandler" /> configured with the
/// <see cref="T:Owin.Security.Providers.PayPal.PayPalAuthenticationOptions" /> supplied to the constructor.
/// </returns>
protected override AuthenticationHandler<PayPalAuthenticationOptions> CreateHandler()
{
return new PayPalAuthenticationHandler(httpClient, logger);
}
private HttpMessageHandler ResolveHttpMessageHandler(PayPalAuthenticationOptions options)
{
HttpMessageHandler handler = options.BackchannelHttpHandler ?? new WebRequestHandler();
// If they provided a validator, apply it or fail.
if (options.BackchannelCertificateValidator != null)
{
// Set the cert validate callback
var webRequestHandler = handler as WebRequestHandler;
if (webRequestHandler == null)
{
throw new InvalidOperationException(Resources.Exception_ValidatorHandlerMismatch);
}
webRequestHandler.ServerCertificateValidationCallback = options.BackchannelCertificateValidator.Validate;
}
return handler;
}
}
}

View File

@@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
namespace Owin.Security.Providers.PayPal
{
public class PayPalAuthenticationOptions : AuthenticationOptions
{
public class PayPalAuthenticationEndpoints
{
/// <summary>
/// Endpoint which is used to redirect users to request PayPal access
/// </summary>
/// <remarks>
/// Defaults to https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize
/// </remarks>
public string AuthorizationEndpoint { get; set; }
/// <summary>
/// Endpoint which is used to exchange code for access token
/// </summary>
/// <remarks>
/// Defaults to https://api.paypal.com/v1/identity/openidconnect/tokenservice
/// </remarks>
public string TokenEndpoint { get; set; }
/// <summary>
/// Endpoint which is used to obtain user information after authentication
/// </summary>
/// <remarks>
/// Defaults to https://api.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid
/// </remarks>
public string UserInfoEndpoint { get; set; }
}
private const string AuthorizationEndPoint = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize";
private const string TokenEndpoint = "https://api.paypal.com/v1/identity/openidconnect/tokenservice";
private const string UserInfoEndpoint = "https://api.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid";
private const string SandboxAuthorizationEndPoint = "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize";
private const string SandboxTokenEndpoint = "https://api.sandbox.paypal.com/v1/identity/openidconnect/tokenservice";
private const string SandboxUserInfoEndpoint = "https://api.sandbox.paypal.com/v1/identity/openidconnect/userinfo/?schema=openid";
/// <summary>
/// Gets or sets the a pinned certificate validator to use to validate the endpoints used
/// in back channel communications belong to PayPal.
/// </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 PayPal.
/// This cannot be set at the same time as BackchannelCertificateValidator unless the value
/// can be downcast to a WebRequestHandler.
/// </summary>
public HttpMessageHandler BackchannelHttpHandler { get; set; }
/// <summary>
/// Gets or sets timeout value in milliseconds for back channel communications with PayPal.
/// </summary>
/// <value>
/// The back channel timeout in milliseconds.
/// </value>
public TimeSpan BackchannelTimeout { get; set; }
/// <summary>
/// The request path within the application's base path where the user-agent will be returned.
/// The middleware will process this request when it arrives.
/// Default value is "/signin-github".
/// </summary>
public PathString CallbackPath { get; set; }
/// <summary>
/// Get or sets the text that the user can display on a sign in user interface.
/// </summary>
public string Caption
{
get { return Description.Caption; }
set { Description.Caption = value; }
}
/// <summary>
/// Gets or sets the PayPal supplied Client ID
/// </summary>
public string ClientId { get; set; }
/// <summary>
/// Gets or sets the PayPal supplied Client Secret
/// </summary>
public string ClientSecret { get; set; }
/// <summary>
/// Gets or sets the PayPal Sandbox server to connect
/// </summary>
public bool IsSandbox { get; set; }
/// <summary>
/// Gets the sets of OAuth endpoints used to authenticate against PayPal. Overriding these endpoints allows you to use PayPal Enterprise for
/// authentication.
/// </summary>
public PayPalAuthenticationEndpoints Endpoints { get; set; }
/// <summary>
/// Gets or sets the <see cref="IPayPalAuthenticationProvider" /> used in the authentication events
/// </summary>
public IPayPalAuthenticationProvider Provider { get; set; }
/// <summary>
/// A list of permissions to request.
/// </summary>
public IList<string> Scope { get; private set; }
/// <summary>
/// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user
/// <see cref="System.Security.Claims.ClaimsIdentity" />.
/// </summary>
public string SignInAsAuthenticationType { get; set; }
/// <summary>
/// Gets or sets the type used to secure data handled by the middleware.
/// </summary>
public ISecureDataFormat<AuthenticationProperties> StateDataFormat { get; set; }
/// <summary>
/// Initializes a new <see cref="PayPalAuthenticationOptions" />
/// </summary>
public PayPalAuthenticationOptions(bool isSandbox=false)
: base("PayPal")
{
IsSandbox = isSandbox;
Caption = Constants.DefaultAuthenticationType;
CallbackPath = new PathString("/signin-paypal");
AuthenticationMode = AuthenticationMode.Passive;
Scope = new List<string>{
"openid"
};
BackchannelTimeout = TimeSpan.FromSeconds(60);
Endpoints = new PayPalAuthenticationEndpoints
{
AuthorizationEndpoint = isSandbox ? SandboxAuthorizationEndPoint : AuthorizationEndPoint,
TokenEndpoint = isSandbox ? SandboxTokenEndpoint : TokenEndpoint,
UserInfoEndpoint = isSandbox ? SandboxUserInfoEndpoint : UserInfoEndpoint
};
}
}
}

View File

@@ -0,0 +1,24 @@
using System.Threading.Tasks;
namespace Owin.Security.Providers.PayPal
{
/// <summary>
/// Specifies callback methods which the <see cref="PayPalAuthenticationMiddleware"></see> invokes to enable developer control over the authentication process. />
/// </summary>
public interface IPayPalAuthenticationProvider
{
/// <summary>
/// Invoked whenever PayPal 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(PayPalAuthenticatedContext 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(PayPalReturnEndpointContext context);
}
}

View File

@@ -0,0 +1,84 @@
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Globalization;
using System.Security.Claims;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Provider;
using Newtonsoft.Json.Linq;
namespace Owin.Security.Providers.PayPal
{
/// <summary>
/// Contains information about the login session as well as the user <see cref="System.Security.Claims.ClaimsIdentity"/>.
/// </summary>
public class PayPalAuthenticatedContext : BaseContext
{
/// <summary>
/// Initializes a <see cref="PayPalAuthenticatedContext"/>
/// </summary>
/// <param name="context">The OWIN environment</param>
/// <param name="user">The JSON-serialized user</param>
/// <param name="accessToken">PayPal Access token</param>
/// <param name="refreshToken">PayPal Refresh token</param>
public PayPalAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string refreshToken)
: base(context)
{
User = user;
AccessToken = accessToken;
RefreshToken = refreshToken;
Id = TryGetValue(user, "user_id").Replace("https://www.paypal.com/webapps/auth/identity/user/","");
Name = TryGetValue(user, "name");
Email = TryGetValue(user, "email");
}
/// <summary>
/// Gets the JSON-serialized user
/// </summary>
/// <remarks>
/// Contains the PayPal user obtained from the User Info endpoint. By default this is https://api.paypal.com/user but it can be
/// overridden in the options
/// </remarks>
public JObject User { get; private set; }
/// <summary>
/// Gets the PayPal access token
/// </summary>
public string AccessToken { get; private set; }
public string RefreshToken { get; private set; }
/// <summary>
/// Gets the PayPal user ID
/// </summary>
public string Id { get; private set; }
/// <summary>
/// Gets the user's name
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets the PayPal emails
/// </summary>
public string Email { get; private set; }
/// <summary>
/// Gets the <see cref="ClaimsIdentity"/> representing the user
/// </summary>
public ClaimsIdentity Identity { get; set; }
/// <summary>
/// Gets or sets a property bag for common authentication properties
/// </summary>
public AuthenticationProperties Properties { get; set; }
private static string TryGetValue(JObject user, string propertyName)
{
JToken value;
return user.TryGetValue(propertyName, out value) ? value.ToString() : null;
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
using System.Threading.Tasks;
namespace Owin.Security.Providers.PayPal
{
/// <summary>
/// Default <see cref="IPayPalAuthenticationProvider"/> implementation.
/// </summary>
public class PayPalAuthenticationProvider : IPayPalAuthenticationProvider
{
/// <summary>
/// Initializes a <see cref="PayPalAuthenticationProvider"/>
/// </summary>
public PayPalAuthenticationProvider()
{
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<PayPalAuthenticatedContext, Task> OnAuthenticated { get; set; }
/// <summary>
/// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked.
/// </summary>
public Func<PayPalReturnEndpointContext, Task> OnReturnEndpoint { get; set; }
/// <summary>
/// Invoked whenever PayPal 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(PayPalAuthenticatedContext 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(PayPalReturnEndpointContext 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.PayPal
{
/// <summary>
/// Provides context information to middleware providers.
/// </summary>
public class PayPalReturnEndpointContext : ReturnEndpointContext
{
/// <summary>
///
/// </summary>
/// <param name="context">OWIN environment</param>
/// <param name="ticket">The authentication ticket</param>
public PayPalReturnEndpointContext(
IOwinContext context,
AuthenticationTicket ticket)
: base(context, ticket)
{
}
}
}

View File

@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.15.0.0")]
[assembly: AssemblyFileVersion("1.15.0.0")]
[assembly: AssemblyVersion("1.17.1.0")]
[assembly: AssemblyFileVersion("1.17.1.0")]

View File

@@ -20,12 +20,14 @@ namespace Owin.Security.Providers.Salesforce
/// <param name="user">The JSON-serialized user</param>
/// <param name="accessToken">Salesforce Access token</param>
/// <param name="refreshToken">Salesforce Refresh token</param>
public SalesforceAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string refreshToken)
/// <param name="instanceUrl">Salesforce instance url</param>
public SalesforceAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string refreshToken, string instanceUrl)
: base(context)
{
User = user;
AccessToken = accessToken;
RefreshToken = refreshToken;
InstanceUrl = instanceUrl;
Id = TryGetValue(user, "id");
UserId = TryGetValue(user, "user_id");
@@ -59,6 +61,11 @@ namespace Owin.Security.Providers.Salesforce
/// </summary>
public string RefreshToken { get; private set; }
/// <summary>
/// Gets the Salesforce instance url
/// </summary>
public string InstanceUrl { get; private set; }
/// <summary>
/// Gets the Salesforce ID / User Info Endpoint
/// </summary>

View File

@@ -86,6 +86,7 @@ namespace Owin.Security.Providers.Salesforce
dynamic response = JsonConvert.DeserializeObject<dynamic>(text);
string accessToken = (string)response.access_token;
string refreshToken = (string)response.refresh_token;
string instanceUrl = (string)response.instance_url;
// Get the Salesforce user using the user info endpoint, which is part of the token - response.id
HttpRequestMessage userRequest = new HttpRequestMessage(HttpMethod.Get, (string)response.id + "?access_token=" + Uri.EscapeDataString(accessToken));
@@ -95,7 +96,7 @@ namespace Owin.Security.Providers.Salesforce
text = await userResponse.Content.ReadAsStringAsync();
JObject user = JObject.Parse(text);
var context = new SalesforceAuthenticatedContext(Context, user, accessToken, refreshToken);
var context = new SalesforceAuthenticatedContext(Context, user, accessToken, refreshToken, instanceUrl);
context.Identity = new ClaimsIdentity(
Options.AuthenticationType,
ClaimsIdentity.DefaultNameClaimType,

View File

@@ -1,5 +1,4 @@
using Microsoft.Owin;
using System;
using System;
namespace Owin.Security.Providers.Steam
{
@@ -25,8 +24,7 @@ namespace Owin.Security.Providers.Steam
throw new ArgumentNullException("options");
}
app.Use(typeof(SteamAuthenticationMiddleware), app, options);
return app;
return app.Use(typeof(SteamAuthenticationMiddleware), app, options);
}
/// <summary>
@@ -39,10 +37,6 @@ namespace Owin.Security.Providers.Steam
{
return UseSteamAuthentication(app, new SteamAuthenticationOptions
{
ProviderDiscoveryUri = "http://steamcommunity.com/openid/",
Caption = "Steam",
AuthenticationType = "Steam",
CallbackPath = new PathString("/signin-openidsteam"),
ApplicationKey = applicationKey
});
}

View File

@@ -1,9 +1,18 @@
using Owin.Security.Providers.OpenID;
using Microsoft.Owin;
using Owin.Security.Providers.OpenID;
namespace Owin.Security.Providers.Steam
{
public sealed class SteamAuthenticationOptions : OpenIDAuthenticationOptions
{
public string ApplicationKey { get; set; }
public SteamAuthenticationOptions()
{
ProviderDiscoveryUri = "http://steamcommunity.com/openid/";
Caption = "Steam";
AuthenticationType = "Steam";
CallbackPath = new PathString("/signin-openidsteam");
}
}
}

View File

@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Owin.Security.Providers.Wargaming
{
internal static class Constants
{
internal const string DefaultAuthenticationType = "Wargaming";
internal const string ProviderDiscoveryUriNorthAmerica = "https://na.wargaming.net/id/openid/";
internal const string ProviderDiscoveryUriEurope = "https://eu.wargaming.net/id/openid/";
internal const string ProviderDiscoveryUriRussia = "https://ru.wargaming.net/id/openid/";
internal const string ProviderDiscoveryUriAsia = "https://asia.wargaming.net/id/openid/";
internal const string ProviderDiscoveryUriKorea = "https://kr.wargaming.net/id/openid/";
}
}

View File

@@ -0,0 +1,69 @@
using System;
using Microsoft.Owin;
namespace Owin.Security.Providers.Wargaming
{
/// <summary>
/// Extension methods for using <see cref="WargamingAuthenticationMiddleware" />
/// </summary>
public static class WargamingAccountAuthenticationExtensions
{
private static string ResolveRegionDiscoveryUri(WargamingAuthenticationOptions.Region region)
{
switch (region)
{
case WargamingAuthenticationOptions.Region.NorthAmerica:
return Constants.ProviderDiscoveryUriNorthAmerica;
case WargamingAuthenticationOptions.Region.Europe:
return Constants.ProviderDiscoveryUriEurope;
case WargamingAuthenticationOptions.Region.Russia:
return Constants.ProviderDiscoveryUriRussia;
case WargamingAuthenticationOptions.Region.Asia:
return Constants.ProviderDiscoveryUriAsia;
case WargamingAuthenticationOptions.Region.Korea:
return Constants.ProviderDiscoveryUriKorea;
default:
return Constants.ProviderDiscoveryUriNorthAmerica;
}
}
/// <summary>
/// Authenticate users using Wargaming
/// </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 UseWargamingAccountAuthentication(this IAppBuilder app, WargamingAuthenticationOptions options)
{
if (app == null)
{
throw new ArgumentNullException("app");
}
if (options == null)
{
throw new ArgumentNullException("options");
}
return app.Use(typeof (WargamingAuthenticationMiddleware), app, options);
}
/// <summary>
/// Authenticate users using Steam
/// </summary>
/// <param name="app">The <see cref="IAppBuilder" /> passed to the configuration method</param>
/// <param name="appId">The wargaming application ID</param>
/// <param name="region">The <see cref="WargamingAuthenticationOptions.Region" /> to authenticate</param>
/// <returns>The updated <see cref="IAppBuilder" /></returns>
public static IAppBuilder UseWargamingAccountAuthentication(this IAppBuilder app, string appId, WargamingAuthenticationOptions.Region region = WargamingAuthenticationOptions.Region.NorthAmerica)
{
return UseWargamingAccountAuthentication(app, new WargamingAuthenticationOptions
{
ProviderDiscoveryUri = ResolveRegionDiscoveryUri(region),
Caption = "Wargaming",
AuthenticationType = "Wargaming",
CallbackPath = new PathString("/signin-wargaming"),
AppId = appId
});
}
}
}

View File

@@ -0,0 +1,36 @@
using Microsoft.Owin.Logging;
using Newtonsoft.Json;
using Owin.Security.Providers.OpenID;
using System.Collections.Generic;
using System.Net.Http;
using System.Security.Claims;
using System.Text.RegularExpressions;
namespace Owin.Security.Providers.Wargaming
{
internal sealed class WargamingAuthenticationHandler : OpenIDAuthenticationHandlerBase<WargamingAuthenticationOptions>
{
private readonly Regex AccountIDRegex = new Regex(@"^https://na.wargaming.net/id/([0-9]{10}).*$", RegexOptions.Compiled);
private const string UserInfoUri = "https://api.worldoftanks.com/wot/account/info/?application_id={0}&account_id={1}&fields=nickname";
public WargamingAuthenticationHandler(HttpClient httpClient, ILogger logger)
: base(httpClient, logger)
{
}
protected override void SetIdentityInformations(ClaimsIdentity identity, string claimedID, IDictionary<string, string> attributeExchangeProperties)
{
Match accountIDMatch = AccountIDRegex.Match(claimedID);
if (accountIDMatch.Success)
{
string accountID = accountIDMatch.Groups[1].Value;
var getUserInfoTask = _httpClient.GetStringAsync(string.Format(UserInfoUri, Options.AppId, accountID));
getUserInfoTask.Wait();
string userInfoRaw = getUserInfoTask.Result;
dynamic userInfo = JsonConvert.DeserializeObject(userInfoRaw);
identity.AddClaim(new Claim(ClaimTypes.Name, (string)userInfo["data"][accountID].nickname, "http://www.w3.org/2001/XMLSchema#string", Options.AuthenticationType));
}
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Globalization;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Logging;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.Owin.Security.Infrastructure;
using Owin.Security.Providers.OpenID;
namespace Owin.Security.Providers.Wargaming
{
/// <summary>
/// OWIN middleware for authenticating users using an OpenID provider
/// </summary>
public class WargamingAuthenticationMiddleware : OpenIDAuthenticationMiddlewareBase<WargamingAuthenticationOptions>
{
/// <summary>
/// Initializes a <see cref="WargamingAuthenticationMiddleware"/>
/// </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 WargamingAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, WargamingAuthenticationOptions options)
: base(next, app, options)
{ }
protected override AuthenticationHandler<WargamingAuthenticationOptions> CreateSpecificHandler()
{
return new WargamingAuthenticationHandler(_httpClient, _logger);
}
}
}

View File

@@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Owin.Security.Providers.OpenID;
namespace Owin.Security.Providers.Wargaming
{
public class WargamingAuthenticationOptions : OpenIDAuthenticationOptions
{
/// <summary>
/// Region to use for to log in
/// </summary>
public enum Region
{
NorthAmerica,
Europe,
Russia,
Asia,
Korea
}
/// <summary>
/// Gets or sets the Wargaming-assigned appId
/// </summary>
public string AppId { get; set; }
}
}

View File

@@ -10,6 +10,7 @@ using Owin.Security.Providers.BattleNet;
using Owin.Security.Providers.Buffer;
using Owin.Security.Providers.Dropbox;
using Owin.Security.Providers.EveOnline;
using Owin.Security.Providers.Flickr;
using Owin.Security.Providers.Foursquare;
using Owin.Security.Providers.GitHub;
using Owin.Security.Providers.GooglePlus;
@@ -17,6 +18,7 @@ using Owin.Security.Providers.GooglePlus.Provider;
using Owin.Security.Providers.HealthGraph;
using Owin.Security.Providers.Instagram;
using Owin.Security.Providers.LinkedIn;
using Owin.Security.Providers.PayPal;
using Owin.Security.Providers.Reddit;
using Owin.Security.Providers.Salesforce;
using Owin.Security.Providers.StackExchange;
@@ -26,8 +28,7 @@ using Owin.Security.Providers.Yahoo;
using Owin.Security.Providers.OpenID;
using Owin.Security.Providers.SoundCloud;
using Owin.Security.Providers.Steam;
using Owin.Security.Providers.Untappd;
using Owin.Security.Providers.WordPress;
using Owin.Security.Providers.Wargaming;using Owin.Security.Providers.Untappd;using Owin.Security.Providers.WordPress;
namespace OwinOAuthProvidersDemo
{
@@ -211,6 +212,15 @@ namespace OwinOAuthProvidersDemo
//app.UseFoursquareAuthentication(
// clientId: "",
// clientSecret: "");
//app.UsePayPalAuthentication(
// clientId: "",
// clientSecret: "",
// isSandbox: false);
//app.UseWargamingAccountAuthentication("", WargamingAuthenticationOptions.Region.NorthAmerica);
//app.UseFlickrAuthentication("", "");
}
}
}