diff --git a/Owin.Security.Providers/Fitbit/Constants.cs b/Owin.Security.Providers/Fitbit/Constants.cs new file mode 100644 index 0000000..3864cc5 --- /dev/null +++ b/Owin.Security.Providers/Fitbit/Constants.cs @@ -0,0 +1,7 @@ +namespace Owin.Security.Providers.Fitbit +{ + internal static class Constants + { + public const string DefaultAuthenticationType = "Fitbit"; + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/FitbitAuthenticationExtensions.cs b/Owin.Security.Providers/Fitbit/FitbitAuthenticationExtensions.cs new file mode 100644 index 0000000..633a8a5 --- /dev/null +++ b/Owin.Security.Providers/Fitbit/FitbitAuthenticationExtensions.cs @@ -0,0 +1,29 @@ +using System; + +namespace Owin.Security.Providers.Fitbit +{ + public static class FitbitAuthenticationExtensions + { + public static IAppBuilder UseFitbitAuthentication(this IAppBuilder app, + FitbitAuthenticationOptions options) + { + if (app == null) + throw new ArgumentNullException("app"); + if (options == null) + throw new ArgumentNullException("options"); + + app.Use(typeof(FitbitAuthenticationMiddleware), app, options); + + return app; + } + + public static IAppBuilder UseFitbitAuthentication(this IAppBuilder app, string clientId, string clientSecret) + { + return app.UseFitbitAuthentication(new FitbitAuthenticationOptions + { + ClientId = clientId, + ClientSecret = clientSecret + }); + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/FitbitAuthenticationHandler.cs b/Owin.Security.Providers/Fitbit/FitbitAuthenticationHandler.cs new file mode 100644 index 0000000..adec2cb --- /dev/null +++ b/Owin.Security.Providers/Fitbit/FitbitAuthenticationHandler.cs @@ -0,0 +1,233 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Owin; +using Microsoft.Owin.Infrastructure; +using Microsoft.Owin.Logging; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.DataHandler.Encoder; +using Microsoft.Owin.Security.Infrastructure; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using Owin.Security.Providers.Fitbit.Provider; + +namespace Owin.Security.Providers.Fitbit +{ + public class FitbitAuthenticationHandler : AuthenticationHandler + { + private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; + + private readonly ILogger logger; + private readonly HttpClient httpClient; + + public FitbitAuthenticationHandler(HttpClient httpClient, ILogger logger) + { + this.httpClient = httpClient; + this.logger = logger; + } + + protected override async Task AuthenticateCoreAsync() + { + AuthenticationProperties properties = null; + + try + { + string code = null; + string state = null; + + IReadableStringCollection query = Request.Query; + IList values = query.GetValues("code"); + if (values != null && values.Count == 1) + { + code = 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; + + // Build up the body for the token request + var body = new List>(); + body.Add(new KeyValuePair("code", code)); + body.Add(new KeyValuePair("grant_type", "authorization_code")); + body.Add(new KeyValuePair("client_id", Options.ClientId)); + body.Add(new KeyValuePair("redirect_uri", redirectUri)); + + // Request the token + var requestMessage = new HttpRequestMessage(HttpMethod.Post, Options.Endpoints.TokenEndpoint); + requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Basic", new Base64TextEncoder().Encode(Encoding.ASCII.GetBytes(Options.ClientId + ":" + Options.ClientSecret))); + requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + requestMessage.Content = new FormUrlEncodedContent(body); + HttpResponseMessage tokenResponse = await httpClient.SendAsync(requestMessage); + tokenResponse.EnsureSuccessStatusCode(); + string text = await tokenResponse.Content.ReadAsStringAsync(); + + // Deserializes the token response + dynamic response = JsonConvert.DeserializeObject(text); + string accessToken = (string)response.access_token; + string refreshToken = (string) response.refresh_token; + + // Get the user info + var userInfoRequest = new HttpRequestMessage(HttpMethod.Get, Options.Endpoints.UserEndpoint); + userInfoRequest.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + userInfoRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + HttpResponseMessage userInfoResponse = await httpClient.SendAsync(userInfoRequest); + userInfoResponse.EnsureSuccessStatusCode(); + text = await userInfoResponse.Content.ReadAsStringAsync(); + JObject user = JObject.Parse(text); + + var context = new FitbitAuthenticatedContext(Context, user, accessToken, refreshToken); + context.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.Name)) + { + context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, 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); + } + return new AuthenticationTicket(null, properties); + } + + protected override Task ApplyResponseChallengeAsync() + { + if (Response.StatusCode != 401) + { + return Task.FromResult(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) + + "&response_type=" + Uri.EscapeDataString("code") + + "&scope=" + Uri.EscapeDataString(scope) + + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + + "&prompt=" + Uri.EscapeDataString(Options.Prompt) + + "&state=" + Uri.EscapeDataString(state); + + Response.Redirect(authorizationEndpoint); + } + + return Task.FromResult(null); + } + + public override async Task InvokeAsync() + { + return await InvokeReplyPathAsync(); + } + + private async Task InvokeReplyPathAsync() + { + if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) + { + // TODO: error responses + + AuthenticationTicket ticket = await AuthenticateAsync(); + if (ticket == null) + { + logger.WriteWarning("Invalid return state, unable to redirect."); + Response.StatusCode = 500; + return true; + } + + var context = new FitbitReturnEndpointContext(Context, ticket); + context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType; + context.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; + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/FitbitAuthenticationMiddleware.cs b/Owin.Security.Providers/Fitbit/FitbitAuthenticationMiddleware.cs new file mode 100644 index 0000000..e984b35 --- /dev/null +++ b/Owin.Security.Providers/Fitbit/FitbitAuthenticationMiddleware.cs @@ -0,0 +1,69 @@ +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.Fitbit.Provider; +using Owin.Security.Providers.Properties; + +namespace Owin.Security.Providers.Fitbit +{ + public class FitbitAuthenticationMiddleware : AuthenticationMiddleware + { + private readonly HttpClient httpClient; + private readonly ILogger logger; + + public FitbitAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, + FitbitAuthenticationOptions 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(); + + if (Options.Provider == null) + Options.Provider = new FitbitAuthenticationProvider(); + + if (Options.StateDataFormat == null) + { + IDataProtector dataProtector = app.CreateDataProtector( + typeof (FitbitAuthenticationMiddleware).FullName, + Options.AuthenticationType, "v1"); + Options.StateDataFormat = new PropertiesDataFormat(dataProtector); + } + + if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType)) + Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType(); + + httpClient = new HttpClient(new WebRequestHandler()) + { + Timeout = Options.BackchannelTimeout, + MaxResponseContentBufferSize = 1024*1024*10, + }; + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin Fitbit middleware"); + httpClient.DefaultRequestHeaders.ExpectContinue = false; + } + + /// + /// Provides the object for processing + /// authentication-related requests. + /// + /// + /// An configured with the + /// supplied to the constructor. + /// + protected override AuthenticationHandler CreateHandler() + { + return new FitbitAuthenticationHandler(httpClient, logger); + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/FitbitAuthenticationOptions.cs b/Owin.Security.Providers/Fitbit/FitbitAuthenticationOptions.cs new file mode 100644 index 0000000..1a04bba --- /dev/null +++ b/Owin.Security.Providers/Fitbit/FitbitAuthenticationOptions.cs @@ -0,0 +1,126 @@ +using System; +using System.Collections.Generic; +using System.Net.Http; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Owin.Security.Providers.Fitbit.Provider; + +namespace Owin.Security.Providers.Fitbit +{ + public class FitbitAuthenticationOptions : AuthenticationOptions + { + public class FitbitAuthenticationEndpoints + { + /// + /// Endpoint which is used to redirect users to request Fitbit access + /// + /// + /// Defaults to https://www.fitbit.com/oauth2/authorize + /// + public string AuthorizationEndpoint { get; set; } + + /// + /// Endpoint which is used to exchange code for access token + /// + /// + /// Defaults to https://api.fitbit.com/oauth2/token + /// + public string TokenEndpoint { get; set; } + + public string UserEndpoint { get; set; } + } + + private const string AuthorizationEndPoint = "https://www.fitbit.com/oauth2/authorize"; + private const string TokenEndpoint = "https://api.fitbit.com/oauth2/token"; + private const string UserEndpoint = "https://api.fitbit.com/1/user/-/profile.json"; + + /// + /// Gets or sets timeout value in milliseconds for back channel communications with Fitbit. + /// + /// + /// 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-Fitbit". + /// + 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 Fitbit supplied Client ID + /// + public string ClientId { get; set; } + + /// + /// Gets or sets the Fitbit supplied Client Secret + /// + public string ClientSecret { get; set; } + + /// + /// Gets the sets of OAuth endpoints used to authenticate against Fitbit. Overriding these endpoints allows you to use Fitbit Enterprise for + /// authentication. + /// + public FitbitAuthenticationEndpoints Endpoints { get; set; } + + /// + /// Gets or sets the used in the authentication events + /// + public IFitbitAuthenticationProvider Provider { get; set; } + + /// + /// A list of permissions to request. + /// + public IList Scope { get; private 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 mode of the fitbit authentication page. Can be none, login, or consent. Defaults to none. + /// + public string Prompt { get; set; } + + /// + /// Gets or sets the type used to secure data handled by the middleware. + /// + public ISecureDataFormat StateDataFormat { get; set; } + + /// + /// Initializes a new + /// + public FitbitAuthenticationOptions() + : base("Fitbit") + { + Caption = Constants.DefaultAuthenticationType; + CallbackPath = new PathString("/signin-fitbit"); + AuthenticationMode = AuthenticationMode.Passive; + Scope = new List + { + "activity", "nutrition", "profile", "settings", "sleep", "social", "weight" + }; + BackchannelTimeout = TimeSpan.FromSeconds(60); + Endpoints = new FitbitAuthenticationEndpoints + { + AuthorizationEndpoint = AuthorizationEndPoint, + TokenEndpoint = TokenEndpoint, + UserEndpoint = UserEndpoint, + }; + Prompt = "none"; + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/Provider/FitbitAuthenticatedContext.cs b/Owin.Security.Providers/Fitbit/Provider/FitbitAuthenticatedContext.cs new file mode 100644 index 0000000..ac8018c --- /dev/null +++ b/Owin.Security.Providers/Fitbit/Provider/FitbitAuthenticatedContext.cs @@ -0,0 +1,72 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using System.Security.Claims; +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; +using Newtonsoft.Json.Linq; + +namespace Owin.Security.Providers.Fitbit.Provider +{ + /// + /// Contains information about the login session as well as the user . + /// + public class FitbitAuthenticatedContext : BaseContext + { + /// + /// Initializes a + /// + /// The OWIN environment + /// The Fitbit user information + /// Fitbit Access token + /// Fitbit Refresh token + public FitbitAuthenticatedContext(IOwinContext context, JObject user, string accessToken, string refreshToken) + : base(context) + { + AccessToken = accessToken; + RefreshToken = refreshToken; + User = user; + Name = user.SelectToken("user.displayName").ToString(); + Id = user.SelectToken("user.encodedId").ToString(); + } + + /// + /// Gets the user json object that was retrieved from Fitbit + /// during the authorization process. + /// + public JObject User { get; private set; } + + /// + /// Gets the user name extracted from the Fitbit API during + /// the authorization process. + /// + public string Name { get; private set; } + + /// + /// Gets the user id extracted from the FitbitAPI during the + /// authorization process. + /// + public string Id { get; private set; } + + /// + /// Gets the Fitbit access token + /// + public string AccessToken { get; private set; } + + /// + /// Gets the Fitbit refresh token + /// + public string RefreshToken { 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/Fitbit/Provider/FitbitAuthenticationProvider.cs b/Owin.Security.Providers/Fitbit/Provider/FitbitAuthenticationProvider.cs new file mode 100644 index 0000000..6cbcbaf --- /dev/null +++ b/Owin.Security.Providers/Fitbit/Provider/FitbitAuthenticationProvider.cs @@ -0,0 +1,50 @@ +using System; +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Fitbit.Provider +{ + /// + /// Default implementation. + /// + public class FitbitAuthenticationProvider : IFitbitAuthenticationProvider + { + /// + /// Initializes a + /// + public FitbitAuthenticationProvider() + { + 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 Fitbit succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + public virtual Task Authenticated(FitbitAuthenticatedContext 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(FitbitReturnEndpointContext context) + { + return OnReturnEndpoint(context); + } + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Fitbit/Provider/FitbitReturnEndpointContext.cs b/Owin.Security.Providers/Fitbit/Provider/FitbitReturnEndpointContext.cs new file mode 100644 index 0000000..1951ddb --- /dev/null +++ b/Owin.Security.Providers/Fitbit/Provider/FitbitReturnEndpointContext.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. + +using Microsoft.Owin; +using Microsoft.Owin.Security; +using Microsoft.Owin.Security.Provider; + +namespace Owin.Security.Providers.Fitbit.Provider +{ + /// + /// Provides context information to middleware providers. + /// + public class FitbitReturnEndpointContext : ReturnEndpointContext + { + /// + /// + /// + /// OWIN environment + /// The authentication ticket + public FitbitReturnEndpointContext( + IOwinContext context, + AuthenticationTicket ticket) + : base(context, ticket) + { + } + } +} diff --git a/Owin.Security.Providers/Fitbit/Provider/IFitbitAuthenticationProvider.cs b/Owin.Security.Providers/Fitbit/Provider/IFitbitAuthenticationProvider.cs new file mode 100644 index 0000000..7d3eca2 --- /dev/null +++ b/Owin.Security.Providers/Fitbit/Provider/IFitbitAuthenticationProvider.cs @@ -0,0 +1,24 @@ +using System.Threading.Tasks; + +namespace Owin.Security.Providers.Fitbit.Provider +{ + /// + /// Specifies callback methods which the invokes to enable developer control over the authentication process. /> + /// + public interface IFitbitAuthenticationProvider + { + /// + /// Invoked whenever Fitbit succesfully authenticates a user + /// + /// Contains information about the login session as well as the user . + /// A representing the completed operation. + Task Authenticated(FitbitAuthenticatedContext 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(FitbitReturnEndpointContext context); + } +} \ No newline at end of file diff --git a/Owin.Security.Providers/Owin.Security.Providers.csproj b/Owin.Security.Providers/Owin.Security.Providers.csproj index 892c561..18aa908 100644 --- a/Owin.Security.Providers/Owin.Security.Providers.csproj +++ b/Owin.Security.Providers/Owin.Security.Providers.csproj @@ -152,6 +152,15 @@ + + + + + + + + + diff --git a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs index 087d8a5..dbdf065 100755 --- a/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs +++ b/OwinOAuthProvidersDemo/App_Start/Startup.Auth.cs @@ -39,6 +39,7 @@ using Owin.Security.Providers.WordPress; using Owin.Security.Providers.Yahoo; using Owin.Security.Providers.Backlog; using Owin.Security.Providers.Vimeo; +using Owin.Security.Providers.Fitbit; namespace OwinOAuthProvidersDemo { @@ -287,6 +288,12 @@ namespace OwinOAuthProvidersDemo //app.UseCosignAuthentication(cosignOptions); //app.UseVimeoAuthentication("", ""); + + //app.UseFitbitAuthentication(new FitbitAuthenticationOptions + //{ + // ClientId = "", + // ClientSecret = "" + //}); } } } diff --git a/README.md b/README.md index 7b2425f..503566e 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Provides a set of extra authentication providers for OWIN ([Project Katana](http - DeviantArt - Dropbox - EVEOnline + - Fitbit - Flickr - Foursquare - GitHub