diff --git a/.gitignore b/.gitignore index 97d3ab6..6dd72a9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,30 @@ -lib/* -bin/Debug/* -src/_ReSharper* -src/packages/* -*.DotSettings.user +[Oo]bj/ +[Bb]in/ +*.user +TestResults/ +*.vspscc +*.vssscc +deploy +deploy/* +*.suo +*.cache +*.docstates +_ReSharper.* +*.csproj.user +*[Rr]e[Ss]harper.user +_ReSharper.* + +packages/ +artifacts/ +msbuild.log +PublishProfiles/ +*.psess +*.vsp +*.pidb +*.userprefs +*DS_Store +*.ncrunchsolution +*.log +*.vspx +*.dbmdl +*.nupkg \ No newline at end of file diff --git a/nuget/SimpleSocialAuth.MVC3.1.0.0-refresh4.nuspec b/nuget/SimpleSocialAuth.MVC3.1.0.0-refresh4.nuspec deleted file mode 100644 index 5138f67..0000000 --- a/nuget/SimpleSocialAuth.MVC3.1.0.0-refresh4.nuspec +++ /dev/null @@ -1,30 +0,0 @@ - - - - 1.0.0-refresh4 - rafek - rafek - http://www.opensource.org/licenses/ms-pl.html - https://github.com/rafek/SimpleSocialAuth - http://i.imgur.com/n1Q5A.png - - - - - - SimpleSocialAuth.MVC3 - false - Super simple and easy to install package that allows web sites creators to seamlessly add OAuth support to their ASP.NET MVC 3 sites. Supporting Twitter, Google and Facebook. - - Profile picture for Facebook fix. - Copyright 2012 - social auth oauth asp.net-mvc - - - - - - - - - \ No newline at end of file diff --git a/nuget/SimpleSocialAuth.MVC3.1.0.1.nuspec b/nuget/SimpleSocialAuth.MVC3.1.0.1.nuspec new file mode 100644 index 0000000..b857136 --- /dev/null +++ b/nuget/SimpleSocialAuth.MVC3.1.0.1.nuspec @@ -0,0 +1,34 @@ + + + + 1.0.1 + rafek, smithkl42 + rafek + http://www.opensource.org/licenses/ms-pl.html + https://github.com/rafek/SimpleSocialAuth + http://i.imgur.com/n1Q5A.png + + + + + + SimpleSocialAuth.MVC3 + false + Super simple and easy to install package that allows web sites creators to seamlessly add OAuth support to their ASP.NET MVC 3 sites. Supporting Twitter, Google and Facebook. + + Profile picture for Facebook fix. + Copyright 2012 + social auth oauth asp.net-mvc + + + + + + + + + + + + + \ No newline at end of file diff --git a/nuget/SimpleSocialAuth.MVC4.1.0.1.nuspec b/nuget/SimpleSocialAuth.MVC4.1.0.1.nuspec new file mode 100644 index 0000000..4ca0084 --- /dev/null +++ b/nuget/SimpleSocialAuth.MVC4.1.0.1.nuspec @@ -0,0 +1,38 @@ + + + + 1.0.10 + rafek, smithkl42 + rafek + http://www.opensource.org/licenses/ms-pl.html + https://github.com/rafek/SimpleSocialAuth + http://i.imgur.com/n1Q5A.png + + + + + + SimpleSocialAuth.MVC4 + false + Super simple and easy to install package that allows web sites creators to seamlessly add OAuth support to their ASP.NET MVC 4 sites. Supporting Twitter, Google and Facebook. + + Adds support for ASP.NET MVC4. + Copyright 2012-2013 + social auth oauth asp.net-mvc + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/nuget/content.common/SimpleAuthController.cs.pp b/nuget/content.common/SimpleAuthController.cs.pp new file mode 100644 index 0000000..c258b93 --- /dev/null +++ b/nuget/content.common/SimpleAuthController.cs.pp @@ -0,0 +1,79 @@ +using System; +using System.Diagnostics; +using System.Web.Mvc; +using System.Web.Security; +using SimpleSocialAuth.Core; +using SimpleSocialAuth.Core.Handlers; + +namespace $rootnamespace$.Controllers +{ + /// + /// Simple scaffolding class for handling OAuth-based authentication. + /// Many scenarios will require that this controller be extended or logic from this + /// controller moved into other classes. + /// + public class SimpleAuthController : Controller + { + public ActionResult LogIn() + { + if (Request.IsAuthenticated) + { + return RedirectToAction("Index", "Home"); + } + Session["ReturnUrl"] = Request.QueryString["returnUrl"]; + return View(); + } + + [HttpPost] + public ActionResult Authenticate(string authType) + { + try + { + var authHandler = AuthHandlerFactory.Create(authType); + var authContext = new PrepareAuthenticationContext( + CurrentContextSession.Instance, + Request.Url, + Url.Action("DoAuth", new { authType })); + string redirectUrl = authHandler.PrepareAuthRequest(authContext); + return Redirect(redirectUrl); + } + catch (Exception ex) + { + Debug.WriteLine("Error calling OAuth provider: " + ex); + TempData["authError"] = ex.Message; + return RedirectToAction("LogIn"); + } + } + + public ActionResult DoAuth(string authType) + { + try + { + var authHandler = AuthHandlerFactory.Create(authType); + var authContext = new ProcessAuthenticationContext(CurrentContextSession.Instance, Request.Url); + var userData = authHandler.ProcessAuthRequest(authContext); + + if (userData == null) + { + TempData["authError"] = "Authentication has failed."; + + return RedirectToAction("LogIn"); + } + + // NOTE: this is just simple usage of setting AuthCookie + // TODO: You may also want to check to see if this user exists in your database, create an entry if they don't, etc. + FormsAuthentication.SetAuthCookie(userData.UserName, true); + + return Session["ReturnUrl"] != null + ? (ActionResult) Redirect((string) Session["ReturnUrl"]) + : RedirectToAction("Index", "Home"); + } + catch (Exception ex) + { + Debug.WriteLine("Error responding to OAuth request: " + ex); + TempData["authError"] = ex.Message; + return RedirectToAction("LogIn"); + } + } + } +} diff --git a/nuget/content/LogIn.cshtml b/nuget/content.mvc3/LogIn.cshtml similarity index 74% rename from nuget/content/LogIn.cshtml rename to nuget/content.mvc3/LogIn.cshtml index 28cb3a9..59ae37b 100644 --- a/nuget/content/LogIn.cshtml +++ b/nuget/content.mvc3/LogIn.cshtml @@ -1,4 +1,6 @@ @using SimpleSocialAuth.MVC3 + + @{ ViewBag.Title = "LogIn"; @@ -6,8 +8,6 @@

LogIn

-@Html.RenderAuthStylesheet() -@Html.RenderAuthScript() @Html.RenderAuthWarnings() @if (TempData["authError"] != null) diff --git a/nuget/content/SimpleAuthController.cs.pp b/nuget/content.mvc3/SimpleAuthController.cs.pp similarity index 98% rename from nuget/content/SimpleAuthController.cs.pp rename to nuget/content.mvc3/SimpleAuthController.cs.pp index d541053..25aa45e 100644 --- a/nuget/content/SimpleAuthController.cs.pp +++ b/nuget/content.mvc3/SimpleAuthController.cs.pp @@ -1,6 +1,7 @@ using System.Web; using System.Web.Mvc; using System.Web.Security; +using SimpleSocialAuth.Core; using SimpleSocialAuth.MVC3; namespace $rootnamespace$.Controllers diff --git a/nuget/content.mvc4/LogIn.cshtml b/nuget/content.mvc4/LogIn.cshtml new file mode 100644 index 0000000..e20c81a --- /dev/null +++ b/nuget/content.mvc4/LogIn.cshtml @@ -0,0 +1,24 @@ +@using SimpleSocialAuth.Mvc4 + +@{ + ViewBag.Title = "LogIn"; +} + +

LogIn

+ +@Styles.Render("~/Content/SimpleSocialAuth") +@Html.RenderAuthWarnings() + +@if (TempData["authError"] != null) +{ +

+ @TempData["authError"] +

+} + +@using (Html.BeginForm("Authenticate", "SimpleAuth", FormMethod.Post, new { id = "authForm" })) +{ + @Html.AuthButtons() +} + +@Scripts.Render("~/Scripts/SimpleSocialAuth") \ No newline at end of file diff --git a/nuget/content.mvc4/SimpleSocialAuthBundleConfig.cs.pp b/nuget/content.mvc4/SimpleSocialAuthBundleConfig.cs.pp new file mode 100644 index 0000000..c91d72f --- /dev/null +++ b/nuget/content.mvc4/SimpleSocialAuthBundleConfig.cs.pp @@ -0,0 +1,16 @@ +using System.Web.Optimization; + +namespace $rootnamespace$.App_Start +{ + public class SimpleSocialAuthBundleConfig + { + public static void RegisterBundles(BundleCollection bundles) + { + bundles.Add(new ScriptBundle("~/scripts/simplesocialauth") + .Include("~/Scripts/simplesocialauth.js")); + + bundles.Add(new StyleBundle("~/content/simplesocialauth") + .Include("~/Content/simplesocialauth.css")); + } + } +} \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/AuthHandlerFactory.cs b/src/SimpleSocialAuth.Core/AuthHandlerFactory.cs index 4394be1..fd94bc1 100644 --- a/src/SimpleSocialAuth.Core/AuthHandlerFactory.cs +++ b/src/SimpleSocialAuth.Core/AuthHandlerFactory.cs @@ -6,57 +6,65 @@ namespace SimpleSocialAuth.Core { - /// - /// Use to produce one of the supported handlers. - /// - /// - public class AuthHandlerFactory - { - private static readonly Dictionary> _handlers = - new Dictionary>(); + /// + /// Use to produce one of the supported handlers. + /// + /// + public class AuthHandlerFactory + { + private static readonly Dictionary> _handlers = + new Dictionary>(); - static AuthHandlerFactory() - { - MapHandlers(); - } + static AuthHandlerFactory() + { + MapHandlers(); + } - private static void MapHandlers() - { - var handlers = - Assembly.GetExecutingAssembly().GetTypes().Where( - x => typeof (IAuthenticationHandler).IsAssignableFrom(x) && !x.IsAbstract && !x.IsInterface); - foreach (var handler in handlers) - { - var key = handler.Name.ToLower().Replace("handler", ""); - var handlerType = handler; - _handlers.Add(key, () => (IAuthenticationHandler) Activator.CreateInstance(handlerType)); - } - } + private static void MapHandlers() + { + var handlers = Assembly + .GetExecutingAssembly() + .GetTypes() + .Where(x => typeof (IAuthenticationHandler).IsAssignableFrom(x) && !x.IsAbstract && !x.IsInterface); + foreach (var handler in handlers) + { + var key = handler.Name.ToLower().Replace("handler", ""); + var handlerType = handler; + _handlers.Add(key, () => (IAuthenticationHandler) Activator.CreateInstance(handlerType)); + } + } - /// - /// Map your own authentication handler. - /// - /// Lower case name such as "facebook" - /// Func used to created the handler. - public static void AddHandler(string key, Func factoryMethod) - { - if (key == null) throw new ArgumentNullException("key"); - if (factoryMethod == null) throw new ArgumentNullException("factoryMethod"); - _handlers[key] = factoryMethod; - } + /// + /// Map your own authentication handler. + /// + /// Lower case name such as "facebook" + /// Func used to created the handler. + public static void AddHandler(string key, Func factoryMethod) + { + if (key == null) throw new ArgumentNullException("key"); + if (factoryMethod == null) throw new ArgumentNullException("factoryMethod"); + _handlers[key] = factoryMethod; + } - /// - /// Create a new handler - /// - /// Lower case name such as "facebook" - /// Handler - public static IAuthenticationHandler Create(string handler) - { - Func factory; - if (!_handlers.TryGetValue(handler, out factory)) - throw new ArgumentOutOfRangeException("handler", handler, "Unknown authentication handler."); + /// + /// Create a new handler + /// + /// Lower case name such as "facebook" + /// Handler + public static IAuthenticationHandler Create(string handler) + { + Func factory; + if (!_handlers.TryGetValue(handler.ToLowerInvariant(), out factory)) + { + string message = "Unknown authentication handler; valid options = "; + foreach (var kvp in _handlers) + { + message += kvp.Key + ", "; + } + throw new ArgumentOutOfRangeException("handler", handler, message); + } - return factory(); - } - } + return factory(); + } + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Consumers/FacebookConsumer.cs b/src/SimpleSocialAuth.Core/Consumers/FacebookConsumer.cs index ff5dee1..fe0d6c3 100644 --- a/src/SimpleSocialAuth.Core/Consumers/FacebookConsumer.cs +++ b/src/SimpleSocialAuth.Core/Consumers/FacebookConsumer.cs @@ -3,20 +3,22 @@ namespace SimpleSocialAuth.Core.Consumers { - internal class FacebookConsumer : WebServerClient - { - private static readonly AuthorizationServerDescription FacebookDescription = - new AuthorizationServerDescription - { - TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"), - AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize") - }; + internal class FacebookConsumer : WebServerClient + { + private static readonly AuthorizationServerDescription FacebookDescription = + new AuthorizationServerDescription + { + TokenEndpoint = new Uri("https://graph.facebook.com/oauth/access_token"), + AuthorizationEndpoint = new Uri("https://graph.facebook.com/oauth/authorize") + }; - public FacebookConsumer() - : base(FacebookDescription) - { - AuthorizationTracker = - new AuthorizationTracker(); - } - } + public FacebookConsumer(string clientIdentifier, string clientSecret) + : base(FacebookDescription, clientIdentifier, clientSecret) + { + AuthorizationTracker = new AuthorizationTracker(); + + // See http://stackoverflow.com/questions/15212959/bad-request-on-processuserauthorization-dotnetopenauth-4-2-2-13055 + ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret); + } + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Consumers/GoogleConsumer.cs b/src/SimpleSocialAuth.Core/Consumers/GoogleConsumer.cs index 5ec1715..7cf7731 100644 --- a/src/SimpleSocialAuth.Core/Consumers/GoogleConsumer.cs +++ b/src/SimpleSocialAuth.Core/Consumers/GoogleConsumer.cs @@ -12,11 +12,13 @@ internal class GoogleConsumer : WebServerClient AuthorizationEndpoint = new Uri("https://accounts.google.com/o/oauth2/auth") }; - public GoogleConsumer() - : base(GoogleDescription) + public GoogleConsumer(string clientIdentifier, string clientSecret) + : base(GoogleDescription, clientIdentifier, clientSecret) { - AuthorizationTracker = - new AuthorizationTracker(); + AuthorizationTracker = new AuthorizationTracker(); + + // See https://groups.google.com/forum/?fromgroups#!topic/dotnetopenid/ibzRfE4TpB0 + ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret); } } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Consumers/TwitterConsumer.cs b/src/SimpleSocialAuth.Core/Consumers/TwitterConsumer.cs index ab90332..c7e30d1 100644 --- a/src/SimpleSocialAuth.Core/Consumers/TwitterConsumer.cs +++ b/src/SimpleSocialAuth.Core/Consumers/TwitterConsumer.cs @@ -6,146 +6,123 @@ namespace SimpleSocialAuth.Core.Consumers { - internal class TwitterConsumer - { - public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = - new ServiceProviderDescription - { - RequestTokenEndpoint = - new MessageReceivingEndpoint( - "http://twitter.com/oauth/request_token", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = - new MessageReceivingEndpoint( - "http://twitter.com/oauth/authenticate", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = - new MessageReceivingEndpoint( - "http://twitter.com/oauth/access_token", - HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = - new ITamperProtectionChannelBindingElement[] - { - new HmacSha1SigningBindingElement() - }, - }; - - private static WebConsumer signInConsumer; - private static readonly object signInConsumerInitLock = new object(); - private readonly ISessionStorage _sessionStorage; - - public TwitterConsumer(ISessionStorage sessionStorage) - { - _sessionStorage = sessionStorage; - } - - private bool IsTwitterConsumerConfigured - { - get - { - return - !string.IsNullOrEmpty(ConfigurationManager.AppSettings["twitterConsumerKey"]) && - !string.IsNullOrEmpty(ConfigurationManager.AppSettings["twitterConsumerSecret"]); - } - } - - private WebConsumer TwitterSignIn - { - get - { - if (signInConsumer == null) - { - lock (signInConsumerInitLock) - { - if (signInConsumer == null) - { - signInConsumer = - new WebConsumer( - SignInWithTwitterServiceDescription, - ShortTermUserSessionTokenManager); - } - } - } - - return signInConsumer; - } - } - - private InMemoryTokenManager ShortTermUserSessionTokenManager - { - get - { - var tokenManager = - (InMemoryTokenManager) _sessionStorage.Load("TwitterShortTermUserSessionTokenManager"); - - if (tokenManager == null) - { - var consumerKey = - ConfigurationManager.AppSettings["twitterConsumerKey"]; - - var consumerSecret = - ConfigurationManager.AppSettings["twitterConsumerSecret"]; - - if (IsTwitterConsumerConfigured) - { - tokenManager = - new InMemoryTokenManager(consumerKey, consumerSecret); - - _sessionStorage.Store("TwitterShortTermUserSessionTokenManager", tokenManager); - } - else - { - throw new InvalidOperationException( - "No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); - } - } - - return - tokenManager; - } - } - - public OutgoingWebResponse StartSignInWithTwitter(Uri callback = null) - { - if (callback == null) - { - callback = - MessagingUtilities - .GetRequestUrlFromContext() - .StripQueryArgumentsWithPrefix("oauth_"); - } - - var request = - TwitterSignIn - .PrepareRequestUserAuthorization(callback, null, null); - - return - TwitterSignIn - .Channel - .PrepareResponse(request); - } - - public bool TryFinishSignInWithTwitter(out string screenName, out int userId) - { - screenName = null; - userId = 0; - - var response = - TwitterSignIn - .ProcessUserAuthorization(); - - if (response == null) - { - return false; - } - - screenName = - response.ExtraData["screen_name"]; - - userId = - int.Parse(response.ExtraData["user_id"]); - - return true; - } - } + internal class TwitterConsumer + { + public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = + new ServiceProviderDescription + { + RequestTokenEndpoint = + new MessageReceivingEndpoint( + "https://twitter.com/oauth/request_token", + HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + UserAuthorizationEndpoint = + new MessageReceivingEndpoint( + "https://twitter.com/oauth/authenticate", + HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + AccessTokenEndpoint = + new MessageReceivingEndpoint( + "https://twitter.com/oauth/access_token", + HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), + TamperProtectionElements = + new ITamperProtectionChannelBindingElement[] + { + new HmacSha1SigningBindingElement() + }, + }; + + private static WebConsumer signInConsumer; + private static readonly object signInConsumerInitLock = new object(); + private readonly ISessionStorage _sessionStorage; + + public TwitterConsumer(ISessionStorage sessionStorage) + { + _sessionStorage = sessionStorage; + } + + private bool IsTwitterConsumerConfigured + { + get + { + return + !string.IsNullOrEmpty(ConfigurationManager.AppSettings["twitterConsumerKey"]) && + !string.IsNullOrEmpty(ConfigurationManager.AppSettings["twitterConsumerSecret"]); + } + } + + private WebConsumer TwitterSignIn + { + get + { + if (signInConsumer == null) + { + lock (signInConsumerInitLock) + { + if (signInConsumer == null) + { + signInConsumer = new WebConsumer(SignInWithTwitterServiceDescription, ShortTermUserSessionTokenManager); + } + } + } + + return signInConsumer; + } + } + + private InMemoryTokenManager ShortTermUserSessionTokenManager + { + get + { + var tokenManager = + (InMemoryTokenManager)_sessionStorage.Load("TwitterShortTermUserSessionTokenManager"); + + if (tokenManager == null) + { + var consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + var consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + + if (IsTwitterConsumerConfigured) + { + tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); + _sessionStorage.Store("TwitterShortTermUserSessionTokenManager", tokenManager); + } + else + { + throw new InvalidOperationException( + "No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); + } + } + + return tokenManager; + } + } + + public OutgoingWebResponse StartSignInWithTwitter(Uri callbackUri = null) + { + if (callbackUri == null) + { + callbackUri = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); + } + + var request = TwitterSignIn.PrepareRequestUserAuthorization(callbackUri, null, null); + + return TwitterSignIn.Channel.PrepareResponse(request); + } + + public bool TryFinishSignInWithTwitter(out string screenName, out int userId) + { + screenName = null; + userId = 0; + + var response = TwitterSignIn.ProcessUserAuthorization(); + + if (response == null) + { + return false; + } + + screenName = response.ExtraData["screen_name"]; + userId = int.Parse(response.ExtraData["user_id"]); + return true; + } + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/CurrentContextSession.cs b/src/SimpleSocialAuth.Core/CurrentContextSession.cs new file mode 100644 index 0000000..9c76453 --- /dev/null +++ b/src/SimpleSocialAuth.Core/CurrentContextSession.cs @@ -0,0 +1,28 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; + +namespace SimpleSocialAuth.Core +{ + public class CurrentContextSession : ISessionStorage + { + + private static CurrentContextSession _instance; + public static CurrentContextSession Instance + { + get { return _instance ?? (_instance = new CurrentContextSession()); } + } + + public object Load(string key) + { + return HttpContext.Current.Session[key]; + } + + public void Store(string key, object value) + { + HttpContext.Current.Session[key] = value; + } + } +} diff --git a/src/SimpleSocialAuth.Core/Handlers/FacebookHandler.cs b/src/SimpleSocialAuth.Core/Handlers/FacebookHandler.cs index fa91603..4677f89 100644 --- a/src/SimpleSocialAuth.Core/Handlers/FacebookHandler.cs +++ b/src/SimpleSocialAuth.Core/Handlers/FacebookHandler.cs @@ -7,68 +7,61 @@ namespace SimpleSocialAuth.Core.Handlers { - public class FacebookHandler : IAuthenticationHandler - { - private static readonly FacebookConsumer facebookConsumer = - new FacebookConsumer - { - ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"], - ClientSecret = ConfigurationManager.AppSettings["facebookAppSecret"] - }; + public class FacebookHandler : IAuthenticationHandler + { + private static readonly FacebookConsumer facebookConsumer = + new FacebookConsumer( + ConfigurationManager.AppSettings["facebookAppID"], + ConfigurationManager.AppSettings["facebookAppSecret"]); - #region IAuthenticationHandler Members + #region IAuthenticationHandler Members - public string PrepareAuthRequest(PrepareAuthenticationContext context) - { - var authorization = - facebookConsumer.ProcessUserAuthorization(); + public string PrepareAuthRequest(PrepareAuthenticationContext context) + { + var authorization = facebookConsumer.ProcessUserAuthorization(); - var callback = - new Uri(Utils.GetUrlBase(context.Request) + context.RedirectPath); + var callback = new Uri(Utils.GetUrlBase(context.RequestUri) + context.RedirectPath); - if (authorization == null) - { - return - facebookConsumer - .PrepareRequestUserAuthorization(returnTo: callback) - .Headers["Location"]; - } + if (authorization == null) + { + return facebookConsumer + .PrepareRequestUserAuthorization(returnTo: callback) + .Headers["Location"]; + } - return null; - } + return null; + } - public BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context) - { - var authorization = - facebookConsumer.ProcessUserAuthorization(); + public BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context) + { + var authorization = facebookConsumer.ProcessUserAuthorization(); - if (authorization.AccessToken == null) - { - return null; - } + if (authorization.AccessToken == null) + { + return null; + } - var graphRequest = - WebRequest - .Create("https://graph.facebook.com/me?access_token=" + - Uri.EscapeDataString(authorization.AccessToken)); + var graphRequest = WebRequest + .Create("https://graph.facebook.com/me?access_token=" + + Uri.EscapeDataString(authorization.AccessToken)); - using (var response = graphRequest.GetResponse()) - using (var responseStream = response.GetResponseStream()) - using (var streamReader = new StreamReader(responseStream)) - { - var json = streamReader.ReadToEnd(); - var jsonObject = JObject.Parse(json); + using (var response = graphRequest.GetResponse()) + using (var responseStream = response.GetResponseStream()) + using (var streamReader = new StreamReader(responseStream)) + { + var json = streamReader.ReadToEnd(); + var jsonObject = JObject.Parse(json); - return - new BasicUserData - { - UserId = jsonObject["id"].ToString(), - UserName = jsonObject["name"].ToString(), - PictureUrl = string.Format("http://graph.facebook.com/{0}/picture", jsonObject["id"]) - }; - } - } + return + new BasicUserData + { + UserId = jsonObject["id"].ToString(), + UserName = jsonObject["name"].ToString(), + PictureUrl = string.Format("http://graph.facebook.com/{0}/picture", jsonObject["id"]) + }; + } + } - #endregion - } + #endregion + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Handlers/GoogleHandler.cs b/src/SimpleSocialAuth.Core/Handlers/GoogleHandler.cs index b66b367..2368d1d 100644 --- a/src/SimpleSocialAuth.Core/Handlers/GoogleHandler.cs +++ b/src/SimpleSocialAuth.Core/Handlers/GoogleHandler.cs @@ -13,22 +13,17 @@ namespace SimpleSocialAuth.Core.Handlers /// Requires that the "googleAppID" and "googleAppSecret" is specified in the appSettings in web/app.config. public class GoogleHandler : IAuthenticationHandler { - private static readonly GoogleConsumer googleConsumer = - new GoogleConsumer - { - ClientIdentifier = ConfigurationManager.AppSettings["googleAppID"], - ClientSecret = ConfigurationManager.AppSettings["googleAppSecret"] - }; + private static readonly GoogleConsumer googleConsumer = new GoogleConsumer( + ConfigurationManager.AppSettings["googleAppID"], + ConfigurationManager.AppSettings["googleAppSecret"]); #region IAuthenticationHandler Members public string PrepareAuthRequest(PrepareAuthenticationContext context) { - var authorization = - googleConsumer.ProcessUserAuthorization(); + var authorization = googleConsumer.ProcessUserAuthorization(); - var callback = - new Uri(Utils.GetUrlBase(context.Request) + context.RedirectPath); + var callback = new Uri(Utils.GetUrlBase(context.RequestUri) + context.RedirectPath); if (authorization == null) { diff --git a/src/SimpleSocialAuth.Core/Handlers/AbstractAuthHandler.cs b/src/SimpleSocialAuth.Core/Handlers/IAuthenticationHandler.cs similarity index 52% rename from src/SimpleSocialAuth.Core/Handlers/AbstractAuthHandler.cs rename to src/SimpleSocialAuth.Core/Handlers/IAuthenticationHandler.cs index 377d5c6..731afe4 100644 --- a/src/SimpleSocialAuth.Core/Handlers/AbstractAuthHandler.cs +++ b/src/SimpleSocialAuth.Core/Handlers/IAuthenticationHandler.cs @@ -1,8 +1,16 @@ -namespace SimpleSocialAuth.Core.Handlers -{ - public interface IAuthenticationHandler - { - string PrepareAuthRequest(PrepareAuthenticationContext context); - BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context); - } +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json.Linq; + +namespace SimpleSocialAuth.Core.Handlers +{ + public interface IAuthenticationHandler + { + string PrepareAuthRequest(PrepareAuthenticationContext context); + BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context); + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Handlers/PrepareAuthenticationContext.cs b/src/SimpleSocialAuth.Core/Handlers/PrepareAuthenticationContext.cs index 3f216c1..8645d29 100644 --- a/src/SimpleSocialAuth.Core/Handlers/PrepareAuthenticationContext.cs +++ b/src/SimpleSocialAuth.Core/Handlers/PrepareAuthenticationContext.cs @@ -1,28 +1,28 @@ +using System; using System.Collections.Generic; namespace SimpleSocialAuth.Core.Handlers { - public class PrepareAuthenticationContext - { - public PrepareAuthenticationContext(IHttpRequest request, ISessionStorage sessionStorage, string redirectPath, - IDictionary parameters) - { - Request = request; - SessionStorage = sessionStorage; - RedirectPath = redirectPath; - Parameters = parameters; - } + public class PrepareAuthenticationContext + { + public PrepareAuthenticationContext(ISessionStorage sessionStorage, Uri requestUri, string redirectPath, IDictionary parameters) + { + RequestUri = requestUri; + SessionStorage = sessionStorage; + RedirectPath = redirectPath; + Parameters = parameters; + } - public PrepareAuthenticationContext(IHttpRequest request, ISessionStorage sessionStorage, string redirectPath) - { - Request = request; - SessionStorage = sessionStorage; - RedirectPath = redirectPath; - } + public PrepareAuthenticationContext(ISessionStorage sessionStorage, Uri requestUri, string redirectPath) + { + RequestUri = requestUri; + SessionStorage = sessionStorage; + RedirectPath = redirectPath; + } - public IHttpRequest Request { get; private set; } - public ISessionStorage SessionStorage { get; private set; } - public string RedirectPath { get; private set; } - public IDictionary Parameters { get; private set; } - } + public Uri RequestUri { get; private set; } + public ISessionStorage SessionStorage { get; private set; } + public string RedirectPath { get; private set; } + public IDictionary Parameters { get; private set; } + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Handlers/ProcessAuthenticationContext.cs b/src/SimpleSocialAuth.Core/Handlers/ProcessAuthenticationContext.cs index 2a6abe0..aa8a04a 100644 --- a/src/SimpleSocialAuth.Core/Handlers/ProcessAuthenticationContext.cs +++ b/src/SimpleSocialAuth.Core/Handlers/ProcessAuthenticationContext.cs @@ -1,14 +1,16 @@ +using System; + namespace SimpleSocialAuth.Core.Handlers { public class ProcessAuthenticationContext { - public ProcessAuthenticationContext(IHttpRequest request, ISessionStorage sessionStorage) + public ProcessAuthenticationContext(ISessionStorage sessionStorage, Uri requestUri) { - Request = request; + RequestUri = requestUri; SessionStorage = sessionStorage; } - public IHttpRequest Request { get; private set; } + public Uri RequestUri { get; private set; } public ISessionStorage SessionStorage { get; private set; } } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Handlers/TwitterHandler.cs b/src/SimpleSocialAuth.Core/Handlers/TwitterHandler.cs index b3d3c3e..cbcea95 100644 --- a/src/SimpleSocialAuth.Core/Handlers/TwitterHandler.cs +++ b/src/SimpleSocialAuth.Core/Handlers/TwitterHandler.cs @@ -4,43 +4,40 @@ namespace SimpleSocialAuth.Core.Handlers { - /// - /// Twitter authentication handler. - /// - /// Required that the following appSettings keys are configured: "twitterConsumerKey" and "twitterConsumerSecret" - public class TwitterHandler : IAuthenticationHandler - { - #region IAuthenticationHandler Members + /// + /// Twitter authentication handler. + /// + /// Required that the following appSettings keys are configured: "twitterConsumerKey" and "twitterConsumerSecret" + public class TwitterHandler : IAuthenticationHandler + { + #region IAuthenticationHandler Members - public string PrepareAuthRequest(PrepareAuthenticationContext context) - { - var callback = - new Uri(Utils.GetUrlBase(context.Request) + context.RedirectPath); + public string PrepareAuthRequest(PrepareAuthenticationContext context) + { + var callback = new Uri(Utils.GetUrlBase(context.RequestUri) + context.RedirectPath); - var consumer = new TwitterConsumer(context.SessionStorage); - return consumer - .StartSignInWithTwitter(callback) - .Headers["Location"]; - } + var consumer = new TwitterConsumer(context.SessionStorage); + return consumer + .StartSignInWithTwitter(callback) + .Headers["Location"]; + } - public BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context) - { - string screenName; - int userId; + public BasicUserData ProcessAuthRequest(ProcessAuthenticationContext context) + { + string screenName; + int userId; - var consumer = new TwitterConsumer(context.SessionStorage); - return - consumer.TryFinishSignInWithTwitter(out screenName, out userId) - ? new BasicUserData - { - UserId = userId.ToString(CultureInfo.InvariantCulture), - UserName = screenName, - PictureUrl = - string.Format("http://api.twitter.com/1/users/profile_image/{0}.png", screenName) - } - : null; - } + var consumer = new TwitterConsumer(context.SessionStorage); + return consumer.TryFinishSignInWithTwitter(out screenName, out userId) + ? new BasicUserData + { + UserId = userId.ToString(CultureInfo.InvariantCulture), + UserName = screenName, + PictureUrl = string.Format("http://api.twitter.com/1/users/profile_image/{0}.png", screenName) + } + : null; + } - #endregion - } + #endregion + } } \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/Properties/AssemblyInfo.cs b/src/SimpleSocialAuth.Core/Properties/AssemblyInfo.cs index 5d374b7..141a635 100644 --- a/src/SimpleSocialAuth.Core/Properties/AssemblyInfo.cs +++ b/src/SimpleSocialAuth.Core/Properties/AssemblyInfo.cs @@ -35,5 +35,5 @@ // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] \ No newline at end of file diff --git a/src/SimpleSocialAuth.Core/SimpleSocialAuth.Core.csproj b/src/SimpleSocialAuth.Core/SimpleSocialAuth.Core.csproj index 0e40c6b..d914b1e 100644 --- a/src/SimpleSocialAuth.Core/SimpleSocialAuth.Core.csproj +++ b/src/SimpleSocialAuth.Core/SimpleSocialAuth.Core.csproj @@ -33,15 +33,99 @@ 4 - - ..\..\lib\DotNetOpenAuth.3.5.0.12037-refresh3\lib\DotNetOpenAuth.dll + + ..\packages\DotNetOpenAuth.Core.4.3.0.13117\lib\net40-full\DotNetOpenAuth.Core.dll - - ..\..\lib\Newtonsoft.Json.4.5.8\lib\net40\Newtonsoft.Json.dll + + ..\packages\DotNetOpenAuth.Core.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.Core.UI.dll + + + ..\packages\DotNetOpenAuth.InfoCard.4.3.0.13117\lib\net40-full\DotNetOpenAuth.InfoCard.dll + + + ..\packages\DotNetOpenAuth.InfoCard.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.InfoCard.UI.dll + + + ..\packages\DotNetOpenAuth.OAuth.Core.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth.dll + + + ..\packages\DotNetOpenAuth.OAuth.Common.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth.Common.dll + + + ..\packages\DotNetOpenAuth.OAuth.Consumer.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth.Consumer.dll + + + ..\packages\DotNetOpenAuth.OAuth.ServiceProvider.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth.ServiceProvider.dll + + + ..\packages\DotNetOpenAuth.OAuth2.Core.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.dll + + + ..\packages\DotNetOpenAuth.OAuth2.AuthorizationServer.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.AuthorizationServer.dll + + + ..\packages\DotNetOpenAuth.OAuth2.Client.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.Client.dll + + + ..\packages\DotNetOpenAuth.OAuth2.Client.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.Client.UI.dll + + + ..\packages\DotNetOpenAuth.OAuth2.ClientAuthorization.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.ClientAuthorization.dll + + + ..\packages\DotNetOpenAuth.OAuth2.ResourceServer.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OAuth2.ResourceServer.dll + + + ..\packages\DotNetOpenAuth.OpenId.Core.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.dll + + + ..\packages\DotNetOpenAuth.OpenId.Provider.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.Provider.dll + + + ..\packages\DotNetOpenAuth.OpenId.Provider.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.Provider.UI.dll + + + ..\packages\DotNetOpenAuth.OpenId.RelyingParty.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.RelyingParty.dll + + + ..\packages\DotNetOpenAuth.OpenId.RelyingParty.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.RelyingParty.UI.dll + + + ..\packages\DotNetOpenAuth.OpenId.Core.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenId.UI.dll + + + ..\packages\DotNetOpenAuth.OpenIdInfoCard.UI.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenIdInfoCard.UI.dll + + + ..\packages\DotNetOpenAuth.OpenIdOAuth.4.3.0.13117\lib\net40-full\DotNetOpenAuth.OpenIdOAuth.dll + + + ..\packages\Newtonsoft.Json.5.0.6\lib\net40\Newtonsoft.Json.dll + + False + ..\packages\Microsoft.Net.Http.2.1.10\lib\net40\System.Net.Http.dll + + + ..\packages\Microsoft.Net.Http.2.1.10\lib\net40\System.Net.Http.Extensions.dll + + + ..\packages\Microsoft.Net.Http.2.1.10\lib\net40\System.Net.Http.Primitives.dll + + + False + ..\packages\Microsoft.Net.Http.2.1.10\lib\net40\System.Net.Http.WebRequest.dll + + + ..\packages\Microsoft.Bcl.1.0.19\lib\net40\System.Runtime.dll + + + ..\packages\Microsoft.Bcl.1.0.19\lib\net40\System.Threading.Tasks.dll + + @@ -54,9 +138,10 @@ + - + @@ -70,9 +155,7 @@ - - - +