diff options
Diffstat (limited to 'samples/DotNetOpenAuth.ApplicationBlock')
5 files changed, 162 insertions, 373 deletions
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj index 9f74693..19f26b5 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj +++ b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj @@ -101,9 +101,6 @@ <Compile Include="GoogleConsumer.cs" /> <Compile Include="HttpAsyncHandlerBase.cs" /> <Compile Include="InMemoryClientAuthorizationTracker.cs" /> - <Compile Include="InMemoryTokenManager.cs"> - <SubType>Code</SubType> - </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> <Compile Include="TwitterConsumer.cs" /> <Compile Include="Util.cs" /> @@ -138,6 +135,10 @@ <Project>{60426312-6AE5-4835-8667-37EDEA670222}</Project> <Name>DotNetOpenAuth.Core</Name> </ProjectReference> + <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth.Common\DotNetOpenAuth.OAuth.Common.csproj"> + <Project>{115217c5-22cd-415c-a292-0dd0238cdd89}</Project> + <Name>DotNetOpenAuth.OAuth.Common</Name> + </ProjectReference> <ProjectReference Include="..\..\src\DotNetOpenAuth.OAuth.Consumer\DotNetOpenAuth.OAuth.Consumer.csproj"> <Project>{B202E40D-4663-4A2B-ACDA-865F88FF7CAA}</Project> <Name>DotNetOpenAuth.OAuth.Consumer</Name> diff --git a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs index cd3c5fe..def378f 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs @@ -4,10 +4,10 @@ // </copyright> //----------------------------------------------------------------------- -namespace DotNetOpenAuth.ApplicationBlock -{ +namespace DotNetOpenAuth.ApplicationBlock { using System; using System.Collections.Generic; + using System.Configuration; using System.Diagnostics; using System.Globalization; using System.IO; @@ -20,6 +20,7 @@ namespace DotNetOpenAuth.ApplicationBlock using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; + using System.Web; using System.Xml; using System.Xml.Linq; using DotNetOpenAuth.Messaging; @@ -29,17 +30,15 @@ namespace DotNetOpenAuth.ApplicationBlock /// <summary> /// A consumer capable of communicating with Google Data APIs. /// </summary> - public static class GoogleConsumer - { + public class GoogleConsumer : Consumer { /// <summary> /// The Consumer to use for accessing Google data APIs. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription ServiceDescription = + new ServiceProviderDescription( + "https://www.google.com/accounts/OAuthGetRequestToken", + "https://www.google.com/accounts/OAuthAuthorizeToken", + "https://www.google.com/accounts/OAuthGetAccessToken"); /// <summary> /// A mapping between Google's applications and their URI scope values. @@ -69,11 +68,22 @@ namespace DotNetOpenAuth.ApplicationBlock private static readonly Uri GetContactsEndpoint = new Uri("http://www.google.com/m8/feeds/contacts/default/full/"); /// <summary> + /// Initializes a new instance of the <see cref="GoogleConsumer"/> class. + /// </summary> + public GoogleConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); + } + + /// <summary> /// The many specific authorization scopes Google offers. /// </summary> [Flags] - public enum Applications : long - { + public enum Applications : long { /// <summary> /// The Gmail address book. /// </summary> @@ -156,74 +166,33 @@ namespace DotNetOpenAuth.ApplicationBlock } /// <summary> - /// The service description to use for accessing Google data APIs using an X509 certificate. + /// Gets the scope URI in Google's format. /// </summary> - /// <param name="signingCertificate">The signing certificate.</param> - /// <returns>A service description that can be used to create an instance of - /// <see cref="DesktopConsumer"/> or <see cref="WebConsumer"/>. </returns> - public static ServiceProviderDescription CreateRsaSha1ServiceDescription(X509Certificate2 signingCertificate) { - if (signingCertificate == null) { - throw new ArgumentNullException("signingCertificate"); - } - - return new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetRequestToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthAuthorizeToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.google.com/accounts/OAuthGetAccessToken", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new RsaSha1ConsumerSigningBindingElement(signingCertificate) }, - }; + /// <param name="scope">The scope, which may include one or several Google applications.</param> + /// <returns>A space-delimited list of URIs for the requested Google applications.</returns> + public static string GetScopeUri(Applications scope) { + return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray()); } /// <summary> /// Requests authorization from Google to access data from a set of Google applications. /// </summary> - /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer" /> or <see cref="CreateDesktopConsumer" />.</param> /// <param name="requestedAccessScope">The requested access scope.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A task that completes with the asynchronous operation. /// </returns> - /// <exception cref="System.ArgumentNullException">consumer</exception> - public static async Task RequestAuthorizationAsync(WebConsumer consumer, Applications requestedAccessScope, CancellationToken cancellationToken = default(CancellationToken)) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - + public Task<Uri> RequestUserAuthorizationAsync(Applications requestedAccessScope, CancellationToken cancellationToken = default(CancellationToken)) { var extraParameters = new Dictionary<string, string> { { "scope", GetScopeUri(requestedAccessScope) }, }; Uri callback = Util.GetCallbackUrlFromContext(); - var request = await consumer.PrepareRequestUserAuthorizationAsync(callback, extraParameters, null, cancellationToken); - var redirectingResponse = await consumer.Channel.PrepareResponseAsync(request, cancellationToken); - redirectingResponse.Send(); - } - - /// <summary> - /// Requests authorization from Google to access data from a set of Google applications. - /// </summary> - /// <param name="consumer">The Google consumer previously constructed using <see cref="CreateWebConsumer" /> or <see cref="CreateDesktopConsumer" />.</param> - /// <param name="requestedAccessScope">The requested access scope.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// The URI to redirect to and the request token. - /// </returns> - /// <exception cref="System.ArgumentNullException">consumer</exception> - public static Task<Tuple<Uri, string>> RequestAuthorizationAsync(DesktopConsumer consumer, Applications requestedAccessScope, CancellationToken cancellationToken = default(CancellationToken)) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - - var extraParameters = new Dictionary<string, string> { - { "scope", GetScopeUri(requestedAccessScope) }, - }; - - return consumer.RequestUserAuthorizationAsync(extraParameters, null, cancellationToken); + return this.RequestUserAuthorizationAsync(callback, extraParameters, cancellationToken); } /// <summary> /// Gets the Gmail address book's contents. /// </summary> - /// <param name="consumer">The Google consumer.</param> /// <param name="accessToken">The access token previously retrieved.</param> /// <param name="maxResults">The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number here.</param> /// <param name="startIndex">The 1-based index of the first result to be retrieved (for paging).</param> @@ -231,15 +200,10 @@ namespace DotNetOpenAuth.ApplicationBlock /// <returns> /// An XML document returned by Google. /// </returns> - /// <exception cref="System.ArgumentNullException">consumer</exception> - public static async Task<XDocument> GetContactsAsync(ConsumerBase consumer, string accessToken, int maxResults = 25, int startIndex = 1, CancellationToken cancellationToken = default(CancellationToken)) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); - } - + public async Task<XDocument> GetContactsAsync(AccessToken accessToken, int maxResults = 25, int startIndex = 1, CancellationToken cancellationToken = default(CancellationToken)) { // Enable gzip compression. Google only compresses the response for recognized user agent headers. - Mike Lim var handler = new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }; - using (var httpClient = consumer.CreateHttpClient(accessToken, handler)) { + using (var httpClient = this.CreateHttpClient(accessToken, handler)) { var request = new HttpRequestMessage(HttpMethod.Get, GetContactsEndpoint); request.Content = new FormUrlEncodedContent( new Dictionary<string, string>() { @@ -255,7 +219,7 @@ namespace DotNetOpenAuth.ApplicationBlock } } - public static async Task PostBlogEntryAsync(ConsumerBase consumer, string accessToken, string blogUrl, string title, XElement body, CancellationToken cancellationToken) { + public async Task PostBlogEntryAsync(AccessToken accessToken, string blogUrl, string title, XElement body, CancellationToken cancellationToken) { string feedUrl; var getBlogHome = WebRequest.Create(blogUrl); using (var blogHomeResponse = getBlogHome.GetResponse()) { @@ -285,7 +249,7 @@ namespace DotNetOpenAuth.ApplicationBlock var request = new HttpRequestMessage(HttpMethod.Post, feedUrl); request.Content = new StreamContent(ms); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/atom+xml"); - using (var httpClient = consumer.CreateHttpClient(accessToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (var response = await httpClient.SendAsync(request, cancellationToken)) { if (response.StatusCode == HttpStatusCode.Created) { // Success @@ -296,14 +260,5 @@ namespace DotNetOpenAuth.ApplicationBlock } } } - - /// <summary> - /// Gets the scope URI in Google's format. - /// </summary> - /// <param name="scope">The scope, which may include one or several Google applications.</param> - /// <returns>A space-delimited list of URIs for the requested Google applications.</returns> - public static string GetScopeUri(Applications scope) { - return string.Join(" ", Util.GetIndividualFlags(scope).Select(app => DataScopeUris[(Applications)app]).ToArray()); - } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs b/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs deleted file mode 100644 index 35f6c08..0000000 --- a/samples/DotNetOpenAuth.ApplicationBlock/InMemoryTokenManager.cs +++ /dev/null @@ -1,147 +0,0 @@ -//----------------------------------------------------------------------- -// <copyright file="InMemoryTokenManager.cs" company="Outercurve Foundation"> -// Copyright (c) Outercurve Foundation. All rights reserved. -// </copyright> -//----------------------------------------------------------------------- - -namespace DotNetOpenAuth.ApplicationBlock { - using System; - using System.Collections.Generic; - using System.Diagnostics; - using DotNetOpenAuth.OAuth.ChannelElements; - using DotNetOpenAuth.OAuth.Messages; - using DotNetOpenAuth.OpenId.Extensions.OAuth; - -#if SAMPLESONLY - /// <summary> - /// A token manager that only retains tokens in memory. - /// Meant for SHORT TERM USE TOKENS ONLY. - /// </summary> - /// <remarks> - /// A likely application of this class is for "Sign In With Twitter", - /// where the user only signs in without providing any authorization to access - /// Twitter APIs except to authenticate, since that access token is only useful once. - /// </remarks> - internal class InMemoryTokenManager : IConsumerTokenManager, IOpenIdOAuthTokenManager { - private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); - - /// <summary> - /// Initializes a new instance of the <see cref="InMemoryTokenManager"/> class. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <param name="consumerSecret">The consumer secret.</param> - public InMemoryTokenManager(string consumerKey, string consumerSecret) { - if (string.IsNullOrEmpty(consumerKey)) { - throw new ArgumentNullException("consumerKey"); - } - - this.ConsumerKey = consumerKey; - this.ConsumerSecret = consumerSecret; - } - - /// <summary> - /// Gets the consumer key. - /// </summary> - /// <value>The consumer key.</value> - public string ConsumerKey { get; private set; } - - /// <summary> - /// Gets the consumer secret. - /// </summary> - /// <value>The consumer secret.</value> - public string ConsumerSecret { get; private set; } - - #region ITokenManager Members - - /// <summary> - /// Gets the Token Secret given a request or access token. - /// </summary> - /// <param name="token">The request or access token.</param> - /// <returns> - /// The secret associated with the given token. - /// </returns> - /// <exception cref="ArgumentException">Thrown if the secret cannot be found for the given token.</exception> - public string GetTokenSecret(string token) { - return this.tokensAndSecrets[token]; - } - - /// <summary> - /// Stores a newly generated unauthorized request token, secret, and optional - /// application-specific parameters for later recall. - /// </summary> - /// <param name="request">The request message that resulted in the generation of a new unauthorized request token.</param> - /// <param name="response">The response message that includes the unauthorized request token.</param> - /// <exception cref="ArgumentException">Thrown if the consumer key is not registered, or a required parameter was not found in the parameters collection.</exception> - /// <remarks> - /// Request tokens stored by this method SHOULD NOT associate any user account with this token. - /// It usually opens up security holes in your application to do so. Instead, you associate a user - /// account with access tokens (not request tokens) in the <see cref="ExpireRequestTokenAndStoreNewAccessToken"/> - /// method. - /// </remarks> - public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { - this.tokensAndSecrets[response.Token] = response.TokenSecret; - } - - /// <summary> - /// Deletes a request token and its associated secret and stores a new access token and secret. - /// </summary> - /// <param name="consumerKey">The Consumer that is exchanging its request token for an access token.</param> - /// <param name="requestToken">The Consumer's request token that should be deleted/expired.</param> - /// <param name="accessToken">The new access token that is being issued to the Consumer.</param> - /// <param name="accessTokenSecret">The secret associated with the newly issued access token.</param> - /// <remarks> - /// <para> - /// Any scope of granted privileges associated with the request token from the - /// original call to <see cref="StoreNewRequestToken"/> should be carried over - /// to the new Access Token. - /// </para> - /// <para> - /// To associate a user account with the new access token, - /// <see cref="System.Web.HttpContext.User">HttpContext.Current.User</see> may be - /// useful in an ASP.NET web application within the implementation of this method. - /// Alternatively you may store the access token here without associating with a user account, - /// and wait until <see cref="WebConsumer.ProcessUserAuthorization()"/> or - /// <see cref="DesktopConsumer.ProcessUserAuthorization(string, string)"/> return the access - /// token to associate the access token with a user account at that point. - /// </para> - /// </remarks> - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { - this.tokensAndSecrets.Remove(requestToken); - this.tokensAndSecrets[accessToken] = accessTokenSecret; - } - - /// <summary> - /// Classifies a token as a request token or an access token. - /// </summary> - /// <param name="token">The token to classify.</param> - /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> - public TokenType GetTokenType(string token) { - throw new NotImplementedException(); - } - - #endregion - - #region IOpenIdOAuthTokenManager Members - - /// <summary> - /// Stores a new request token obtained over an OpenID request. - /// </summary> - /// <param name="consumerKey">The consumer key.</param> - /// <param name="authorization">The authorization message carrying the request token and authorized access scope.</param> - /// <remarks> - /// <para>The token secret is the empty string.</para> - /// <para>Tokens stored by this method should be short-lived to mitigate - /// possible security threats. Their lifetime should be sufficient for the - /// relying party to receive the positive authentication assertion and immediately - /// send a follow-up request for the access token.</para> - /// </remarks> - public void StoreOpenIdAuthorizedRequestToken(string consumerKey, AuthorizationApprovedResponse authorization) { - this.tokensAndSecrets[authorization.RequestToken] = string.Empty; - } - - #endregion - } -#else -#error The InMemoryTokenManager class is only for samples as it forgets all tokens whenever the application restarts! You should implement IConsumerTokenManager in your own app that stores tokens in a persistent store (like a SQL database). -#endif -}
\ No newline at end of file diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs index e665d96..bb6f9d3 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs @@ -30,27 +30,23 @@ namespace DotNetOpenAuth.ApplicationBlock { /// <summary> /// A consumer capable of communicating with Twitter. /// </summary> - public static class TwitterConsumer { + public class TwitterConsumer : Consumer { /// <summary> /// The description of Twitter's OAuth protocol URIs for use with actually reading/writing /// a user's private Twitter data. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/request_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/authorize", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("http://twitter.com/oauth/access_token", HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, - }; + public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/authorize", + "https://api.twitter.com/oauth/access_token"); /// <summary> /// The description of Twitter's OAuth protocol URIs for use with their "Sign in with Twitter" feature. /// </summary> - 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() }, - }; + public static readonly ServiceProviderDescription SignInWithTwitterServiceDescription = new ServiceProviderDescription( + "https://api.twitter.com/oauth/request_token", + "https://api.twitter.com/oauth/authenticate", + "https://api.twitter.com/oauth/access_token"); /// <summary> /// The URI to get a user's favorites. @@ -69,21 +65,26 @@ namespace DotNetOpenAuth.ApplicationBlock { private static readonly Uri VerifyCredentialsEndpoint = new Uri("http://api.twitter.com/1/account/verify_credentials.xml"); /// <summary> - /// The consumer used for the Sign in to Twitter feature. + /// Initializes a new instance of the <see cref="TwitterConsumer"/> class. /// </summary> - private static WebConsumer signInConsumer; - - /// <summary> - /// The lock acquired to initialize the <see cref="signInConsumer"/> field. - /// </summary> - private static object signInConsumerInitLock = new object(); + public TwitterConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); + } /// <summary> - /// Initializes static members of the <see cref="TwitterConsumer"/> class. + /// Initializes a new instance of the <see cref="TwitterConsumer"/> class. /// </summary> - static TwitterConsumer() { - // Twitter can't handle the Expect 100 Continue HTTP header. - ServicePointManager.FindServicePoint(GetFavoritesEndpoint).Expect100Continue = false; + /// <param name="consumerKey">The consumer key.</param> + /// <param name="consumerSecret">The consumer secret.</param> + public TwitterConsumer(string consumerKey, string consumerSecret) + : this() { + this.ConsumerKey = consumerKey; + this.ConsumerSecret = consumerSecret; } /// <summary> @@ -96,46 +97,69 @@ namespace DotNetOpenAuth.ApplicationBlock { } } + public static Consumer CreateConsumer(bool forWeb = true) { + string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + if (IsTwitterConsumerConfigured) { + ITemporaryCredentialStorage storage = forWeb ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() : new MemoryTemporaryCredentialStorage(); + return new Consumer(consumerKey, consumerSecret, ServiceDescription, storage) { + HostFactories = new TwitterHostFactories(), + }; + } else { + throw new InvalidOperationException("No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); + } + } + /// <summary> - /// Gets the consumer to use for the Sign in to Twitter feature. + /// Prepares a redirect that will send the user to Twitter to sign in. /// </summary> - /// <value>The twitter sign in.</value> - private static WebConsumer TwitterSignIn { - get { - if (signInConsumer == null) { - lock (signInConsumerInitLock) { - if (signInConsumer == null) { - signInConsumer = new WebConsumer(SignInWithTwitterServiceDescription, ShortTermUserSessionTokenManager); - } - } - } - - return signInConsumer; + /// <param name="forceNewLogin">if set to <c>true</c> the user will be required to re-enter their Twitter credentials even if already logged in to Twitter.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// The redirect message. + /// </returns> + /// <remarks> + /// Call <see cref="OutgoingWebResponse.Send" /> or + /// <c>return StartSignInWithTwitter().<see cref="MessagingUtilities.AsActionResult">AsActionResult()</see></c> + /// to actually perform the redirect. + /// </remarks> + public static async Task<Uri> StartSignInWithTwitterAsync(bool forceNewLogin = false, CancellationToken cancellationToken = default(CancellationToken)) { + var redirectParameters = new Dictionary<string, string>(); + if (forceNewLogin) { + redirectParameters["force_login"] = "true"; } - } + Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); - private static InMemoryTokenManager ShortTermUserSessionTokenManager { - get { - var store = HttpContext.Current.Session; - var tokenManager = (InMemoryTokenManager)store["TwitterShortTermUserSessionTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; - if (IsTwitterConsumerConfigured) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - store["TwitterShortTermUserSessionTokenManager"] = tokenManager; - } else { - throw new InvalidOperationException("No Twitter OAuth consumer key and secret could be found in web.config AppSettings."); - } - } + var consumer = CreateConsumer(); + consumer.ServiceProvider = SignInWithTwitterServiceDescription; + Uri redirectUrl = await consumer.RequestUserAuthorizationAsync(callback, cancellationToken: cancellationToken); + return redirectUrl; + } - return tokenManager; + /// <summary> + /// Checks the incoming web request to see if it carries a Twitter authentication response, + /// and provides the user's Twitter screen name and unique id if available. + /// </summary> + /// <param name="completeUrl">The URL that came back from the service provider to complete the authorization.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns> + /// A tuple with the screen name and Twitter unique user ID if successful; otherwise <c>null</c>. + /// </returns> + public static async Task<Tuple<string, int>> TryFinishSignInWithTwitterAsync(Uri completeUrl = null, CancellationToken cancellationToken = default(CancellationToken)) { + var consumer = CreateConsumer(); + consumer.ServiceProvider = SignInWithTwitterServiceDescription; + var response = await consumer.ProcessUserAuthorizationAsync(completeUrl ?? HttpContext.Current.Request.Url, cancellationToken: cancellationToken); + if (response == null) { + return null; } + + string screenName = response.ExtraData["screen_name"]; + int userId = int.Parse(response.ExtraData["user_id"]); + return Tuple.Create(screenName, userId); } - public static async Task<JArray> GetUpdatesAsync( - ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - using (var httpClient = twitter.CreateHttpClient(accessToken)) { + public async Task<JArray> GetUpdatesAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (var response = await httpClient.GetAsync(GetFriendTimelineStatusEndpoint, cancellationToken)) { response.EnsureSuccessStatusCode(); string jsonString = await response.Content.ReadAsStringAsync(); @@ -145,8 +169,8 @@ namespace DotNetOpenAuth.ApplicationBlock { } } - public static async Task<XDocument> GetFavorites(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - using (var httpClient = twitter.CreateHttpClient(accessToken)) { + public async Task<XDocument> GetFavorites(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (HttpResponseMessage response = await httpClient.GetAsync(GetFavoritesEndpoint, cancellationToken)) { response.EnsureSuccessStatusCode(); return XDocument.Parse(await response.Content.ReadAsStringAsync()); @@ -154,7 +178,7 @@ namespace DotNetOpenAuth.ApplicationBlock { } } - public static async Task<XDocument> UpdateProfileBackgroundImageAsync(ConsumerBase twitter, string accessToken, string image, bool tile, CancellationToken cancellationToken) { + public async Task<XDocument> UpdateProfileBackgroundImageAsync(AccessToken accessToken, string image, bool tile, CancellationToken cancellationToken) { var imageAttachment = new StreamContent(File.OpenRead(image)); imageAttachment.Headers.ContentType = new MediaTypeHeaderValue("image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileBackgroundImageEndpoint); @@ -163,7 +187,7 @@ namespace DotNetOpenAuth.ApplicationBlock { content.Add(new StringContent(tile.ToString().ToLowerInvariant()), "tile"); request.Content = content; request.Headers.ExpectContinue = false; - using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { response.EnsureSuccessStatusCode(); string responseString = await response.Content.ReadAsStringAsync(); @@ -172,19 +196,19 @@ namespace DotNetOpenAuth.ApplicationBlock { } } - public static Task<XDocument> UpdateProfileImageAsync(ConsumerBase twitter, string accessToken, string pathToImage, CancellationToken cancellationToken = default(CancellationToken)) { + public Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, string pathToImage, CancellationToken cancellationToken = default(CancellationToken)) { string contentType = "image/" + Path.GetExtension(pathToImage).Substring(1).ToLowerInvariant(); - return UpdateProfileImageAsync(twitter, accessToken, File.OpenRead(pathToImage), contentType, cancellationToken); + return this.UpdateProfileImageAsync(accessToken, File.OpenRead(pathToImage), contentType, cancellationToken); } - public static async Task<XDocument> UpdateProfileImageAsync(ConsumerBase twitter, string accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) { + public async Task<XDocument> UpdateProfileImageAsync(AccessToken accessToken, Stream image, string contentType, CancellationToken cancellationToken = default(CancellationToken)) { var imageAttachment = new StreamContent(image); imageAttachment.Headers.ContentType = new MediaTypeHeaderValue(contentType); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UpdateProfileImageEndpoint); var content = new MultipartFormDataContent(); content.Add(imageAttachment, "image", "twitterPhoto"); request.Content = content; - using (var httpClient = twitter.CreateHttpClient(accessToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (HttpResponseMessage response = await httpClient.SendAsync(request, cancellationToken)) { response.EnsureSuccessStatusCode(); string responseString = await response.Content.ReadAsStringAsync(); @@ -193,8 +217,8 @@ namespace DotNetOpenAuth.ApplicationBlock { } } - public static async Task<XDocument> VerifyCredentialsAsync(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - using (var httpClient = twitter.CreateHttpClient(accessToken)) { + public async Task<XDocument> VerifyCredentialsAsync(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + using (var httpClient = this.CreateHttpClient(accessToken)) { using (var response = await httpClient.GetAsync(VerifyCredentialsEndpoint, cancellationToken)) { response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync()) { @@ -204,57 +228,26 @@ namespace DotNetOpenAuth.ApplicationBlock { } } - public static async Task<string> GetUsername(ConsumerBase twitter, string accessToken, CancellationToken cancellationToken = default(CancellationToken)) { - XDocument xml = await VerifyCredentialsAsync(twitter, accessToken, cancellationToken); + public async Task<string> GetUsername(AccessToken accessToken, CancellationToken cancellationToken = default(CancellationToken)) { + XDocument xml = await this.VerifyCredentialsAsync(accessToken, cancellationToken); XPathNavigator nav = xml.CreateNavigator(); return nav.SelectSingleNode("/user/screen_name").Value; } - /// <summary> - /// Prepares a redirect that will send the user to Twitter to sign in. - /// </summary> - /// <param name="forceNewLogin">if set to <c>true</c> the user will be required to re-enter their Twitter credentials even if already logged in to Twitter.</param> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// The redirect message. - /// </returns> - /// <remarks> - /// Call <see cref="OutgoingWebResponse.Send" /> or - /// <c>return StartSignInWithTwitter().<see cref="MessagingUtilities.AsActionResult">AsActionResult()</see></c> - /// to actually perform the redirect. - /// </remarks> - public static async Task<HttpResponseMessage> StartSignInWithTwitterAsync(bool forceNewLogin = false, CancellationToken cancellationToken = default(CancellationToken)) { - var redirectParameters = new Dictionary<string, string>(); - if (forceNewLogin) { - redirectParameters["force_login"] = "true"; - } - Uri callback = MessagingUtilities.GetRequestUrlFromContext().StripQueryArgumentsWithPrefix("oauth_"); - var request = await TwitterSignIn.PrepareRequestUserAuthorizationAsync(callback, null, redirectParameters, cancellationToken); - return await TwitterSignIn.Channel.PrepareResponseAsync(request, cancellationToken); - } + private class TwitterHostFactories : IHostFactories { + private static readonly IHostFactories underlyingFactories = new DefaultOAuthHostFactories(); - /// <summary> - /// Checks the incoming web request to see if it carries a Twitter authentication response, - /// and provides the user's Twitter screen name and unique id if available. - /// </summary> - /// <param name="cancellationToken">The cancellation token.</param> - /// <returns> - /// A tuple with the screen name and Twitter unique user ID if successful; otherwise <c>null</c>. - /// </returns> - public static async Task<Tuple<string, int>> TryFinishSignInWithTwitterAsync(CancellationToken cancellationToken = default(CancellationToken)) { - var response = await TwitterSignIn.ProcessUserAuthorizationAsync(cancellationToken: cancellationToken); - if (response == null) { - return null; + public HttpMessageHandler CreateHttpMessageHandler() { + return new WebRequestHandler(); } - string screenName = response.ExtraData["screen_name"]; - int userId = int.Parse(response.ExtraData["user_id"]); - - // If we were going to make this LOOK like OpenID even though it isn't, - // this seems like a reasonable, secure claimed id to allow the user to assume. - ////OpenId.Identifier fake_claimed_id = string.Format(CultureInfo.InvariantCulture, "http://twitter.com/{0}#{1}", screenName, userId); + public HttpClient CreateHttpClient(HttpMessageHandler handler = null) { + var client = underlyingFactories.CreateHttpClient(handler); - return Tuple.Create(screenName, userId); + // Twitter can't handle the Expect 100 Continue HTTP header. + client.DefaultRequestHeaders.ExpectContinue = false; + return client; + } } } } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs index cedcbf7..1dff5b6 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/YammerConsumer.cs @@ -4,61 +4,48 @@ // </copyright> //----------------------------------------------------------------------- -namespace DotNetOpenAuth.ApplicationBlock -{ +namespace DotNetOpenAuth.ApplicationBlock { using System; using System.Collections.Generic; + using System.Configuration; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; + using System.Web; using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; - public static class YammerConsumer - { + public class YammerConsumer : Consumer { /// <summary> /// The Consumer to use for accessing Google data APIs. /// </summary> - public static readonly ServiceProviderDescription ServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/request_token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - UserAuthorizationEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/authorize", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.GetRequest), - AccessTokenEndpoint = new MessageReceivingEndpoint("https://www.yammer.com/oauth/access_token", HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new PlaintextSigningBindingElement() }, - ProtocolVersion = ProtocolVersion.V10, - }; + public static readonly ServiceProviderDescription ServiceDescription = + new ServiceProviderDescription( + "https://www.yammer.com/oauth/request_token", + "https://www.yammer.com/oauth/authorize", + "https://www.yammer.com/oauth/access_token"); - public static DesktopConsumer CreateConsumer(IConsumerTokenManager tokenManager) { - return new DesktopConsumer(ServiceDescription, tokenManager); + public YammerConsumer() { + this.ServiceProvider = ServiceDescription; + this.ConsumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"]; + this.ConsumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"]; + this.TemporaryCredentialStorage = HttpContext.Current != null + ? (ITemporaryCredentialStorage)new CookieTemporaryCredentialStorage() + : new MemoryTemporaryCredentialStorage(); } - public static Task<Tuple<Uri, string>> PrepareRequestAuthorizationAsync(DesktopConsumer consumer, CancellationToken cancellationToken = default(CancellationToken)) { - if (consumer == null) { - throw new ArgumentNullException("consumer"); + /// <summary> + /// Gets a value indicating whether the Twitter consumer key and secret are set in the web.config file. + /// </summary> + public static bool IsConsumerConfigured { + get { + return !string.IsNullOrEmpty(ConfigurationManager.AppSettings["yammerConsumerKey"]) && + !string.IsNullOrEmpty(ConfigurationManager.AppSettings["yammerConsumerSecret"]); } - - return consumer.RequestUserAuthorizationAsync(null, null, cancellationToken); - } - - public static async Task<AuthorizedTokenResponse> CompleteAuthorizationAsync(DesktopConsumer consumer, string requestToken, string userCode, CancellationToken cancellationToken = default(CancellationToken)) { - // Because Yammer has a proprietary callback_token parameter, and it's passed - // with the message that specifically bans extra arguments being passed, we have - // to cheat by adding the data to the URL itself here. - var customServiceDescription = new ServiceProviderDescription { - RequestTokenEndpoint = ServiceDescription.RequestTokenEndpoint, - UserAuthorizationEndpoint = ServiceDescription.UserAuthorizationEndpoint, - AccessTokenEndpoint = new MessageReceivingEndpoint(ServiceDescription.AccessTokenEndpoint.Location.AbsoluteUri + "?oauth_verifier=" + Uri.EscapeDataString(userCode), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), - TamperProtectionElements = ServiceDescription.TamperProtectionElements, - ProtocolVersion = ProtocolVersion.V10, - }; - - // To use a custom service description we also must create a new WebConsumer. - var customConsumer = new DesktopConsumer(customServiceDescription, consumer.TokenManager); - var response = await customConsumer.ProcessUserAuthorizationAsync(requestToken, userCode, cancellationToken); - return response; } } } |