From 6d001e3e136a29953dd3f8b11e342d826d80f46b Mon Sep 17 00:00:00 2001 From: Ivan Nikitin Date: Tue, 24 Mar 2015 19:14:26 +0100 Subject: [PATCH 1/2] Flickr support --- Owin.Security.Providers/Flickr/Constants.cs | 7 + .../Flickr/FlickrAuthenticationExtensions.cs | 29 ++ .../Flickr/FlickrAuthenticationHandler.cs | 367 ++++++++++++++++++ .../Flickr/FlickrAuthenticationMiddleware.cs | 90 +++++ .../Flickr/FlickrAuthenticationOptions.cs | 99 +++++ .../Flickr/Messages/AccessToken.cs | 25 ++ .../Flickr/Messages/RequestToken.cs | 29 ++ .../Flickr/Messages/RequestTokenSerializer.cs | 106 +++++ .../Flickr/Messages/Serializers.cs | 22 ++ .../Provider/FlickrAuthenticatedContext.cs | 66 ++++ .../Provider/FlickrAuthenticationProvider.cs | 45 +++ .../Provider/FlickrReturnEndpointContext.cs | 21 + .../Provider/IFlickrAuthenticationProvider.cs | 26 ++ .../Owin.Security.Providers.csproj | 13 + .../App_Start/Startup.Auth.cs | 3 + 15 files changed, 948 insertions(+) create mode 100644 Owin.Security.Providers/Flickr/Constants.cs create mode 100644 Owin.Security.Providers/Flickr/FlickrAuthenticationExtensions.cs create mode 100644 Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs create mode 100644 Owin.Security.Providers/Flickr/FlickrAuthenticationMiddleware.cs create mode 100644 Owin.Security.Providers/Flickr/FlickrAuthenticationOptions.cs create mode 100644 Owin.Security.Providers/Flickr/Messages/AccessToken.cs create mode 100644 Owin.Security.Providers/Flickr/Messages/RequestToken.cs create mode 100644 Owin.Security.Providers/Flickr/Messages/RequestTokenSerializer.cs create mode 100644 Owin.Security.Providers/Flickr/Messages/Serializers.cs create mode 100644 Owin.Security.Providers/Flickr/Provider/FlickrAuthenticatedContext.cs create mode 100644 Owin.Security.Providers/Flickr/Provider/FlickrAuthenticationProvider.cs create mode 100644 Owin.Security.Providers/Flickr/Provider/FlickrReturnEndpointContext.cs create mode 100644 Owin.Security.Providers/Flickr/Provider/IFlickrAuthenticationProvider.cs diff --git a/Owin.Security.Providers/Flickr/Constants.cs b/Owin.Security.Providers/Flickr/Constants.cs new file mode 100644 index 0000000..e5a32d3 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Constants.cs @@ -0,0 +1,7 @@ +namespace Owin.Security.Providers.Flickr +{ + internal static class Constants + { + public const string DefaultAuthenticationType = "Flickr"; + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Flickr/FlickrAuthenticationExtensions.cs b/Owin.Security.Providers/Flickr/FlickrAuthenticationExtensions.cs new file mode 100644 index 0000000..b1fe1d8 --- /dev/null +++ b/Owin.Security.Providers/Flickr/FlickrAuthenticationExtensions.cs @@ -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 + }); + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs b/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs new file mode 100644 index 0000000..93591b4 --- /dev/null +++ b/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs @@ -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 + { + 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 InvokeAsync() + { + if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) + { + return await InvokeReturnPathAsync(); + } + return false; + } + + protected override async Task AuthenticateCoreAsync() + { + AuthenticationProperties properties = null; + try + { + IReadableStringCollection query = Request.Query; + string protectedRequestToken = Request.Cookies[StateCookie]; + + RequestToken requestToken = Options.StateDataFormat.Unprotect(protectedRequestToken); + + if (requestToken == null) + { + logger.WriteWarning("Invalid state"); + return null; + } + + properties = requestToken.Properties; + + string returnedToken = query.Get("oauth_token"); + if (string.IsNullOrWhiteSpace(returnedToken)) + { + logger.WriteWarning("Missing oauth_token"); + return new AuthenticationTicket(null, properties); + } + + if (returnedToken != requestToken.Token) + { + logger.WriteWarning("Unmatched token"); + return new AuthenticationTicket(null, properties); + } + + string oauthVerifier = query.Get("oauth_verifier"); + if (string.IsNullOrWhiteSpace(oauthVerifier)) + { + logger.WriteWarning("Missing or blank oauth_verifier"); + return new AuthenticationTicket(null, properties); + } + + AccessToken accessToken = await ObtainAccessTokenAsync(Options.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 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 ObtainRequestTokenAsync(string AppKey, string AppSecret, string callBackUri, AuthenticationProperties properties) + { + logger.WriteVerbose("ObtainRequestToken"); + + string nonce = Guid.NewGuid().ToString("N"); + + var authorizationParts = new SortedDictionary + { + { "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 ObtainAccessTokenAsync(string AppKey, string AppSecret, RequestToken token, string verifier) + { + logger.WriteVerbose("ObtainAccessToken"); + + string nonce = Guid.NewGuid().ToString("N"); + + var authorizationParts = new SortedDictionary + { + { "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>() + { + new KeyValuePair("oauth_verifier", verifier) + }; + + request.Content = new FormUrlEncodedContent(formPairs); + + HttpResponseMessage response = await httpClient.SendAsync(request, Request.CallCancelled); + + if (!response.IsSuccessStatusCode) + { + logger.WriteError("AccessToken request failed with a status code of " + response.StatusCode); + response.EnsureSuccessStatusCode(); // throw + } + + string responseText = await response.Content.ReadAsStringAsync(); + IFormCollection responseParameters = WebHelpers.ParseForm(responseText); + + return new AccessToken + { + Token = Uri.UnescapeDataString(responseParameters["oauth_token"]), + TokenSecret = Uri.UnescapeDataString(responseParameters["oauth_token_secret"]), + UserId = Uri.UnescapeDataString(responseParameters["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); + } + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Flickr/FlickrAuthenticationMiddleware.cs b/Owin.Security.Providers/Flickr/FlickrAuthenticationMiddleware.cs new file mode 100644 index 0000000..3eb4be0 --- /dev/null +++ b/Owin.Security.Providers/Flickr/FlickrAuthenticationMiddleware.cs @@ -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 + { + 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(); + + 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( + 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 + }; + } + + /// + /// Provides the object for processing + /// authentication-related requests. + /// + /// + /// An configured with the + /// supplied to the constructor. + /// + protected override AuthenticationHandler 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; + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Flickr/FlickrAuthenticationOptions.cs b/Owin.Security.Providers/Flickr/FlickrAuthenticationOptions.cs new file mode 100644 index 0000000..9dff4c5 --- /dev/null +++ b/Owin.Security.Providers/Flickr/FlickrAuthenticationOptions.cs @@ -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 + { + /// + /// Gets or sets the a pinned certificate validator to use to validate the endpoints used + /// in back channel communications belong to Flickr. + /// + /// + /// The pinned certificate validator. + /// + /// + /// If this property is null then the default certificate checks are performed, + /// validating the subject name and if the signing chain is a trusted party. + /// + public ICertificateValidator BackchannelCertificateValidator { get; set; } + + /// + /// The HttpMessageHandler used to communicate with Flickr. + /// This cannot be set at the same time as BackchannelCertificateValidator unless the value + /// can be downcast to a WebRequestHandler. + /// + public HttpMessageHandler BackchannelHttpHandler { get; set; } + + /// + /// Gets or sets timeout value in milliseconds for back channel communications with Flickr. + /// + /// + /// The back channel timeout in milliseconds. + /// + public TimeSpan BackchannelTimeout { get; set; } + + /// + /// 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". + /// + public PathString CallbackPath { get; set; } + + /// + /// Get or sets the text that the user can display on a sign in user interface. + /// + public string Caption + { + get { return Description.Caption; } + set { Description.Caption = value; } + } + + /// + /// Gets or sets the Flickr supplied App Key + /// + public string AppKey { get; set; } + + /// + /// Gets or sets the Flickr supplied App Secret + /// + public string AppSecret { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public IFlickrAuthenticationProvider Provider { get; set; } + + /// + /// A list of permissions to request. + /// + public string Scope { get; set; } + + /// + /// Gets or sets the name of another authentication middleware which will be responsible for actually issuing a user + /// . + /// + public string SignInAsAuthenticationType { get; set; } + + /// + /// Gets or sets the type used to secure data handled by the middleware. + /// + public ISecureDataFormat StateDataFormat { get; set; } + + /// + /// Initializes a new + /// + public FlickrAuthenticationOptions() + : base("Flickr") + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-flickr"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = "read"; + BackchannelTimeout = TimeSpan.FromSeconds(60); + } + } +} diff --git a/Owin.Security.Providers/Flickr/Messages/AccessToken.cs b/Owin.Security.Providers/Flickr/Messages/AccessToken.cs new file mode 100644 index 0000000..40c10dd --- /dev/null +++ b/Owin.Security.Providers/Flickr/Messages/AccessToken.cs @@ -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 +{ + /// + /// Flickr access token + /// + public class AccessToken : RequestToken + { + /// + /// Gets or sets the Flickr User ID + /// + public string UserId { get; set; } + + /// + /// Gets or sets the Flickr User Name + /// + public string UserName { get; set; } + + /// + /// Gets or sets the Flickr User Full Name + /// + public string FullName { get; set; } + } +} diff --git a/Owin.Security.Providers/Flickr/Messages/RequestToken.cs b/Owin.Security.Providers/Flickr/Messages/RequestToken.cs new file mode 100644 index 0000000..74748aa --- /dev/null +++ b/Owin.Security.Providers/Flickr/Messages/RequestToken.cs @@ -0,0 +1,29 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin.Security; + +namespace Owin.Security.Providers.Flickr.Messages +{ + /// + /// Yahoo request token + /// + public class RequestToken + { + /// + /// Gets or sets the Yahoo token + /// + public string Token { get; set; } + + /// + /// Gets or sets the Yahoo token secret + /// + public string TokenSecret { get; set; } + + public bool CallbackConfirmed { get; set; } + + /// + /// Gets or sets a property bag for common authentication properties + /// + public AuthenticationProperties Properties { get; set; } + } +} diff --git a/Owin.Security.Providers/Flickr/Messages/RequestTokenSerializer.cs b/Owin.Security.Providers/Flickr/Messages/RequestTokenSerializer.cs new file mode 100644 index 0000000..56b0253 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Messages/RequestTokenSerializer.cs @@ -0,0 +1,106 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.DataHandler.Serializer; + +namespace Owin.Security.Providers.Flickr.Messages +{ + /// + /// Serializes and deserializes Yahoo request and access tokens so that they can be used by other application components. + /// + public class RequestTokenSerializer : IDataSerializer + { + private const int FormatVersion = 1; + + /// + /// Serialize a request token + /// + /// The token to serialize + /// A byte array containing the serialized token + [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Dispose is idempotent")] + public virtual byte[] Serialize(RequestToken model) + { + using (var memory = new MemoryStream()) + { + using (var writer = new BinaryWriter(memory)) + { + Write(writer, model); + writer.Flush(); + return memory.ToArray(); + } + } + } + + /// + /// Deserializes a request token + /// + /// A byte array containing the serialized token + /// The Yahoo request token + [SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times", Justification = "Dispose is idempotent")] + public virtual RequestToken Deserialize(byte[] data) + { + using (var memory = new MemoryStream(data)) + { + using (var reader = new BinaryReader(memory)) + { + return Read(reader); + } + } + } + + /// + /// Writes a Yahoo request token as a series of bytes. Used by the method. + /// + /// The writer to use in writing the token + /// The token to write + public static void Write(BinaryWriter writer, RequestToken token) + { + if (writer == null) + { + throw new ArgumentNullException("writer"); + } + if (token == null) + { + throw new ArgumentNullException("token"); + } + + writer.Write(FormatVersion); + writer.Write(token.Token); + writer.Write(token.TokenSecret); + writer.Write(token.CallbackConfirmed); + PropertiesSerializer.Write(writer, token.Properties); + } + + /// + /// Reads a Yahoo request token from a series of bytes. Used by the method. + /// + /// The reader to use in reading the token bytes + /// The token + public static RequestToken Read(BinaryReader reader) + { + if (reader == null) + { + throw new ArgumentNullException("reader"); + } + + if (reader.ReadInt32() != FormatVersion) + { + return null; + } + + string token = reader.ReadString(); + string tokenSecret = reader.ReadString(); + bool callbackConfirmed = reader.ReadBoolean(); + AuthenticationProperties properties = PropertiesSerializer.Read(reader); + if (properties == null) + { + return null; + } + + return new RequestToken { Token = token, TokenSecret = tokenSecret, CallbackConfirmed = callbackConfirmed, Properties = properties }; + } + } +} diff --git a/Owin.Security.Providers/Flickr/Messages/Serializers.cs b/Owin.Security.Providers/Flickr/Messages/Serializers.cs new file mode 100644 index 0000000..bcf577d --- /dev/null +++ b/Owin.Security.Providers/Flickr/Messages/Serializers.cs @@ -0,0 +1,22 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin.Security.DataHandler.Serializer; + +namespace Owin.Security.Providers.Flickr.Messages +{ + /// + /// Provides access to a request token serializer + /// + public static class Serializers + { + static Serializers() + { + RequestToken = new RequestTokenSerializer(); + } + + /// + /// Gets or sets a statically-avaliable serializer object. The value for this property will be by default. + /// + public static IDataSerializer RequestToken { get; set; } + } +} diff --git a/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticatedContext.cs b/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticatedContext.cs new file mode 100644 index 0000000..d8bba84 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticatedContext.cs @@ -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 { + /// + /// Contains information about the login session as well as the user . + /// + public class FlickrAuthenticatedContext : BaseContext { + /// + /// Initializes a + /// + /// The OWIN environment + /// Flick access toke + public FlickrAuthenticatedContext(IOwinContext context, AccessToken accessToken) + : base(context) + { + FullName = accessToken.FullName; + UserId = accessToken.UserId; + UserName = accessToken.UserName; + AccessToken = accessToken.Token; + AccessTokenSecret = accessToken.TokenSecret; + } + + /// + /// Gets user full name + /// + public string FullName { get; private set; } + + /// + /// Gets the Flickr user ID + /// + public string UserId { get; private set; } + + /// + /// Gets the Flickr username + /// + public string UserName { get; private set; } + + /// + /// Gets the Flickr access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Flickr access token secret + /// + public string AccessTokenSecret { get; private set; } + + /// + /// Gets the representing the user + /// + public ClaimsIdentity Identity { get; set; } + + /// + /// Gets or sets a property bag for common authentication properties + /// + public AuthenticationProperties Properties { get; set; } + } +} diff --git a/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticationProvider.cs b/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticationProvider.cs new file mode 100644 index 0000000..c043f44 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Provider/FlickrAuthenticationProvider.cs @@ -0,0 +1,45 @@ +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Flickr { + /// + /// Default implementation. + /// + public class FlickrAuthenticationProvider : IFlickrAuthenticationProvider { + /// + /// Initializes a + /// + public FlickrAuthenticationProvider() { + OnAuthenticated = context => Task.FromResult(null); + OnReturnEndpoint = context => Task.FromResult(null); + } + + /// + /// Gets or sets the function that is invoked when the Authenticated method is invoked. + /// + public Func OnAuthenticated { get; set; } + + /// + /// Gets or sets the function that is invoked when the ReturnEndpoint method is invoked. + /// + public Func OnReturnEndpoint { get; set; } + + /// + /// Invoked whenever Flickr succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(FlickrAuthenticatedContext context) { + return OnAuthenticated(context); + } + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + public virtual Task ReturnEndpoint(FlickrReturnEndpointContext context) { + return OnReturnEndpoint(context); + } + } +} diff --git a/Owin.Security.Providers/Flickr/Provider/FlickrReturnEndpointContext.cs b/Owin.Security.Providers/Flickr/Provider/FlickrReturnEndpointContext.cs new file mode 100644 index 0000000..1b9ad25 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Provider/FlickrReturnEndpointContext.cs @@ -0,0 +1,21 @@ +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; + +namespace Owin.Security.Providers.Flickr { + /// + /// Provides context information to middleware providers. + /// + public class FlickrReturnEndpointContext : ReturnEndpointContext { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public FlickrReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) { + } + } +} diff --git a/Owin.Security.Providers/Flickr/Provider/IFlickrAuthenticationProvider.cs b/Owin.Security.Providers/Flickr/Provider/IFlickrAuthenticationProvider.cs new file mode 100644 index 0000000..96d54d7 --- /dev/null +++ b/Owin.Security.Providers/Flickr/Provider/IFlickrAuthenticationProvider.cs @@ -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 { + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface IFlickrAuthenticationProvider { + /// + /// Invoked whenever Flickr succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(FlickrAuthenticatedContext context); + + /// + /// Invoked prior to the being saved in a local cookie and the browser being redirected to the originally requested URL. + /// + /// + /// A representing the completed operation. + Task ReturnEndpoint(FlickrReturnEndpointContext context); + } +} diff --git a/Owin.Security.Providers/Owin.Security.Providers.csproj b/Owin.Security.Providers/Owin.Security.Providers.csproj index a638670..3364ab0 100644 --- a/Owin.Security.Providers/Owin.Security.Providers.csproj +++ b/Owin.Security.Providers/Owin.Security.Providers.csproj @@ -112,6 +112,19 @@ + + + + + + + + + + + + + diff --git a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs index bf04d4a..cdfdb3b 100755 --- a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs +++ b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.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("", ""); } } } \ No newline at end of file From 1eb34c4e83b11a53aa1e1b3ecdfad8347c68c5b3 Mon Sep 17 00:00:00 2001 From: Ivan Nikitin Date: Wed, 25 Mar 2015 16:39:55 +0100 Subject: [PATCH 2/2] Flickr - Fixes incorrect variable uses --- Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs b/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs index 93591b4..fa920c4 100644 --- a/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs +++ b/Owin.Security.Providers/Flickr/FlickrAuthenticationHandler.cs @@ -98,12 +98,12 @@ namespace Owin.Security.Providers.Flickr context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.UserId, XmlSchemaString, Options.AuthenticationType)); } - if (!String.IsNullOrEmpty(context.FullName)) + if(!String.IsNullOrEmpty(context.UserName)) { context.Identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName, XmlSchemaString, Options.AuthenticationType)); } - if (!String.IsNullOrEmpty(context.UserName)) + if (!String.IsNullOrEmpty(context.FullName)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.FullName, XmlSchemaString, Options.AuthenticationType));