diff options
Diffstat (limited to 'samples')
47 files changed, 858 insertions, 147 deletions
diff --git a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs index 2a98ffe..ecb7d6c 100644 --- a/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs +++ b/samples/DotNetOpenAuth.ApplicationBlock/TwitterConsumer.cs @@ -8,6 +8,7 @@ namespace DotNetOpenAuth.ApplicationBlock { using System; using System.Collections.Generic; using System.IO; + using System.Net; using System.Xml; using System.Xml.Linq; using DotNetOpenAuth.Messaging; @@ -38,6 +39,18 @@ namespace DotNetOpenAuth.ApplicationBlock { /// </summary> private static readonly MessageReceivingEndpoint GetFriendTimelineStatusEndpoint = new MessageReceivingEndpoint("http://twitter.com/statuses/friends_timeline.xml", HttpDeliveryMethods.GetRequest); + private static readonly MessageReceivingEndpoint UpdateProfileBackgroundImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_background_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + + private static readonly MessageReceivingEndpoint UpdateProfileImageEndpoint = new MessageReceivingEndpoint("http://twitter.com/account/update_profile_image.xml", HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest); + + /// <summary> + /// Initializes static members of the <see cref="TwitterConsumer"/> class. + /// </summary> + static TwitterConsumer() { + // Twitter can't handle the Expect 100 Continue HTTP header. + ServicePointManager.FindServicePoint(GetFavoritesEndpoint.Location).Expect100Continue = false; + } + public static XDocument GetUpdates(ConsumerBase twitter, string accessToken) { IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFriendTimelineStatusEndpoint, accessToken); return XDocument.Load(XmlReader.Create(response.GetResponseReader())); @@ -47,5 +60,32 @@ namespace DotNetOpenAuth.ApplicationBlock { IncomingWebResponse response = twitter.PrepareAuthorizedRequestAndSend(GetFavoritesEndpoint, accessToken); return XDocument.Load(XmlReader.Create(response.GetResponseReader())); } + + public static XDocument UpdateProfileBackgroundImage(ConsumerBase twitter, string accessToken, string image, bool tile) { + HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileBackgroundImageEndpoint, accessToken); + request.ServicePoint.Expect100Continue = false; + var parts = new[] { + MultipartPostPart.CreateFormFilePart("image", image, "image/" + Path.GetExtension(image).Substring(1).ToLowerInvariant()), + MultipartPostPart.CreateFormPart("tile", tile.ToString().ToLowerInvariant()), + }; + IncomingWebResponse response = request.PostMultipart(twitter.Channel.WebRequestHandler, parts); + string responseString = response.GetResponseReader().ReadToEnd(); + return XDocument.Parse(responseString); + } + + public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, string pathToImage) { + string contentType = "image/" + Path.GetExtension(pathToImage).Substring(1).ToLowerInvariant(); + return UpdateProfileImage(twitter, accessToken, File.OpenRead(pathToImage), contentType); + } + + public static XDocument UpdateProfileImage(ConsumerBase twitter, string accessToken, Stream image, string contentType) { + HttpWebRequest request = twitter.PrepareAuthorizedRequest(UpdateProfileImageEndpoint, accessToken); + var parts = new[] { + MultipartPostPart.CreateFormFilePart("image", "twitterPhoto", contentType, image), + }; + IncomingWebResponse response = request.PostMultipart(twitter.Channel.WebRequestHandler, parts); + string responseString = response.GetResponseReader().ReadToEnd(); + return XDocument.Parse(responseString); + } } } diff --git a/samples/InfoCardRelyingParty/web.config b/samples/InfoCardRelyingParty/web.config index f14d14b..7599561 100644 --- a/samples/InfoCardRelyingParty/web.config +++ b/samples/InfoCardRelyingParty/web.config @@ -1,15 +1,8 @@ <?xml version="1.0"?> -<!-- - Note: As an alternative to hand editing this file you can use the - web admin tool to configure settings for your application. Use - the Website->Asp.Net Configuration option in Visual Studio. - A full list of settings and comments can be found in - machine.config.comments usually located in - \Windows\Microsoft.Net\Framework\v2.x\Config ---> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" /> + <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> @@ -23,6 +16,12 @@ </sectionGroup> </configSections> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> + <dotNetOpenAuth> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> + </dotNetOpenAuth> + <log4net> <appender name="TracePageAppender" type="TracePageAppender, __code"> <layout type="log4net.Layout.PatternLayout"> @@ -41,13 +40,13 @@ </logger> </log4net> - <appSettings/> - <connectionStrings/> - <system.net> <defaultProxy enabled="true" /> </system.net> + <appSettings/> + <connectionStrings/> + <system.web> <!-- Set compilation debug="true" to insert debugging @@ -66,6 +65,7 @@ <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <pages> diff --git a/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs b/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs index fede300..120f00a 100644 --- a/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs +++ b/samples/OAuthConsumer/App_Code/InMemoryTokenManager.cs @@ -28,14 +28,6 @@ public class InMemoryTokenManager : IConsumerTokenManager { #region ITokenManager Members - public string GetConsumerSecret(string consumerKey) { - if (consumerKey == this.ConsumerKey) { - return this.ConsumerSecret; - } else { - throw new ArgumentException("Unrecognized consumer key.", "consumerKey"); - } - } - public string GetTokenSecret(string token) { return this.tokensAndSecrets[token]; } @@ -44,20 +36,6 @@ public class InMemoryTokenManager : IConsumerTokenManager { this.tokensAndSecrets[response.Token] = response.TokenSecret; } - /// <summary> - /// Checks whether a given request token has already been authorized - /// by some user for use by the Consumer that requested it. - /// </summary> - /// <param name="requestToken">The Consumer's request token.</param> - /// <returns> - /// True if the request token has already been fully authorized by the user - /// who owns the relevant protected resources. False if the token has not yet - /// been authorized, has expired or does not exist. - /// </returns> - public bool IsRequestTokenAuthorized(string requestToken) { - throw new NotImplementedException(); - } - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { this.tokensAndSecrets.Remove(requestToken); this.tokensAndSecrets[accessToken] = accessTokenSecret; diff --git a/samples/OAuthConsumer/Twitter.aspx b/samples/OAuthConsumer/Twitter.aspx index a659533..30ce2a0 100644 --- a/samples/OAuthConsumer/Twitter.aspx +++ b/samples/OAuthConsumer/Twitter.aspx @@ -16,9 +16,19 @@ </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> + <p>Ok, Twitter has authorized us to download your feeds. Notice how we never asked + you for your Twitter username or password. </p> + <p> + Upload a new profile photo: + <asp:FileUpload ID="profilePhoto" runat="server" /> + <asp:Button ID="uploadProfilePhotoButton" runat="server" + onclick="uploadProfilePhotoButton_Click" Text="Upload photo" /> + <asp:Label ID="photoUploadedLabel" runat="server" EnableViewState="False" + Text="Done!" Visible="False"></asp:Label> + </p> + <p> + Click 'Get updates' to download updates to this sample. + </p> <asp:Button ID="downloadUpdates" runat="server" Text="Get updates" OnClick="downloadUpdates_Click" /> <asp:PlaceHolder runat="server" ID="resultsPlaceholder" /> </asp:View> diff --git a/samples/OAuthConsumer/Twitter.aspx.cs b/samples/OAuthConsumer/Twitter.aspx.cs index 9b9eced..f309396 100644 --- a/samples/OAuthConsumer/Twitter.aspx.cs +++ b/samples/OAuthConsumer/Twitter.aspx.cs @@ -75,4 +75,20 @@ public partial class Twitter : System.Web.UI.Page { tableBuilder.Append("</table>"); resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); } + + protected void uploadProfilePhotoButton_Click(object sender, EventArgs e) { + if (profilePhoto.PostedFile.ContentType == null) { + photoUploadedLabel.Visible = true; + photoUploadedLabel.Text = "Select a file first."; + return; + } + + var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); + XDocument imageResult = TwitterConsumer.UpdateProfileImage( + twitter, + this.AccessToken, + profilePhoto.PostedFile.InputStream, + profilePhoto.PostedFile.ContentType); + photoUploadedLabel.Visible = true; + } } diff --git a/samples/OAuthConsumer/Web.config b/samples/OAuthConsumer/Web.config index c3a808a..496da95 100644 --- a/samples/OAuthConsumer/Web.config +++ b/samples/OAuthConsumer/Web.config @@ -3,6 +3,7 @@ <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" /> + <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> @@ -34,6 +35,12 @@ </settings> </system.net> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> + <dotNetOpenAuth> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> + </dotNetOpenAuth> + <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. --> @@ -59,6 +66,7 @@ <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <!-- diff --git a/samples/OAuthConsumerWpf/App.config b/samples/OAuthConsumerWpf/App.config index e53b4a3..d4d434a 100644 --- a/samples/OAuthConsumerWpf/App.config +++ b/samples/OAuthConsumerWpf/App.config @@ -3,6 +3,7 @@ <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" /> + <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth" requirePermission="false" allowLocation="true"/> </configSections> <!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names), @@ -23,6 +24,12 @@ </settings> </system.net> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> + <dotNetOpenAuth> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true"/> + </dotNetOpenAuth> + <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. --> diff --git a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs b/samples/OAuthConsumerWpf/InMemoryTokenManager.cs index faa485f..4f70c06 100644 --- a/samples/OAuthConsumerWpf/InMemoryTokenManager.cs +++ b/samples/OAuthConsumerWpf/InMemoryTokenManager.cs @@ -39,20 +39,6 @@ namespace DotNetOpenAuth.Samples.OAuthConsumerWpf { this.tokensAndSecrets[response.Token] = response.TokenSecret; } - /// <summary> - /// Checks whether a given request token has already been authorized - /// by some user for use by the Consumer that requested it. - /// </summary> - /// <param name="requestToken">The Consumer's request token.</param> - /// <returns> - /// True if the request token has already been fully authorized by the user - /// who owns the relevant protected resources. False if the token has not yet - /// been authorized, has expired or does not exist. - /// </returns> - public bool IsRequestTokenAuthorized(string requestToken) { - throw new NotImplementedException(); - } - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { this.tokensAndSecrets.Remove(requestToken); this.tokensAndSecrets[accessToken] = accessTokenSecret; diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml b/samples/OAuthConsumerWpf/MainWindow.xaml index e948bd2..c59175c 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml +++ b/samples/OAuthConsumerWpf/MainWindow.xaml @@ -72,5 +72,66 @@ <Label Grid.Row="3" Grid.Column="1" Name="wcfFavoriteSites" /> </Grid> </TabItem> + <TabItem Header="Generic"> + <Grid> + <Grid.RowDefinitions> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="auto" /> + <RowDefinition Height="*" /> + </Grid.RowDefinitions> + <Grid.ColumnDefinitions> + <ColumnDefinition Width="auto" /> + <ColumnDefinition Width="*" /> + <ColumnDefinition Width="auto" /> + </Grid.ColumnDefinitions> + <Label Grid.Row="0">Request Token URL</Label> + <TextBox Grid.Column="1" x:Name="requestTokenUrlBox" /> + <ComboBox Grid.Column="2" x:Name="requestTokenHttpMethod" SelectedIndex="1"> + <ComboBox.Items> + <ComboBoxItem>GET</ComboBoxItem> + <ComboBoxItem>POST</ComboBoxItem> + </ComboBox.Items> + </ComboBox> + <Label Grid.Row="1">Authorize URL</Label> + <TextBox Grid.Row="1" Grid.Column="1" x:Name="authorizeUrlBox" /> + <Label Grid.Row="1" Grid.Column="2">GET</Label> + <Label Grid.Row="2">Access Token URL</Label> + <TextBox Grid.Row="2" Grid.Column="1" x:Name="accessTokenUrlBox" /> + <ComboBox Grid.Row="2" Grid.Column="2" x:Name="accessTokenHttpMethod" SelectedIndex="1"> + <ComboBox.Items> + <ComboBoxItem>GET</ComboBoxItem> + <ComboBoxItem>POST</ComboBoxItem> + </ComboBox.Items> + </ComboBox> + <Label Grid.Row="3">Resource URL</Label> + <TextBox Grid.Row="3" Grid.Column="1" x:Name="resourceUrlBox" /> + <ComboBox Grid.Row="3" Grid.Column="2" x:Name="resourceHttpMethodList" SelectedIndex="0"> + <ComboBox.Items> + <ComboBoxItem>GET w/ header</ComboBoxItem> + <ComboBoxItem>GET w/ querystring</ComboBoxItem> + <ComboBoxItem>POST</ComboBoxItem> + </ComboBox.Items> + </ComboBox> + <Label Grid.Row="4">Consumer key</Label> + <TextBox Grid.Row="4" Grid.Column="1" x:Name="consumerKeyBox" Grid.ColumnSpan="2"/> + <Label Grid.Row="5">Consumer secret</Label> + <TextBox Grid.Row="5" Grid.Column="1" x:Name="consumerSecretBox" Grid.ColumnSpan="2"/> + <Label Grid.Row="6">OAuth version</Label> + <ComboBox Grid.Row="6" Grid.Column="1" SelectedIndex="1" x:Name="oauthVersion"> + <ComboBox.Items> + <ComboBoxItem>1.0</ComboBoxItem> + <ComboBoxItem>1.0a</ComboBoxItem> + </ComboBox.Items> + </ComboBox> + <Button Grid.Row="7" Grid.Column="1" x:Name="beginButton" Click="beginButton_Click">Begin</Button> + <TextBox Grid.Column="0" Grid.Row="8" Grid.ColumnSpan="3" Name="resultsBox" IsReadOnly="True" /> + </Grid> + </TabItem> </TabControl> </Window> diff --git a/samples/OAuthConsumerWpf/MainWindow.xaml.cs b/samples/OAuthConsumerWpf/MainWindow.xaml.cs index ebbeffc..c917288 100644 --- a/samples/OAuthConsumerWpf/MainWindow.xaml.cs +++ b/samples/OAuthConsumerWpf/MainWindow.xaml.cs @@ -2,6 +2,7 @@ using System; using System.Collections.Generic; using System.Configuration; + using System.Diagnostics; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; @@ -125,6 +126,7 @@ Authorize auth = new Authorize( this.wcf, (DesktopConsumer consumer, out string requestToken) => consumer.RequestUserAuthorization(requestArgs, null, out requestToken)); + auth.Owner = this; bool? result = auth.ShowDialog(); if (result.HasValue && result.Value) { this.wcfAccessToken = auth.AccessToken; @@ -149,5 +151,52 @@ return predicate(client); } } + + private void beginButton_Click(object sender, RoutedEventArgs e) { + try { + var service = new ServiceProviderDescription { + RequestTokenEndpoint = new MessageReceivingEndpoint(requestTokenUrlBox.Text, requestTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), + UserAuthorizationEndpoint = new MessageReceivingEndpoint(authorizeUrlBox.Text, HttpDeliveryMethods.GetRequest), + AccessTokenEndpoint = new MessageReceivingEndpoint(accessTokenUrlBox.Text, accessTokenHttpMethod.SelectedIndex == 0 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, + ProtocolVersion = oauthVersion.SelectedIndex == 0 ? ProtocolVersion.V10 : ProtocolVersion.V10a, + }; + var tokenManager = new InMemoryTokenManager(); + tokenManager.ConsumerKey = consumerKeyBox.Text; + tokenManager.ConsumerSecret = consumerSecretBox.Text; + + var consumer = new DesktopConsumer(service, tokenManager); + string accessToken; + if (service.ProtocolVersion == ProtocolVersion.V10) { + string requestToken; + Uri authorizeUrl = consumer.RequestUserAuthorization(null, null, out requestToken); + Process.Start(authorizeUrl.AbsoluteUri); + MessageBox.Show(this, "Click OK when you've authorized the app."); + var authorizationResponse = consumer.ProcessUserAuthorization(requestToken, null); + accessToken = authorizationResponse.AccessToken; + } else { + var authorizePopup = new Authorize( + consumer, + (DesktopConsumer c, out string requestToken) => c.RequestUserAuthorization(null, null, out requestToken)); + authorizePopup.Owner = this; + bool? result = authorizePopup.ShowDialog(); + if (result.HasValue && result.Value) { + accessToken = authorizePopup.AccessToken; + } else { + return; + } + } + HttpDeliveryMethods resourceHttpMethod = resourceHttpMethodList.SelectedIndex < 2 ? HttpDeliveryMethods.GetRequest : HttpDeliveryMethods.PostRequest; + if (resourceHttpMethodList.SelectedIndex == 1) { + resourceHttpMethod |= HttpDeliveryMethods.AuthorizationHeaderRequest; + } + var resourceEndpoint = new MessageReceivingEndpoint(resourceUrlBox.Text, resourceHttpMethod); + using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken)) { + resultsBox.Text = resourceResponse.GetResponseReader().ReadToEnd(); + } + } catch (DotNetOpenAuth.Messaging.ProtocolException ex) { + MessageBox.Show(this, ex.Message); + } + } } } diff --git a/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs b/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs index 710508d..8c93d2f 100644 --- a/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs +++ b/samples/OAuthServiceProvider/App_Code/DatabaseTokenManager.cs @@ -40,6 +40,10 @@ public class DatabaseTokenManager : IServiceProviderTokenManager { } } + public void UpdateToken(IServiceProviderRequestToken token) { + // Nothing to do here, since we're using Linq To SQL. + } + #endregion #region ITokenManager Members diff --git a/samples/OAuthServiceProvider/App_Code/Global.cs b/samples/OAuthServiceProvider/App_Code/Global.cs index b343dcd..10b3cba 100644 --- a/samples/OAuthServiceProvider/App_Code/Global.cs +++ b/samples/OAuthServiceProvider/App_Code/Global.cs @@ -92,7 +92,15 @@ public class Global : HttpApplication { private void Application_Start(object sender, EventArgs e) { log4net.Config.XmlConfigurator.Configure(); Logger.Info("Sample starting..."); - Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, "/"); + string appPath = HttpContext.Current.Request.ApplicationPath; + if (!appPath.EndsWith("/")) { + appPath += "/"; + } + + // This will break in IIS Integrated Pipeline mode, since applications + // start before the first incoming request context is available. + // TODO: fix this. + Constants.WebRootUrl = new Uri(HttpContext.Current.Request.Url, appPath); var tokenManager = new DatabaseTokenManager(); Global.TokenManager = tokenManager; } diff --git a/samples/OAuthServiceProvider/App_Code/OAuthAuthorizationManager.cs b/samples/OAuthServiceProvider/App_Code/OAuthAuthorizationManager.cs index 8589932..ee90364 100644 --- a/samples/OAuthServiceProvider/App_Code/OAuthAuthorizationManager.cs +++ b/samples/OAuthServiceProvider/App_Code/OAuthAuthorizationManager.cs @@ -24,34 +24,38 @@ public class OAuthAuthorizationManager : ServiceAuthorizationManager { HttpRequestMessageProperty httpDetails = operationContext.RequestContext.RequestMessage.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty; Uri requestUri = operationContext.RequestContext.RequestMessage.Properties["OriginalHttpRequestUri"] as Uri; ServiceProvider sp = Constants.CreateServiceProvider(); - var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri); - if (auth != null) { - var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken); - - var principal = sp.CreatePrincipal(auth); - var policy = new OAuthPrincipalAuthorizationPolicy(principal); - var policies = new List<IAuthorizationPolicy> { - policy, - }; - - var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); - if (operationContext.IncomingMessageProperties.Security != null) { - operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; - } else { - operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { - ServiceSecurityContext = securityContext, + try { + var auth = sp.ReadProtectedResourceAuthorization(httpDetails, requestUri); + if (auth != null) { + var accessToken = Global.DataContext.OAuthTokens.Single(token => token.Token == auth.AccessToken); + + var principal = sp.CreatePrincipal(auth); + var policy = new OAuthPrincipalAuthorizationPolicy(principal); + var policies = new List<IAuthorizationPolicy> { + policy, }; - } - securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { - principal.Identity, - }; + var securityContext = new ServiceSecurityContext(policies.AsReadOnly()); + if (operationContext.IncomingMessageProperties.Security != null) { + operationContext.IncomingMessageProperties.Security.ServiceSecurityContext = securityContext; + } else { + operationContext.IncomingMessageProperties.Security = new SecurityMessageProperty { + ServiceSecurityContext = securityContext, + }; + } + + securityContext.AuthorizationContext.Properties["Identities"] = new List<IIdentity> { + principal.Identity, + }; - // Only allow this method call if the access token scope permits it. - string[] scopes = accessToken.Scope.Split('|'); - if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) { - return true; + // Only allow this method call if the access token scope permits it. + string[] scopes = accessToken.Scope.Split('|'); + if (scopes.Contains(operationContext.IncomingMessageHeaders.Action)) { + return true; + } } + } catch (ProtocolException ex) { + Global.Logger.Error("Error processing OAuth messages.", ex); } return false; diff --git a/samples/OAuthServiceProvider/Members/Authorize.aspx.cs b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs index f936c60..1e981a3 100644 --- a/samples/OAuthServiceProvider/Members/Authorize.aspx.cs +++ b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs @@ -63,7 +63,9 @@ public partial class Authorize : System.Web.UI.Page { string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10); verificationCodeLabel.Text = verifier; ITokenContainingMessage requestTokenMessage = pending; - Global.TokenManager.GetRequestToken(requestTokenMessage.Token).VerificationCode = verifier; + var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token); + requestToken.VerificationCode = verifier; + Global.TokenManager.UpdateToken(requestToken); } } } diff --git a/samples/OAuthServiceProvider/Web.config b/samples/OAuthServiceProvider/Web.config index d039daa..3ea490f 100644 --- a/samples/OAuthServiceProvider/Web.config +++ b/samples/OAuthServiceProvider/Web.config @@ -3,6 +3,7 @@ <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false"/> + <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection" requirePermission="false" allowLocation="true"/> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> @@ -34,6 +35,12 @@ </settings> </system.net> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> + <dotNetOpenAuth> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> + </dotNetOpenAuth> + <appSettings/> <connectionStrings> <add name="DatabaseConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" @@ -54,6 +61,7 @@ <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <authentication mode="Forms"> diff --git a/samples/OpenIdOfflineProvider/App.config b/samples/OpenIdOfflineProvider/App.config index cd04b13..7263338 100644 --- a/samples/OpenIdOfflineProvider/App.config +++ b/samples/OpenIdOfflineProvider/App.config @@ -1,9 +1,20 @@ <?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> + <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> <section name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth" requirePermission="false" allowLocation="true"/> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false"/> </configSections> + + <!-- 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. + It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. --> + <uri> + <idn enabled="All"/> + <iriParsing enabled="true"/> + </uri> + + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> <dotNetOpenAuth> <messaging> <untrustedWebRequest> @@ -13,6 +24,8 @@ </whitelistHosts> </untrustedWebRequest> </messaging> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true"/> </dotNetOpenAuth> <log4net> <appender name="TextBoxAppender" type="log4net.Appender.TextWriterAppender"> diff --git a/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj b/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj index bb307a4..43a8093 100644 --- a/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj +++ b/samples/OpenIdOfflineProvider/OpenIdOfflineProvider.csproj @@ -57,10 +57,8 @@ <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> - <PropertyGroup Condition=" '$(Sign)' == 'true' "> + <PropertyGroup> <SignAssembly>true</SignAssembly> - <AssemblyOriginatorKeyFile>..\..\src\official-build-key.pfx</AssemblyOriginatorKeyFile> - <DefineConstants>$(DefineConstants);StrongNameSigned</DefineConstants> </PropertyGroup> <ItemGroup> <Reference Include="log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL"> diff --git a/samples/OpenIdOfflineProvider/TextBoxTextWriter.cs b/samples/OpenIdOfflineProvider/TextBoxTextWriter.cs index 8118986..5319a78 100644 --- a/samples/OpenIdOfflineProvider/TextBoxTextWriter.cs +++ b/samples/OpenIdOfflineProvider/TextBoxTextWriter.cs @@ -71,7 +71,7 @@ namespace DotNetOpenAuth.OpenIdOfflineProvider { /// Verifies conditions that should be true for any valid state of this object. /// </summary> [ContractInvariantMethod] - protected void ObjectInvariant() { + private void ObjectInvariant() { Contract.Invariant(this.Box != null); } diff --git a/samples/OpenIdProviderMvc/Web.config b/samples/OpenIdProviderMvc/Web.config index f36bfcf..ba96c2a 100644 --- a/samples/OpenIdProviderMvc/Web.config +++ b/samples/OpenIdProviderMvc/Web.config @@ -1,12 +1,4 @@ <?xml version="1.0"?> -<!-- - Note: As an alternative to hand editing this file you can use the - web admin tool to configure settings for your application. Use - the Website->Asp.Net Configuration option in Visual Studio. - A full list of settings and comments can be found in - machine.config.comments usually located in - \Windows\Microsoft.Net\Framework\v2.x\Config ---> <configuration> <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> @@ -67,6 +59,8 @@ </whitelistHosts> </untrustedWebRequest> </messaging> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> </dotNetOpenAuth> <appSettings/> @@ -87,6 +81,7 @@ <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <!-- diff --git a/samples/OpenIdProviderWebForms/Code/InMemoryConsumerDescription.cs b/samples/OpenIdProviderWebForms/Code/InMemoryConsumerDescription.cs new file mode 100644 index 0000000..de4505d --- /dev/null +++ b/samples/OpenIdProviderWebForms/Code/InMemoryConsumerDescription.cs @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------- +// <copyright file="InMemoryConsumerDescription.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace OpenIdProviderWebForms.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetOpenAuth.OAuth.ChannelElements; + + public class InMemoryConsumerDescription : IConsumerDescription { + #region IConsumerDescription Members + + public string Key { get; set; } + + public string Secret { get; set; } + + public System.Security.Cryptography.X509Certificates.X509Certificate2 Certificate { get; set; } + + public Uri Callback { get; set; } + + public DotNetOpenAuth.OAuth.VerificationCodeFormat VerificationCodeFormat { get; set; } + + public int VerificationCodeLength { get; set; } + + #endregion + } +} diff --git a/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderAccessToken.cs b/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderAccessToken.cs new file mode 100644 index 0000000..7e26b45 --- /dev/null +++ b/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderAccessToken.cs @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------- +// <copyright file="InMemoryServiceProviderAccessToken.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace OpenIdProviderWebForms.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetOpenAuth.OAuth.ChannelElements; + + public class InMemoryServiceProviderAccessToken : IServiceProviderAccessToken { + #region IServiceProviderAccessToken Members + + public string Token { get; set; } + + public DateTime? ExpirationDate { get; set; } + + public string Username { get; set; } + + public string[] Roles { get; set; } + + #endregion + + public string Secret { get; set; } + + public string Scope { get; set; } + } +} diff --git a/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderRequestToken.cs b/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderRequestToken.cs new file mode 100644 index 0000000..9c02427 --- /dev/null +++ b/samples/OpenIdProviderWebForms/Code/InMemoryServiceProviderRequestToken.cs @@ -0,0 +1,42 @@ +//----------------------------------------------------------------------- +// <copyright file="InMemoryServiceProviderRequestToken.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace OpenIdProviderWebForms.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetOpenAuth.OAuth.ChannelElements; + + public class InMemoryServiceProviderRequestToken : IServiceProviderRequestToken { + /// <summary> + /// Initializes a new instance of the <see cref="InMemoryServiceProviderRequestToken"/> class. + /// </summary> + public InMemoryServiceProviderRequestToken() { + this.CreatedOn = DateTime.Now; + } + + #region IServiceProviderRequestToken Members + + public string Token { get; set; } + + public string ConsumerKey { get; set; } + + public DateTime CreatedOn { get; set; } + + public Uri Callback { get; set; } + + public string VerificationCode { get; set; } + + public Version ConsumerVersion { get; set; } + + #endregion + + public string Secret { get; set; } + + public string Scope { get; set; } + } +} diff --git a/samples/OpenIdProviderWebForms/Code/InMemoryTokenManager.cs b/samples/OpenIdProviderWebForms/Code/InMemoryTokenManager.cs new file mode 100644 index 0000000..b04f736 --- /dev/null +++ b/samples/OpenIdProviderWebForms/Code/InMemoryTokenManager.cs @@ -0,0 +1,117 @@ +//----------------------------------------------------------------------- +// <copyright file="InMemoryTokenManager.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace OpenIdProviderWebForms.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using DotNetOpenAuth.OpenId.Extensions.OAuth; + + /// <summary> + /// A simple in-memory token manager. JUST FOR PURPOSES OF KEEPING THE SAMPLE SIMPLE. + /// </summary> + /// <remarks> + /// This is merely a sample app. A real web app SHOULD NEVER store a memory-only + /// token manager in application. It should be an IServiceProviderTokenManager + /// implementation that is bound to a database. + /// </remarks> + public class InMemoryTokenManager : IServiceProviderTokenManager, IOpenIdOAuthTokenManager, ICombinedOpenIdProviderTokenManager { + private Dictionary<string, InMemoryServiceProviderRequestToken> requestTokens = new Dictionary<string, InMemoryServiceProviderRequestToken>(); + private Dictionary<string, InMemoryServiceProviderAccessToken> accessTokens = new Dictionary<string, InMemoryServiceProviderAccessToken>(); + + /// <summary> + /// Initializes a new instance of the <see cref="InMemoryTokenManager"/> class. + /// </summary> + internal InMemoryTokenManager() { + } + + #region IServiceProviderTokenManager Members + + public IConsumerDescription GetConsumer(string consumerKey) { + return new InMemoryConsumerDescription { + Key = consumerKey, + Secret = "some crazy secret", + }; + } + + public IServiceProviderRequestToken GetRequestToken(string token) { + return this.requestTokens[token]; + } + + public IServiceProviderAccessToken GetAccessToken(string token) { + throw new NotImplementedException(); + } + + public void UpdateToken(IServiceProviderRequestToken token) { + // Nothing to do here, since there's not database in this sample. + } + + #endregion + + #region ITokenManager Members + + public string GetTokenSecret(string token) { + if (this.requestTokens.ContainsKey(token)) { + return this.requestTokens[token].Secret; + } else { + return this.accessTokens[token].Secret; + } + } + + public void StoreNewRequestToken(DotNetOpenAuth.OAuth.Messages.UnauthorizedTokenRequest request, DotNetOpenAuth.OAuth.Messages.ITokenSecretContainingMessage response) { + throw new NotImplementedException(); + } + + public bool IsRequestTokenAuthorized(string requestToken) { + // In OpenID+OAuth scenarios, request tokens are always authorized. + return true; + } + + public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { + this.requestTokens.Remove(requestToken); + this.accessTokens[accessToken] = new InMemoryServiceProviderAccessToken { + Token = accessToken, + Secret = accessTokenSecret, + }; + } + + public TokenType GetTokenType(string token) { + if (this.requestTokens.ContainsKey(token)) { + return TokenType.RequestToken; + } else if (this.accessTokens.ContainsKey(token)) { + return TokenType.AccessToken; + } else { + return TokenType.InvalidToken; + } + } + + #endregion + + #region IOpenIdOAuthTokenManager Members + + public void StoreOpenIdAuthorizedRequestToken(string consumerKey, AuthorizationApprovedResponse authorization) { + this.requestTokens[authorization.RequestToken] = new InMemoryServiceProviderRequestToken { + Token = authorization.RequestToken, + Scope = authorization.Scope, + ConsumerVersion = authorization.Version, + }; + } + + #endregion + + #region ICombinedOpenIdProviderTokenManager Members + + public string GetConsumerKey(DotNetOpenAuth.OpenId.Realm realm) { + // We just use the realm as the consumer key, like Google does. + return realm; + } + + #endregion + } +} diff --git a/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs b/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs new file mode 100644 index 0000000..cc4beff --- /dev/null +++ b/samples/OpenIdProviderWebForms/Code/OAuthHybrid.cs @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------- +// <copyright file="OAuthHybrid.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +namespace OpenIdProviderWebForms.Code { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.OAuth.ChannelElements; + + internal class OAuthHybrid { + /// <summary> + /// Initializes static members of the <see cref="OAuthHybrid"/> class. + /// </summary> + static OAuthHybrid() { + ServiceProvider = new ServiceProvider(GetServiceDescription(), TokenManager); + } + + internal static IServiceProviderTokenManager TokenManager { + get { + // This is merely a sample app. A real web app SHOULD NEVER store a memory-only + // token manager in application. It should be an IServiceProviderTokenManager + // implementation that is bound to a database. + var tokenManager = (IServiceProviderTokenManager)HttpContext.Current.Application["TokenManager"]; + if (tokenManager == null) { + HttpContext.Current.Application["TokenManager"] = tokenManager = new InMemoryTokenManager(); + } + + return tokenManager; + } + } + + internal static ServiceProvider ServiceProvider { get; private set; } + + internal static ServiceProviderDescription GetServiceDescription() { + return new ServiceProviderDescription { + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, + }; + } + } +} diff --git a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj index ceea842..ffb0f2f 100644 --- a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj +++ b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj @@ -83,12 +83,20 @@ <Content Include="user_xrds.aspx" /> </ItemGroup> <ItemGroup> + <Compile Include="access_token.ashx.cs"> + <DependentUpon>access_token.ashx</DependentUpon> + </Compile> + <Compile Include="Code\InMemoryConsumerDescription.cs" /> + <Compile Include="Code\InMemoryServiceProviderAccessToken.cs" /> <Compile Include="Code\CustomStore.cs" /> <Compile Include="Code\CustomStoreDataSet.Designer.cs"> <DependentUpon>CustomStoreDataSet.xsd</DependentUpon> <AutoGen>True</AutoGen> <DesignTime>True</DesignTime> </Compile> + <Compile Include="Code\InMemoryServiceProviderRequestToken.cs" /> + <Compile Include="Code\InMemoryTokenManager.cs" /> + <Compile Include="Code\OAuthHybrid.cs" /> <Compile Include="Code\ReadOnlyXmlMembershipProvider.cs" /> <Compile Include="Code\TracePageAppender.cs" /> <Compile Include="Code\Util.cs" /> @@ -157,6 +165,7 @@ <Content Include="TracePage.aspx" /> </ItemGroup> <ItemGroup> + <Content Include="access_token.ashx" /> <None Include="Code\CustomStoreDataSet.xsc"> <DependentUpon>CustomStoreDataSet.xsd</DependentUpon> </None> @@ -190,7 +199,7 @@ <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> <WebProjectProperties> <UseIIS>False</UseIIS> - <AutoAssignPort>True</AutoAssignPort> + <AutoAssignPort>False</AutoAssignPort> <DevelopmentServerPort>4860</DevelopmentServerPort> <DevelopmentServerVPath>/</DevelopmentServerVPath> <IISUrl> diff --git a/samples/OpenIdProviderWebForms/Web.config b/samples/OpenIdProviderWebForms/Web.config index 3aba822..9cacf9d 100644 --- a/samples/OpenIdProviderWebForms/Web.config +++ b/samples/OpenIdProviderWebForms/Web.config @@ -1,12 +1,4 @@ <?xml version="1.0"?> -<!-- - Note: As an alternative to hand editing this file you can use the - web admin tool to configure settings for your application. Use - the Website->Asp.Net Configuration option in Visual Studio. - A full list of settings and comments can be found in - machine.config.comments usually located in - \Windows\Microsoft.Net\Framework\v2.x\Config ---> <configuration> <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/> @@ -66,6 +58,8 @@ </whitelistHosts> </untrustedWebRequest> </messaging> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> </dotNetOpenAuth> <system.web> @@ -81,6 +75,7 @@ <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <sessionState mode="InProc" cookieless="false"/> diff --git a/samples/OpenIdProviderWebForms/access_token.ashx b/samples/OpenIdProviderWebForms/access_token.ashx new file mode 100644 index 0000000..dcb088e --- /dev/null +++ b/samples/OpenIdProviderWebForms/access_token.ashx @@ -0,0 +1 @@ +<%@ WebHandler Language="C#" CodeBehind="access_token.ashx.cs" Class="OpenIdProviderWebForms.access_token" %> diff --git a/samples/OpenIdProviderWebForms/access_token.ashx.cs b/samples/OpenIdProviderWebForms/access_token.ashx.cs new file mode 100644 index 0000000..b895da9 --- /dev/null +++ b/samples/OpenIdProviderWebForms/access_token.ashx.cs @@ -0,0 +1,23 @@ +namespace OpenIdProviderWebForms { + using System; + using System.Collections.Generic; + using System.Linq; + using System.Web; + using System.Web.Services; + using DotNetOpenAuth.OAuth; + using OpenIdProviderWebForms.Code; + + [WebService(Namespace = "http://tempuri.org/")] + [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] + public class access_token : IHttpHandler { + public bool IsReusable { + get { return true; } + } + + public void ProcessRequest(HttpContext context) { + var request = OAuthHybrid.ServiceProvider.ReadAccessTokenRequest(); + var response = OAuthHybrid.ServiceProvider.PrepareAccessTokenMessage(request); + OAuthHybrid.ServiceProvider.Channel.Send(response); + } + } +} diff --git a/samples/OpenIdProviderWebForms/decide.aspx b/samples/OpenIdProviderWebForms/decide.aspx index 4a6e2d8..d63364e 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx +++ b/samples/OpenIdProviderWebForms/decide.aspx @@ -17,6 +17,10 @@ <td><asp:Label runat="server" ID='realmLabel' /> </td> </tr> </table> + <asp:Panel runat="server" ID="OAuthPanel" Visible="false"> + <p>In addition the relying party has asked for permission to access your private data. </p> + <asp:CheckBox runat="server" Text="Allow the relying party to access my private data" ID="oauthPermission" /> + </asp:Panel> <p>Allow this to proceed? </p> <uc1:ProfileFields ID="profileFields" runat="server" Visible="false" /> <asp:Button ID="yes_button" OnClick="Yes_Click" Text=" yes " runat="Server" /> diff --git a/samples/OpenIdProviderWebForms/decide.aspx.cs b/samples/OpenIdProviderWebForms/decide.aspx.cs index 3a14cf7..b392d85 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx.cs +++ b/samples/OpenIdProviderWebForms/decide.aspx.cs @@ -6,6 +6,7 @@ namespace OpenIdProviderWebForms { using DotNetOpenAuth.OpenId.Extensions.ProviderAuthenticationPolicy; using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration; using DotNetOpenAuth.OpenId.Provider; + using OpenIdProviderWebForms.Code; /// <summary> /// Page for giving the user the option to continue or cancel out of authentication with a consumer. @@ -21,6 +22,11 @@ namespace OpenIdProviderWebForms { this.realmLabel.Text = ProviderEndpoint.PendingRequest.Realm.ToString(); + var oauthRequest = OAuthHybrid.ServiceProvider.ReadAuthorizationRequest(ProviderEndpoint.PendingRequest); + if (oauthRequest != null) { + this.OAuthPanel.Visible = true; + } + if (ProviderEndpoint.PendingAuthenticationRequest != null) { if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity) { ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier = Code.Util.BuildIdentityUrl(); @@ -51,6 +57,22 @@ namespace OpenIdProviderWebForms { } protected void Yes_Click(object sender, EventArgs e) { + if (!Page.IsValid) { + return; + } + + if (this.OAuthPanel.Visible) { + string grantedScope = null; + if (this.oauthPermission.Checked) { + // This SIMPLE sample merely uses the realm as the consumerKey, + // but in a real app this will probably involve a database lookup to translate + // the realm to a known consumerKey. + grantedScope = string.Empty; // we don't scope individual access rights on this sample + } + + OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope); + } + var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>(); ClaimsResponse sregResponse = null; if (sregRequest != null) { diff --git a/samples/OpenIdProviderWebForms/decide.aspx.designer.cs b/samples/OpenIdProviderWebForms/decide.aspx.designer.cs index 05386cd..3aa6271 100644 --- a/samples/OpenIdProviderWebForms/decide.aspx.designer.cs +++ b/samples/OpenIdProviderWebForms/decide.aspx.designer.cs @@ -50,6 +50,24 @@ namespace OpenIdProviderWebForms { protected global::System.Web.UI.WebControls.Label realmLabel; /// <summary> + /// OAuthPanel control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.Panel OAuthPanel; + + /// <summary> + /// oauthPermission control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.CheckBox oauthPermission; + + /// <summary> /// profileFields control. /// </summary> /// <remarks> diff --git a/samples/OpenIdRelyingPartyMvc/Content/css/openidlogin.css b/samples/OpenIdRelyingPartyMvc/Content/css/openidlogin.css index 20338c4..5f401d0 100644 --- a/samples/OpenIdRelyingPartyMvc/Content/css/openidlogin.css +++ b/samples/OpenIdRelyingPartyMvc/Content/css/openidlogin.css @@ -52,7 +52,7 @@ #openidlogin .provider { - cursor: hand; + cursor: pointer; } #openidlogin .buttons .provider diff --git a/samples/OpenIdRelyingPartyMvc/Web.config b/samples/OpenIdRelyingPartyMvc/Web.config index 8becaf6..ac59296 100644 --- a/samples/OpenIdRelyingPartyMvc/Web.config +++ b/samples/OpenIdRelyingPartyMvc/Web.config @@ -1,12 +1,4 @@ <?xml version="1.0"?> -<!-- - Note: As an alternative to hand editing this file you can use the - web admin tool to configure settings for your application. Use - the Website->Asp.Net Configuration option in Visual Studio. - A full list of settings and comments can be found in - machine.config.comments usually located in - \Windows\Microsoft.Net\Framework\v2.x\Config ---> <configuration> <configSections> <section name="uri" type="System.Configuration.UriSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> @@ -62,6 +54,8 @@ </whitelistHosts> </untrustedWebRequest> </messaging> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> </dotNetOpenAuth> <appSettings/> @@ -83,6 +77,7 @@ <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <remove assembly="DotNetOpenAuth.Contracts"/> </assemblies> </compilation> <!-- diff --git a/samples/OpenIdRelyingPartyWebForms/Code/InMemoryTokenManager.cs b/samples/OpenIdRelyingPartyWebForms/Code/InMemoryTokenManager.cs index e665cb6..09a5b08 100644 --- a/samples/OpenIdRelyingPartyWebForms/Code/InMemoryTokenManager.cs +++ b/samples/OpenIdRelyingPartyWebForms/Code/InMemoryTokenManager.cs @@ -46,20 +46,6 @@ namespace OpenIdRelyingPartyWebForms.Code { this.tokensAndSecrets[response.Token] = response.TokenSecret; } - /// <summary> - /// Checks whether a given request token has already been authorized - /// by some user for use by the Consumer that requested it. - /// </summary> - /// <param name="requestToken">The Consumer's request token.</param> - /// <returns> - /// True if the request token has already been fully authorized by the user - /// who owns the relevant protected resources. False if the token has not yet - /// been authorized, has expired or does not exist. - /// </returns> - public bool IsRequestTokenAuthorized(string requestToken) { - throw new NotImplementedException(); - } - public void ExpireRequestTokenAndStoreNewAccessToken(string consumerKey, string requestToken, string accessToken, string accessTokenSecret) { this.tokensAndSecrets.Remove(requestToken); this.tokensAndSecrets[accessToken] = accessTokenSecret; diff --git a/samples/OpenIdRelyingPartyWebForms/Global.asax.cs b/samples/OpenIdRelyingPartyWebForms/Global.asax.cs index ac74853..6583289 100644 --- a/samples/OpenIdRelyingPartyWebForms/Global.asax.cs +++ b/samples/OpenIdRelyingPartyWebForms/Global.asax.cs @@ -42,6 +42,20 @@ } } + internal static InMemoryTokenManager OwnSampleOPHybridTokenManager { + get { + var tokenManager = (InMemoryTokenManager)HttpContext.Current.Application["OwnSampleOPHybridTokenManager"]; + if (tokenManager == null) { + string consumerKey = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Request.ApplicationPath).AbsoluteUri; + string consumerSecret = "some crazy secret"; + tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); + HttpContext.Current.Application["OwnSampleOPHybridTokenManager"] = tokenManager; + } + + return tokenManager; + } + } + public static string ToString(NameValueCollection collection) { using (StringWriter sw = new StringWriter()) { foreach (string key in collection.Keys) { diff --git a/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj b/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj index d3bf92c..6f5df5c 100644 --- a/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj +++ b/samples/OpenIdRelyingPartyWebForms/OpenIdRelyingPartyWebForms.csproj @@ -101,6 +101,13 @@ <Compile Include="Code\InMemoryTokenManager.cs" /> <Compile Include="Code\State.cs" /> <Compile Include="Code\TracePageAppender.cs" /> + <Compile Include="loginPlusOAuthSampleOP.aspx.cs"> + <DependentUpon>loginPlusOAuthSampleOP.aspx</DependentUpon> + <SubType>ASPXCodeBehind</SubType> + </Compile> + <Compile Include="loginPlusOAuthSampleOP.aspx.designer.cs"> + <DependentUpon>loginPlusOAuthSampleOP.aspx</DependentUpon> + </Compile> <Compile Include="Global.asax.cs"> <DependentUpon>Global.asax</DependentUpon> </Compile> @@ -169,6 +176,7 @@ <Content Include="xrds.aspx" /> </ItemGroup> <ItemGroup> + <Content Include="loginPlusOAuthSampleOP.aspx" /> <Content Include="images\attention.png" /> <Content Include="images\dotnetopenid_tiny.gif" /> <Content Include="images\openid_login.gif" /> diff --git a/samples/OpenIdRelyingPartyWebForms/Web.config b/samples/OpenIdRelyingPartyWebForms/Web.config index f952a6f..a83430f 100644 --- a/samples/OpenIdRelyingPartyWebForms/Web.config +++ b/samples/OpenIdRelyingPartyWebForms/Web.config @@ -23,6 +23,7 @@ <!--<servicePointManager checkCertificateRevocationList="true"/>--> </settings> </system.net> + <!-- this is an optional configuration section where aspects of dotnetopenauth can be customized --> <dotNetOpenAuth> <openid> @@ -46,6 +47,8 @@ </whitelistHosts> </untrustedWebRequest> </messaging> + <!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --> + <reporting enabled="true" /> </dotNetOpenAuth> <appSettings> @@ -58,7 +61,11 @@ <system.web> <!--<sessionState cookieless="true" />--> - <compilation debug="true"/> + <compilation debug="true"> + <assemblies> + <remove assembly="DotNetOpenAuth.Contracts"/> + </assemblies> + </compilation> <customErrors mode="RemoteOnly"/> <authentication mode="Forms"> <forms name="OpenIdRelyingPartySession"/> <!-- named cookie prevents conflicts with other samples --> diff --git a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx index 232cf3f..d542834 100644 --- a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx +++ b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx @@ -25,20 +25,25 @@ td <asp:Content runat="server" ContentPlaceHolderID="Main"> <script type="text/javascript"> - function onauthenticated(sender) { + function onauthenticated(sender, e) { var emailBox = document.getElementById('<%= emailAddressBox.ClientID %>'); emailBox.disabled = false; emailBox.title = null; // remove tooltip describing why the box was disabled. // the sreg response may not always be included. - if (sender.sreg) { + if (e && e.sreg) { // and the email field may not always be included in the sreg response. - if (sender.sreg.email) { emailBox.value = sender.sreg.email; } + if (e.sreg.email) { emailBox.value = e.sreg.email; } } } </script> <asp:MultiView runat="server" ID="multiView" ActiveViewIndex='0'> <asp:View runat="server" ID="commentSubmission"> + <p> + The scenario here is that you've just read a blog post and you want to comment on + that post. You're <b>not</b> actually logging into the web site by entering your + OpenID here, but your OpenID <i>will</i> be verified before the comment is posted. + </p> <table> <tr> <td> @@ -48,7 +53,7 @@ td <openid:OpenIdAjaxTextBox ID="OpenIdAjaxTextBox1" runat="server" CssClass="openidtextbox" OnLoggingIn="OpenIdAjaxTextBox1_LoggingIn" OnLoggedIn="OpenIdAjaxTextBox1_LoggedIn" - OnClientAssertionReceived="onauthenticated(sender)" + OnClientAssertionReceived="onauthenticated(sender, e)" OnUnconfirmedPositiveAssertion="OpenIdAjaxTextBox1_UnconfirmedPositiveAssertion" /> <asp:RequiredFieldValidator ID="openidRequiredValidator" runat="server" ControlToValidate="OpenIdAjaxTextBox1" ValidationGroup="openidVG" @@ -74,7 +79,7 @@ td </td> </tr> <tr> - <td /> + <td></td> <td> <asp:Button runat="server" Text="Submit" ID="submitButton" OnClick="submitButton_Click" /> </td> diff --git a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs index de44e35..f7d44d5 100644 --- a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs @@ -13,7 +13,7 @@ protected void OpenIdAjaxTextBox1_LoggingIn(object sender, OpenIdEventArgs e) { e.Request.AddExtension(new ClaimsRequest { - Email = DemandLevel.Request, + Email = DemandLevel.Require, }); } diff --git a/samples/OpenIdRelyingPartyWebForms/login.aspx b/samples/OpenIdRelyingPartyWebForms/login.aspx index 281725c..d0cdb1a 100644 --- a/samples/OpenIdRelyingPartyWebForms/login.aspx +++ b/samples/OpenIdRelyingPartyWebForms/login.aspx @@ -7,8 +7,7 @@ <rp:OpenIdLogin ID="OpenIdLogin1" runat="server" CssClass="openid_login" RequestCountry="Request" RequestEmail="Require" RequestGender="Require" RequestPostalCode="Require" RequestTimeZone="Require" RememberMeVisible="True" PolicyUrl="~/PrivacyPolicy.aspx" TabIndex="1" - OnLoggedIn="OpenIdLogin1_LoggedIn" OnLoggingIn="OpenIdLogin1_LoggingIn" - OnSetupRequired="OpenIdLogin1_SetupRequired" /> + OnLoggedIn="OpenIdLogin1_LoggedIn" OnLoggingIn="OpenIdLogin1_LoggingIn" /> <fieldset title="Knobs"> <asp:CheckBox ID="requireSslCheckBox" runat="server" Text="RequireSsl (high security) mode" @@ -22,11 +21,8 @@ </asp:CheckBoxList> <p>Try the PPID identifier functionality against the OpenIDProviderMvc sample.</p> </fieldset> - <br /> - <asp:Label ID="setupRequiredLabel" runat="server" EnableViewState="False" Text="You must log into your Provider first to use Immediate mode." - Visible="False" /> <p> <rp:OpenIdButton runat="server" ImageUrl="~/images/yahoo.png" Text="Login with Yahoo!" ID="yahooLoginButton" - Identifier="https://me.yahoo.com/" /> + Identifier="https://me.yahoo.com/" OnLoggingIn="OpenIdLogin1_LoggingIn" OnLoggedIn="OpenIdLogin1_LoggedIn" /> </p> </asp:Content> diff --git a/samples/OpenIdRelyingPartyWebForms/login.aspx.cs b/samples/OpenIdRelyingPartyWebForms/login.aspx.cs index 1de942a..6721e9b 100644 --- a/samples/OpenIdRelyingPartyWebForms/login.aspx.cs +++ b/samples/OpenIdRelyingPartyWebForms/login.aspx.cs @@ -35,10 +35,6 @@ namespace OpenIdRelyingPartyWebForms { State.PapePolicies = e.Response.GetExtension<PolicyResponse>(); } - protected void OpenIdLogin1_SetupRequired(object sender, OpenIdEventArgs e) { - this.setupRequiredLabel.Visible = true; - } - private void prepareRequest(IAuthenticationRequest request) { // Collect the PAPE policies requested by the user. List<string> policies = new List<string>(); diff --git a/samples/OpenIdRelyingPartyWebForms/login.aspx.designer.cs b/samples/OpenIdRelyingPartyWebForms/login.aspx.designer.cs index 944f5ff..4a2521c 100644 --- a/samples/OpenIdRelyingPartyWebForms/login.aspx.designer.cs +++ b/samples/OpenIdRelyingPartyWebForms/login.aspx.designer.cs @@ -41,15 +41,6 @@ namespace OpenIdRelyingPartyWebForms { protected global::System.Web.UI.WebControls.CheckBoxList papePolicies; /// <summary> - /// setupRequiredLabel control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.WebControls.Label setupRequiredLabel; - - /// <summary> /// yahooLoginButton control. /// </summary> /// <remarks> diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx new file mode 100644 index 0000000..863f335 --- /dev/null +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx @@ -0,0 +1,34 @@ +<%@ Page Language="C#" AutoEventWireup="True" CodeBehind="loginPlusOAuthSampleOP.aspx.cs" + Inherits="OpenIdRelyingPartyWebForms.loginPlusOAuthSampleOP" ValidateRequest="false" + MasterPageFile="~/Site.Master" %> + +<%@ Register Assembly="DotNetOpenAuth" Namespace="DotNetOpenAuth.OpenId.RelyingParty" + TagPrefix="rp" %> +<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="Main"> + <h2>Login Page </h2> + <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex='0'> + <asp:View ID="View1" runat="server"> + <asp:Label runat="server" Text="OpenIdProviderWebForms sample's OP Identifier or Claimed Identifier: " /> + <rp:OpenIdTextBox runat="server" ID="identifierBox" Text="http://localhost:4860/" + OnLoggingIn="identifierBox_LoggingIn" OnLoggedIn="identifierBox_LoggedIn" OnCanceled="identifierBox_Failed" + OnFailed="identifierBox_Failed" /> + <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="required" + ControlToValidate="identifierBox" /> + <br /> + <asp:Button ID="beginButton" runat="server" Text="Login + OAuth request" OnClick="beginButton_Click" /> + </asp:View> + <asp:View ID="AuthorizationGiven" runat="server"> + Authentication succeeded, and OAuth access was granted. + <p>The actual login step is aborted since this sample focuses on the process only + up to this point.</p> + </asp:View> + <asp:View ID="AuthorizationDenied" runat="server"> + Authentication succeeded, but OAuth access was denied. + <p>The actual login step is aborted since this sample focuses on the process only + up to this point.</p> + </asp:View> + <asp:View ID="AuthenticationFailed" runat="server"> + Authentication failed or was canceled. + </asp:View> + </asp:MultiView> +</asp:Content> diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs new file mode 100644 index 0000000..c7d3168 --- /dev/null +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs @@ -0,0 +1,62 @@ +namespace OpenIdRelyingPartyWebForms { + using System; + using System.Web.Security; + using DotNetOpenAuth.ApplicationBlock; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth; + using DotNetOpenAuth.OAuth.ChannelElements; + using DotNetOpenAuth.OAuth.Messages; + using DotNetOpenAuth.OpenId; + using DotNetOpenAuth.OpenId.Extensions.AttributeExchange; + using DotNetOpenAuth.OpenId.RelyingParty; + + public partial class loginPlusOAuthSampleOP : System.Web.UI.Page { + protected void Page_Load(object sender, EventArgs e) { + } + + protected void beginButton_Click(object sender, EventArgs e) { + if (!Page.IsValid) { + return; + } + + this.identifierBox.LogOn(); + } + + protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e) { + ServiceProviderDescription serviceDescription = new ServiceProviderDescription { + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, + }; + + WebConsumer consumer = new WebConsumer(serviceDescription, Global.OwnSampleOPHybridTokenManager); + consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName"); + } + + protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) { + State.FetchResponse = e.Response.GetExtension<FetchResponse>(); + + ServiceProviderDescription serviceDescription = new ServiceProviderDescription { + AccessTokenEndpoint = new MessageReceivingEndpoint(new Uri(e.Response.Provider.Uri, "/access_token.ashx"), HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest), + TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() }, + }; + WebConsumer consumer = new WebConsumer(serviceDescription, Global.OwnSampleOPHybridTokenManager); + + AuthorizedTokenResponse accessToken = consumer.ProcessUserAuthorization(e.Response); + if (accessToken != null) { + this.MultiView1.SetActiveView(this.AuthorizationGiven); + + // At this point, the access token would be somehow associated with the user + // account at the RP. + ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken); + } else { + this.MultiView1.SetActiveView(this.AuthorizationDenied); + } + + // Avoid the redirect + e.Cancel = true; + } + + protected void identifierBox_Failed(object sender, OpenIdEventArgs e) { + this.MultiView1.SetActiveView(this.AuthenticationFailed); + } + } +} diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.designer.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.designer.cs new file mode 100644 index 0000000..9bf29b9 --- /dev/null +++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.designer.cs @@ -0,0 +1,88 @@ +//------------------------------------------------------------------------------ +// <auto-generated> +// This code was generated by a tool. +// Runtime Version:2.0.50727.4918 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// </auto-generated> +//------------------------------------------------------------------------------ + +namespace OpenIdRelyingPartyWebForms { + + + public partial class loginPlusOAuthSampleOP { + + /// <summary> + /// MultiView1 control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.MultiView MultiView1; + + /// <summary> + /// View1 control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.View View1; + + /// <summary> + /// identifierBox control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::DotNetOpenAuth.OpenId.RelyingParty.OpenIdTextBox identifierBox; + + /// <summary> + /// RequiredFieldValidator1 control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1; + + /// <summary> + /// beginButton control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.Button beginButton; + + /// <summary> + /// AuthorizationGiven control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.View AuthorizationGiven; + + /// <summary> + /// AuthorizationDenied control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.View AuthorizationDenied; + + /// <summary> + /// AuthenticationFailed control. + /// </summary> + /// <remarks> + /// Auto-generated field. + /// To modify move field declaration from designer file to code-behind file. + /// </remarks> + protected global::System.Web.UI.WebControls.View AuthenticationFailed; + } +} diff --git a/samples/OpenIdRelyingPartyWebForms/logout.aspx b/samples/OpenIdRelyingPartyWebForms/logout.aspx index 71c0433..156f800 100644 --- a/samples/OpenIdRelyingPartyWebForms/logout.aspx +++ b/samples/OpenIdRelyingPartyWebForms/logout.aspx @@ -7,6 +7,7 @@ State.FriendlyLoginName = null; State.ProfileFields = null; System.Web.Security.FormsAuthentication.SignOut(); + DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingPartyControlBase.LogOff(); Response.Redirect("~/"); } </script> diff --git a/samples/OpenIdRelyingPartyWebForms/xrds.aspx b/samples/OpenIdRelyingPartyWebForms/xrds.aspx index 52e27f7..92983fd 100644 --- a/samples/OpenIdRelyingPartyWebForms/xrds.aspx +++ b/samples/OpenIdRelyingPartyWebForms/xrds.aspx @@ -17,7 +17,9 @@ is default.aspx. <URI priority="1"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/login.aspx"))%></URI> <URI priority="2"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/loginProgrammatic.aspx"))%></URI> <URI priority="3"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/ajaxlogin.aspx"))%></URI> - <URI priority="3"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/NoIdentityOpenId.aspx"))%></URI> + <URI priority="4"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/NoIdentityOpenId.aspx"))%></URI> + <URI priority="5"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/loginPlusOAuth.aspx"))%></URI> + <URI priority="6"><%=new Uri(Request.Url, Response.ApplyAppPathModifier("~/loginPlusOAuthSampleOP.aspx"))%></URI> </Service> <Service> <Type>http://specs.openid.net/extensions/ui/icon</Type> |