diff options
Diffstat (limited to 'samples')
28 files changed, 368 insertions, 145 deletions
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj index 590b96b..626dbaa 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj +++ b/samples/DotNetOpenAuth.ApplicationBlock/DotNetOpenAuth.ApplicationBlock.csproj @@ -57,6 +57,7 @@ <ItemGroup> <Compile Include="GoogleConsumer.cs" /> <Compile Include="Properties\AssemblyInfo.cs" /> + <Compile Include="TwitterConsumer.cs" /> <Compile Include="Util.cs" /> </ItemGroup> <ItemGroup> diff --git a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs index c6f2b89..f0a4c03 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/GoogleConsumer.cs @@ -11,6 +11,7 @@ namespace DotNetOpenAuth.ApplicationBlock { using System.IO; using System.Linq; using System.Net; + using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Xml; @@ -26,7 +27,7 @@ namespace DotNetOpenAuth.ApplicationBlock { /// <summary> /// The Consumer to use for accessing Google data APIs. /// </summary> - private static readonly ServiceProviderDescription GoogleDescription = new ServiceProviderDescription { + 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), @@ -69,26 +70,21 @@ namespace DotNetOpenAuth.ApplicationBlock { } /// <summary> - /// Initializes a new instance of the <see cref="WebConsumer"/> class that is prepared to communicate with Google. + /// The service description to use for accessing Google data APIs using an X509 certificate. /// </summary> - /// <param name="tokenManager">The token manager.</param> - /// <param name="consumerKey">The consumer key.</param> - /// <returns>The newly instantiated <see cref="WebConsumer"/>.</returns> - public static WebConsumer CreateWebConsumer(ITokenManager tokenManager, string consumerKey) { - return new WebConsumer(GoogleDescription, tokenManager) { - ConsumerKey = consumerKey, - }; - } + /// <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"); + } - /// <summary> - /// Initializes a new instance of the <see cref="DesktopConsumer"/> class that is prepared to communicate with Google. - /// </summary> - /// <param name="tokenManager">The token manager.</param> - /// <param name="consumerKey">The consumer key.</param> - /// <returns>The newly instantiated <see cref="DesktopConsumer"/>.</returns> - public static DesktopConsumer CreateDesktopConsumer(ITokenManager tokenManager, string consumerKey) { - return new DesktopConsumer(GoogleDescription, tokenManager) { - ConsumerKey = consumerKey, + 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 RsaSha1SigningBindingElement(signingCertificate) }, }; } diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs new file mode 100644 index 0000000..2a98ffe --- /dev/null +++ b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs @@ -0,0 +1,51 @@ +//----------------------------------------------------------------------- +// <copyright file="TwitterConsumer.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace DotNetOpenAuth.ApplicationBlock { + using System; + using System.Collections.Generic; + using System.IO; + using System.Xml; + using System.Xml.Linq; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.OAuth.ChannelElements; + + /// <summary> + /// A consumer capable of communicating with Twitter. + /// </summary> + public static class TwitterConsumer { + /// <summary> + /// The description of Twitter's OAuth protocol URIs. + /// </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() }, + }; + + /// <summary> + /// The URI to get a user's favorites. + /// </summary> + private static readonly MessageReceivingEndpoint GetFavoritesEndpoint = new MessageReceivingEndpoint("http://twitter.com/favorites.xml", HttpDeliveryMethods.GetRequest); + + /// <summary> + /// The URI to get the data on the user's home page. + /// </summary> + private static readonly MessageReceivingEndpoint GetFriendTimelineStatusEndpoint = new MessageReceivingEndpoint("http://twitter.com/statuses/friends_timeline.xml", HttpDeliveryMethods.GetRequest); + + public static XDocument GetUpdates(ConsumerBase twitter, string accessToken) { + IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFriendTimelineStatusEndpoint, accessToken); + return XDocument.Load(XmlReader.Create(response.GetResponseReader())); + } + + public static XDocument GetFavorites(ConsumerBase twitter, string accessToken) { + IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFavoritesEndpoint, accessToken); + return XDocument.Load(XmlReader.Create(response.GetResponseReader())); + } + } +} diff --git a/samples/InfoCardRelyingParty/web.config b/samples/InfoCardRelyingParty/web.config index b3b8654..f14d14b 100644 --- a/samples/InfoCardRelyingParty/web.config +++ b/samples/InfoCardRelyingParty/web.config @@ -43,6 +43,11 @@ <appSettings/> <connectionStrings/> + + <system.net> + <defaultProxy enabled="true" /> + </system.net> + <system.web> <!-- Set compilation debug="true" to insert debugging diff --git a/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs b/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs index f36a396..fede300 100644 --- a/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs +++ b/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs @@ -10,10 +10,14 @@ using System.Diagnostics; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; -public class InMemoryTokenManager : ITokenManager { +public class InMemoryTokenManager : IConsumerTokenManager { private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); public InMemoryTokenManager(string consumerKey, string consumerSecret) { + if (String.IsNullOrEmpty(consumerKey)) { + throw new ArgumentNullException("consumerKey"); + } + this.ConsumerKey = consumerKey; this.ConsumerSecret = consumerSecret; } diff --git a/samples/OAuthConsumer/Default.aspx b/samples/OAuthConsumer/Default.aspx index 20e0f94..aa4ef79 100644 --- a/samples/OAuthConsumer/Default.aspx +++ b/samples/OAuthConsumer/Default.aspx @@ -1,11 +1,13 @@ -<%@ Page Title="DotNetOpenAuth Consumer samples" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" %> +<%@ Page Title="DotNetOpenAuth Consumer samples" Language="C#" MasterPageFile="~/MasterPage.master" + AutoEventWireup="true" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <p>OAuth allows this web site to access your private data with your authorization, - but without you having to give up your password. </p> + <p>OAuth allows this web site to access your private data with your authorization, but + without you having to give up your password. </p> <p>Select a demo:</p> <ul> <li><a href="GoogleAddressBook.aspx">Download your Gmail address book</a></li> + <li><a href="Twitter.aspx">Get your Twitter updates</a></li> <li><a href="SampleWcf.aspx">Interop with Service Provider sample using WCF w/ OAuth</a></li> </ul> </asp:Content> diff --git a/samples/OAuthConsumer/GoogleAddressBook.aspx b/samples/OAuthConsumer/GoogleAddressBook.aspx index 1c20954..56179b7 100644 --- a/samples/OAuthConsumer/GoogleAddressBook.aspx +++ b/samples/OAuthConsumer/GoogleAddressBook.aspx @@ -1,45 +1,26 @@ -<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" - CodeFile="GoogleAddressBook.aspx.cs" Inherits="GoogleAddressBook" %> +<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" + AutoEventWireup="true" CodeFile="GoogleAddressBook.aspx.cs" Inherits="GoogleAddressBook" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View runat="server" ID="Authorize"> - <table> - <tr> - <td> - Google Consumer Key - </td> - <td> - <asp:TextBox ID="consumerKeyBox" runat="server" Columns="35"></asp:TextBox> - <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" - ControlToValidate="consumerKeyBox" Display="Dynamic" - ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator> - </td> - </tr> - <tr> - <td> - Google Consumer Secret - </td> - <td> - <asp:TextBox ID="consumerSecretBox" runat="server" Columns="35"></asp:TextBox> - <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" - ControlToValidate="consumerSecretBox" Display="Dynamic">*</asp:RequiredFieldValidator> - </td> - </tr> - <tr> - <td> - </td> - <td> - Don't have a Google Consumer Key? - <a href="https://www.google.com/accounts/ManageDomains">Get one</a>.</td> - </tr> - </table> - <asp:Button ID="authorizeButton" runat="server" Text="Download your Gmail Address Book" - OnClick="authorizeButton_Click" /> + <asp:View runat="server"> + <h2>Google setup</h2> + <p>A Google client app must be endorsed by a Google user. </p> + <ol> + <li><a target="_blank" href="https://www.google.com/accounts/ManageDomains">Visit Google + and create a client app</a>. </li> + <li>Modify your web.config file to include your consumer key and consumer secret. + </li> + </ol> </asp:View> - <asp:View runat="server" ID="Results"> - <p>Now displaying the first 25 records from your address book:</p> - <asp:PlaceHolder runat="server" ID="resultsPlaceholder" /> + <asp:View runat="server"> + <h2>Updates</h2> + <p>Ok, Google has authorized us to download your contacts. Click 'Get address book' + to download the first 25 contacts to this sample. Notice how we never asked you + for your Google username or password. </p> + <asp:Button ID="getAddressBookButton" runat="server" OnClick="getAddressBookButton_Click" + Text="Get address book" /> + <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> </asp:View> </asp:MultiView> </asp:Content> diff --git a/samples/OAuthConsumer/GoogleAddressBook.aspx.cs b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs index 838b286..463d7e3 100644 --- a/samples/OAuthConsumer/GoogleAddressBook.aspx.cs +++ b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs @@ -1,4 +1,5 @@ using System; +using System.Configuration; using System.Linq; using System.Text; using System.Web; @@ -6,52 +7,67 @@ using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Linq; using DotNetOpenAuth.ApplicationBlock; +using DotNetOpenAuth.OAuth; /// <summary> /// A page to demonstrate downloading a Gmail address book using OAuth. /// </summary> public partial class GoogleAddressBook : System.Web.UI.Page { + private string AccessToken { + get { return (string)Session["GoogleAccessToken"]; } + set { Session["GoogleAccessToken"] = value; } + } + + private InMemoryTokenManager TokenManager { + get { + var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; + if (tokenManager == null) { + string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; + string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; + if (!string.IsNullOrEmpty(consumerKey)) { + tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); + Application["GoogleTokenManager"] = tokenManager; + } + } + + return tokenManager; + } + } + protected void Page_Load(object sender, EventArgs e) { - if (!IsPostBack) { - if (Session["TokenManager"] != null) { - InMemoryTokenManager tokenManager = (InMemoryTokenManager)Session["TokenManager"]; - var google = GoogleConsumer.CreateWebConsumer(tokenManager, tokenManager.ConsumerKey); + if (this.TokenManager != null) { + MultiView1.ActiveViewIndex = 1; + + if (!IsPostBack) { + var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); + // Is Google calling back with authorization? var accessTokenResponse = google.ProcessUserAuthorization(); if (accessTokenResponse != null) { - // User has approved access - MultiView1.ActiveViewIndex = 1; - resultsPlaceholder.Controls.Add(new Label { Text = accessTokenResponse.AccessToken }); - - XDocument contactsDocument = GoogleConsumer.GetContacts(google, accessTokenResponse.AccessToken); - var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) - select new { - Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, - Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value, - }; - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>"); - foreach (var contact in contacts) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(contact.Name), - HttpUtility.HtmlEncode(contact.Email)); - } - tableBuilder.Append("</table>"); - resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + this.AccessToken = accessTokenResponse.AccessToken; + } else if (this.AccessToken == null) { + // If we don't yet have access, immediately request it. + GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); } } } } - protected void authorizeButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } + protected void getAddressBookButton_Click(object sender, EventArgs e) { + var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - InMemoryTokenManager tokenManager = new InMemoryTokenManager(consumerKeyBox.Text, consumerSecretBox.Text); - Session["TokenManager"] = tokenManager; - var google = GoogleConsumer.CreateWebConsumer(tokenManager, consumerKeyBox.Text); - GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); + XDocument contactsDocument = GoogleConsumer.GetContacts(google, this.AccessToken); + var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) + select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value }; + StringBuilder tableBuilder = new StringBuilder(); + tableBuilder.Append("<table><tr><td>Name</td><td>Email</td></tr>"); + foreach (var contact in contacts) { + tableBuilder.AppendFormat( + "<tr><td>{0}</td><td>{1}</td></tr>", + HttpUtility.HtmlEncode(contact.Name), + HttpUtility.HtmlEncode(contact.Email)); + } + tableBuilder.Append("</table>"); + resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); } } diff --git a/samples/OAuthConsumer/SampleWcf.aspx.cs b/samples/OAuthConsumer/SampleWcf.aspx.cs index e733970..7572dd8 100644 --- a/samples/OAuthConsumer/SampleWcf.aspx.cs +++ b/samples/OAuthConsumer/SampleWcf.aspx.cs @@ -109,9 +109,7 @@ public partial class SampleWcf : System.Web.UI.Page { new HmacSha1SigningBindingElement(), }, }, - tokenManager) { - ConsumerKey = consumerKey, - }; + tokenManager); return consumer; } diff --git a/samples/OAuthConsumer/Twitter.aspx b/samples/OAuthConsumer/Twitter.aspx new file mode 100644 index 0000000..a659533 --- /dev/null +++ b/samples/OAuthConsumer/Twitter.aspx @@ -0,0 +1,26 @@ +<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" + CodeFile="Twitter.aspx.cs" Inherits="Twitter" %> + +<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> +</asp:Content> +<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> + <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> + <asp:View ID="View1" runat="server"> + <h2>Twitter setup</h2> + <p>A Twitter client app must be endorsed by a Twitter user. </p> + <ol> + <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create + a client app</a>. </li> + <li>Modify your web.config file to include your consumer key and consumer secret.</li> + </ol> + </asp:View> + <asp:View runat="server"> + <h2>Updates</h2> + <p>Ok, Twitter has authorized us to download your feeds. Click 'Get updates' to download + updates to this sample. Notice how we never asked you for your Twitter username + or password. </p> + <asp:Button ID="downloadUpdates" runat="server" Text="Get updates" OnClick="downloadUpdates_Click" /> + <asp:PlaceHolder runat="server" ID="resultsPlaceholder" /> + </asp:View> + </asp:MultiView> +</asp:Content> diff --git a/samples/OAuthConsumer/Twitter.aspx.cs b/samples/OAuthConsumer/Twitter.aspx.cs new file mode 100644 index 0000000..a4fb0cb --- /dev/null +++ b/samples/OAuthConsumer/Twitter.aspx.cs @@ -0,0 +1,78 @@ +using System; +using System.Collections.Generic; +using System.Configuration; +using System.Linq; +using System.Text; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Xml.Linq; +using System.Xml.XPath; +using DotNetOpenAuth.ApplicationBlock; +using DotNetOpenAuth.OAuth; + +public partial class Twitter : System.Web.UI.Page { + private string AccessToken { + get { return (string)Session["TwitterAccessToken"]; } + set { Session["TwitterAccessToken"] = value; } + } + + private InMemoryTokenManager TokenManager { + get { + var tokenManager = (InMemoryTokenManager)Application["TwitterTokenManager"]; + if (tokenManager == null) { + string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; + string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; + if (!string.IsNullOrEmpty(consumerKey)) { + tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); + Application["TwitterTokenManager"] = tokenManager; + } + } + + return tokenManager; + } + } + + protected void Page_Load(object sender, EventArgs e) { + if (this.TokenManager != null) { + MultiView1.ActiveViewIndex = 1; + + if (!IsPostBack) { + var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); + + // Is Twitter calling back with authorization? + var accessTokenResponse = twitter.ProcessUserAuthorization(); + if (accessTokenResponse != null) { + this.AccessToken = accessTokenResponse.AccessToken; + } else if (this.AccessToken == null) { + // If we don't yet have access, immediately request it. + twitter.Channel.Send(twitter.PrepareRequestUserAuthorization()); + } + } + } + } + + protected void downloadUpdates_Click(object sender, EventArgs e) { + var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); + XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, AccessToken).CreateReader()); + XPathNavigator nav = updates.CreateNavigator(); + var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>() + where !status.SelectSingleNode("user/protected").ValueAsBoolean + select new { + User = status.SelectSingleNode("user/name").InnerXml, + Status = status.SelectSingleNode("text").InnerXml, + }; + + StringBuilder tableBuilder = new StringBuilder(); + tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); + + foreach (var update in parsedUpdates) { + tableBuilder.AppendFormat( + "<tr><td>{0}</td><td>{1}</td></tr>", + HttpUtility.HtmlEncode(update.User), + HttpUtility.HtmlEncode(update.Status)); + } + tableBuilder.Append("</table>"); + resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); + } +} diff --git a/samples/OAuthConsumer/Web.config b/samples/OAuthConsumer/Web.config index 7d7f6aa..fc4c7dc 100644 --- a/samples/OAuthConsumer/Web.config +++ b/samples/OAuthConsumer/Web.config @@ -14,8 +14,22 @@ </sectionGroup> </sectionGroup> </configSections> - <appSettings/> + <appSettings> + <!-- Fill in your various consumer keys and secrets here to make the sample work. --> + <!-- You must get these values by signing up with each individual service provider. --> + <!-- Twitter sign-up: https://twitter.com/oauth_clients --> + <add key="twitterConsumerKey" value="" /> + <add key="twitterConsumerSecret" value="" /> + <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> + <add key="googleConsumerKey" value=""/> + <add key="googleConsumerSecret" value=""/> + </appSettings> <connectionStrings/> + + <system.net> + <defaultProxy enabled="true" /> + </system.net> + <system.web> <!-- Set compilation debug="true" to insert debugging @@ -141,9 +155,7 @@ enabled="false" /> <security mode="Message"> <transport clientCredentialType="Windows" proxyCredentialType="None" - realm=""> - <extendedProtectionPolicy policyEnforcement="Never" /> - </transport> + realm=""/> <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" /> </security> diff --git a/samples/OAuthConsumerWpf/App.config b/samples/OAuthConsumerWpf/App.config index 9780370..2f849e4 100644 --- a/samples/OAuthConsumerWpf/App.config +++ b/samples/OAuthConsumerWpf/App.config @@ -3,6 +3,23 @@ <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" /> </configSections> + + <appSettings> + <!-- Fill in your various consumer keys and secrets here to make the sample work. --> + <!-- You must get these values by signing up with each individual service provider. --> + <!-- Google sign-up: https://www.google.com/accounts/ManageDomains --> + <add key="googleConsumerKey" value=""/> + <!-- Google requires either a secret or an X.509 certificate. This sample will use + the certificate if it is specified, otherwise it will use the shared secret. --> + <add key="googleConsumerSecret" value=""/> + <add key="googleConsumerCertificateFile" value=""/> + <add key="googleConsumerCertificatePassword" value=""/> + </appSettings> + + <system.net> + <defaultProxy enabled="true" /> + </system.net> + <log4net> <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="Testing.log" /> diff --git a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs b/samples/OAuthConsumerWpf/InMemoryTokenManager.cs index b4692f1..faa485f 100644 --- a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs +++ b/samples/OAuthConsumerWpf/InMemoryTokenManager.cs @@ -11,15 +11,15 @@ namespace DotNetOpenAuth.Samples.OAuthConsumerWpf { using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; - internal class InMemoryTokenManager : ITokenManager { + internal class InMemoryTokenManager : IConsumerTokenManager { private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); internal InMemoryTokenManager() { } - internal string ConsumerKey { get; set; } + public string ConsumerKey { get; internal set; } - internal string ConsumerSecret { get; set; } + public string ConsumerSecret { get; internal set; } #region ITokenManager Members diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml b/samples/OAuthConsumerWpf/MainWindow.xaml index f422353..fb036ce 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml +++ b/samples/OAuthConsumerWpf/MainWindow.xaml @@ -18,18 +18,6 @@ <Button Name="beginAuthorizationButton" Click="beginAuthorizationButton_Click">Start authorize</Button> <Button Name="completeAuthorizationButton" Margin="5,0,0,0" Click="completeAuthorizationButton_Click" IsEnabled="false">Complete authorization</Button> </StackPanel> - <Label>Consumer Key</Label> - <TextBox Grid.Column="1" Name="consumerKeyBox"/> - <Label Grid.Row="1">Consumer Secret</Label> - <TextBox Grid.Row="1" Grid.Column="1" Name="consumerSecretBox"/> - <Label Grid.Row="2" Grid.Column="1"> - <TextBlock> - Don't have a Google Consumer Key? - <Hyperlink NavigateUri="https://www.google.com/accounts/ManageDomains"> - <TextBlock>Get one!</TextBlock> - </Hyperlink> - </TextBlock> - </Label> <TabControl Grid.ColumnSpan="2" Grid.Row="4" Name="tabControl1" Margin="0,10,0,0"> <TabItem Header="Gmail Contacts" Name="gmailContactsTab"> <Grid Name="contactsGrid"> diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs index b57589a..6c1c2ba 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs +++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs @@ -1,7 +1,9 @@ namespace DotNetOpenAuth.Samples.OAuthConsumerWpf { using System; using System.Collections.Generic; + using System.Configuration; using System.Linq; + using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Windows; @@ -34,13 +36,25 @@ public MainWindow() { InitializeComponent(); - this.google = GoogleConsumer.CreateDesktopConsumer(this.tokenManager, string.Empty); + this.tokenManager.ConsumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; + this.tokenManager.ConsumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; + + string pfxFile = ConfigurationManager.AppSettings["googleConsumerCertificateFile"]; + if (string.IsNullOrEmpty(pfxFile)) { + this.google = new DesktopConsumer(GoogleConsumer.ServiceDescription, this.tokenManager); + } else { + string pfxPassword = ConfigurationManager.AppSettings["googleConsumerCertificatePassword"]; + var signingCertificate = new X509Certificate2(pfxFile, pfxPassword); + var service = GoogleConsumer.CreateRsaSha1ServiceDescription(signingCertificate); + this.google = new DesktopConsumer(service, this.tokenManager); + } } private void beginAuthorizationButton_Click(object sender, RoutedEventArgs e) { - this.tokenManager.ConsumerKey = consumerKeyBox.Text; - this.tokenManager.ConsumerSecret = consumerSecretBox.Text; - this.google.ConsumerKey = consumerKeyBox.Text; + if (string.IsNullOrEmpty(this.tokenManager.ConsumerKey)) { + MessageBox.Show(this, "You must modify the App.config or OAuthConsumerWpf.exe.config file for this application to include your Google OAuth consumer key first.", "Configuration required", MessageBoxButton.OK, MessageBoxImage.Stop); + return; + } Cursor original = this.Cursor; this.Cursor = Cursors.Wait; @@ -65,10 +79,7 @@ this.accessToken = grantedAccess.AccessToken; XDocument contactsDocument = GoogleConsumer.GetContacts(this.google, grantedAccess.AccessToken); var contacts = from entry in contactsDocument.Root.Elements(XName.Get("entry", "http://www.w3.org/2005/Atom")) - select new { - Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, - Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value, - }; + select new { Name = entry.Element(XName.Get("title", "http://www.w3.org/2005/Atom")).Value, Email = entry.Element(XName.Get("email", "http://schemas.google.com/g/2005")).Attribute("address").Value }; contactsGrid.Children.Clear(); foreach (var contact in contacts) { contactsGrid.RowDefinitions.Add(new RowDefinition()); diff --git a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj index e1181ae..0617746 100644 --- a/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj +++ b/samples/OAuthConsumerWpf/OAuthConsumerWpf.csproj @@ -43,11 +43,16 @@ <ErrorReport>prompt</ErrorReport> </PropertyGroup> <ItemGroup> + <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> + <SpecificVersion>False</SpecificVersion> + <HintPath>..\..\lib\log4net.dll</HintPath> + </Reference> <Reference Include="Microsoft.Contracts, Version=1.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\..\lib\Microsoft.Contracts.dll</HintPath> </Reference> <Reference Include="System" /> + <Reference Include="System.configuration" /> <Reference Include="System.Core"> <RequiredTargetFramework>3.5</RequiredTargetFramework> </Reference> diff --git a/samples/OAuthConsumerWpf/Properties/AssemblyInfo.cs b/samples/OAuthConsumerWpf/Properties/AssemblyInfo.cs index 029ad14..8d23055 100644 --- a/samples/OAuthConsumerWpf/Properties/AssemblyInfo.cs +++ b/samples/OAuthConsumerWpf/Properties/AssemblyInfo.cs @@ -16,6 +16,8 @@ using System.Windows; [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] +[assembly: log4net.Config.XmlConfigurator(Watch = true)] + // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. diff --git a/samples/OAuthServiceProvider/App_Code/CustomOAuthTypeProvider.cs b/samples/OAuthServiceProvider/App_Code/CustomOAuthTypeProvider.cs index a4397c1..9fdbf29 100644 --- a/samples/OAuthServiceProvider/App_Code/CustomOAuthTypeProvider.cs +++ b/samples/OAuthServiceProvider/App_Code/CustomOAuthTypeProvider.cs @@ -15,7 +15,7 @@ public class CustomOAuthMessageFactory : OAuthServiceProviderMessageFactory { /// Initializes a new instance of the <see cref="CustomOAuthMessageFactory"/> class. /// </summary> /// <param name="tokenManager">The token manager instance to use.</param> - public CustomOAuthMessageFactory(ITokenManager tokenManager) : base(tokenManager) { + public CustomOAuthMessageFactory(IServiceProviderTokenManager tokenManager) : base(tokenManager) { } public override IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { diff --git a/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs b/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs index b5d8fdd..d922901 100644 --- a/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs +++ b/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs @@ -11,8 +11,8 @@ using System.Linq; using DotNetOpenAuth.OAuth.ChannelElements; using DotNetOpenAuth.OAuth.Messages; -public class DatabaseTokenManager : ITokenManager { - #region ITokenManager Members +public class DatabaseTokenManager : IServiceProviderTokenManager { + #region IServiceProviderTokenManager public string GetConsumerSecret(string consumerKey) { var consumerRow = Global.DataContext.OAuthConsumers.SingleOrDefault( @@ -24,6 +24,10 @@ public class DatabaseTokenManager : ITokenManager { return consumerRow.ConsumerSecret; } + #endregion + + #region ITokenManager Members + public string GetTokenSecret(string token) { var tokenRow = Global.DataContext.OAuthTokens.SingleOrDefault( tokenCandidate => tokenCandidate.Token == token); diff --git a/samples/OAuthServiceProvider/Web.config b/samples/OAuthServiceProvider/Web.config index f4bd208..8fad999 100644 --- a/samples/OAuthServiceProvider/Web.config +++ b/samples/OAuthServiceProvider/Web.config @@ -19,6 +19,11 @@ <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" /> </connectionStrings> + + <system.net> + <defaultProxy enabled="true" /> + </system.net> + <system.web> <!-- Set compilation debug="true" to insert debugging diff --git a/samples/OpenIdProviderMvc/Web.config b/samples/OpenIdProviderMvc/Web.config index 52a7e4b..208e827 100644 --- a/samples/OpenIdProviderMvc/Web.config +++ b/samples/OpenIdProviderMvc/Web.config @@ -43,6 +43,24 @@ </messaging> </dotNetOpenAuth> <appSettings/> + + <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names), + which is necessary for OpenID urls with unicode characters in the domain/host name. --> + <uri> + <idn enabled="All" /> + <iriParsing enabled="true" /> + </uri> + + <system.net> + <defaultProxy enabled="true" /> + <settings> + <!-- This setting causes .NET to check certificate revocation lists (CRL) + before trusting HTTPS certificates. But this setting tends to not + be allowed in shared hosting environments. --> + <!--<servicePointManager checkCertificateRevocationList="true"/>--> + </settings> + </system.net> + <system.web> <!-- Set compilation debug="true" to insert debugging diff --git a/samples/OpenIdProviderWebForms/Default.aspx b/samples/OpenIdProviderWebForms/Default.aspx index ef090e1..b216d51 100644 --- a/samples/OpenIdProviderWebForms/Default.aspx +++ b/samples/OpenIdProviderWebForms/Default.aspx @@ -49,8 +49,8 @@ <asp:Button runat="server" ID="sendAssertionButton" Text="Login" OnClick="sendAssertionButton_Click" /> <asp:RequiredFieldValidator runat="server" ControlToValidate="relyingPartySite" Text="Specify relying party site first" /> </div> - <p id="bookmarkParagraph" style="display: none">Bookmark <a id="bookmark"></a>so you - can log into the RP automatically in the future.</p> + <p id="bookmarkParagraph" style="display: none">Bookmark <a id="bookmark"></a> so + you can log into the RP automatically in the future.</p> <p>An unsolicited assertion is a way to log in to a relying party site directly from your OpenID Provider. </p> <p><asp:Label runat="server" EnableViewState="false" Visible="false" ID="errorLabel" diff --git a/samples/OpenIdProviderWebForms/Default.aspx.cs b/samples/OpenIdProviderWebForms/Default.aspx.cs index 808dbb1..4843639 100644 --- a/samples/OpenIdProviderWebForms/Default.aspx.cs +++ b/samples/OpenIdProviderWebForms/Default.aspx.cs @@ -14,12 +14,12 @@ protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["rp"] != null) { if (Page.User.Identity.IsAuthenticated) { - SendAssertion(Request.QueryString["rp"]); + this.SendAssertion(Request.QueryString["rp"]); } else { FormsAuthentication.RedirectToLoginPage(); } } else { - TextBox relyingPartySite = (TextBox)loginView.FindControl("relyingPartySite"); + TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); if (relyingPartySite != null) { relyingPartySite.Focus(); } @@ -27,8 +27,8 @@ } protected void sendAssertionButton_Click(object sender, EventArgs e) { - TextBox relyingPartySite = (TextBox)loginView.FindControl("relyingPartySite"); - SendAssertion(relyingPartySite.Text); + TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite"); + this.SendAssertion(relyingPartySite.Text); } private void SendAssertion(string relyingPartyRealm) { @@ -39,7 +39,7 @@ string rpSite = Identifier.Parse(relyingPartyRealm); op.PrepareUnsolicitedAssertion(providerEndpoint, rpSite, Util.BuildIdentityUrl(), Util.BuildIdentityUrl()).Send(); } catch (ProtocolException ex) { - Label errorLabel = (Label)loginView.FindControl("errorLabel"); + Label errorLabel = (Label)this.loginView.FindControl("errorLabel"); errorLabel.Visible = true; errorLabel.Text = ex.Message; } diff --git a/samples/OpenIdProviderWebForms/Web.config b/samples/OpenIdProviderWebForms/Web.config index 85b3c30..04d0416 100644 --- a/samples/OpenIdProviderWebForms/Web.config +++ b/samples/OpenIdProviderWebForms/Web.config @@ -48,11 +48,12 @@ <iriParsing enabled="true"/> </uri> - <!-- This setting causes .NET to check certificate revocation lists (CRL) - before trusting HTTPS certificates. But this setting tends to not - be allowed in shared hosting environments. --> <system.net> + <defaultProxy enabled="true" /> <settings> + <!-- This setting causes .NET to check certificate revocation lists (CRL) + before trusting HTTPS certificates. But this setting tends to not + be allowed in shared hosting environments. --> <!--<servicePointManager checkCertificateRevocationList="true"/>--> </settings> </system.net> diff --git a/samples/OpenIdRelyingPartyMvc/Web.config b/samples/OpenIdRelyingPartyMvc/Web.config index b051162..d865be1 100644 --- a/samples/OpenIdRelyingPartyMvc/Web.config +++ b/samples/OpenIdRelyingPartyMvc/Web.config @@ -48,12 +48,13 @@ <iriParsing enabled="true" /> </uri> - <!-- This setting causes .NET to check certificate revocation lists (CRL) - before trusting HTTPS certificates. But this setting tends to not - be allowed in shared hosting environments. --> <system.net> + <defaultProxy enabled="true" /> <settings> - <servicePointManager checkCertificateRevocationList="true"/> + <!-- This setting causes .NET to check certificate revocation lists (CRL) + before trusting HTTPS certificates. But this setting tends to not + be allowed in shared hosting environments. --> + <!--<servicePointManager checkCertificateRevocationList="true"/>--> </settings> </system.net> diff --git a/samples/OpenIdRelyingPartyWebForms/Code/TracePageAppender.cs b/samples/OpenIdRelyingPartyWebForms/Code/TracePageAppender.cs index 9848bb3..a03293b 100644 --- a/samples/OpenIdRelyingPartyWebForms/Code/TracePageAppender.cs +++ b/samples/OpenIdRelyingPartyWebForms/Code/TracePageAppender.cs @@ -1,4 +1,4 @@ -namespace OpenIdRelyingPartyWebForms { +namespace OpenIdRelyingPartyWebForms.Code { using System; using System.Collections.Generic; using System.IO; diff --git a/samples/OpenIdRelyingPartyWebForms/Web.config b/samples/OpenIdRelyingPartyWebForms/Web.config index 5a8fc23..9c281a4 100644 --- a/samples/OpenIdRelyingPartyWebForms/Web.config +++ b/samples/OpenIdRelyingPartyWebForms/Web.config @@ -32,11 +32,12 @@ <iriParsing enabled="true" /> </uri> - <!-- This setting causes .NET to check certificate revocation lists (CRL) - before trusting HTTPS certificates. But this setting tends to not - be allowed in shared hosting environments. --> <system.net> + <defaultProxy enabled="true" /> <settings> + <!-- This setting causes .NET to check certificate revocation lists (CRL) + before trusting HTTPS certificates. But this setting tends to not + be allowed in shared hosting environments. --> <!--<servicePointManager checkCertificateRevocationList="true"/>--> </settings> </system.net> @@ -70,7 +71,7 @@ <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline" /> </layout> </appender> - <appender name="TracePageAppender" type="OpenIdRelyingPartyWebForms.TracePageAppender, OpenIdRelyingPartyWebForms"> + <appender name="TracePageAppender" type="OpenIdRelyingPartyWebForms.Code.TracePageAppender, OpenIdRelyingPartyWebForms"> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline" /> </layout> |