Flickr support
This commit is contained in:
7
Owin.Security.Providers/Flickr/Constants.cs
Normal file
7
Owin.Security.Providers/Flickr/Constants.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace Owin.Security.Providers.Flickr
|
||||
{
|
||||
internal static class Constants
|
||||
{
|
||||
public const string DefaultAuthenticationType = "Flickr";
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
367
Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs
Normal file
367
Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs
Normal 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.FullName))
|
||||
{
|
||||
context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName,
|
||||
XmlSchemaString, Options.AuthenticationType));
|
||||
}
|
||||
if (!String.IsNullOrEmpty(context.UserName))
|
||||
{
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
25
Owin.Security.Providers/Flickr/Messages/AccessToken.cs
Normal file
25
Owin.Security.Providers/Flickr/Messages/AccessToken.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
29
Owin.Security.Providers/Flickr/Messages/RequestToken.cs
Normal file
29
Owin.Security.Providers/Flickr/Messages/RequestToken.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
22
Owin.Security.Providers/Flickr/Messages/Serializers.cs
Normal file
22
Owin.Security.Providers/Flickr/Messages/Serializers.cs
Normal 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; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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" />
|
||||
|
||||
@@ -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;
|
||||
@@ -209,6 +210,8 @@ namespace OwinOAuthProvidersDemo
|
||||
//app.UseFoursquareAuthentication(
|
||||
// clientId: "",
|
||||
// clientSecret: "");
|
||||
|
||||
//app.UseFlickrAuthentication("", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user