diff options
author | Andrew Arnott <andrewarnott@gmail.com> | 2008-11-03 17:22:00 -0800 |
---|---|---|
committer | Andrew <andrewarnott@gmail.com> | 2008-11-04 08:12:52 -0800 |
commit | 462e19abd9034c11a12cad30e9899740f2bef8ff (patch) | |
tree | e08667f1d69249f8daa6c348a919bd0fd5434415 /samples/Consumer | |
parent | 6a79be0eca3929d8fb4e797799dac8d6f7875475 (diff) | |
download | DotNetOpenAuth-462e19abd9034c11a12cad30e9899740f2bef8ff.zip DotNetOpenAuth-462e19abd9034c11a12cad30e9899740f2bef8ff.tar.gz DotNetOpenAuth-462e19abd9034c11a12cad30e9899740f2bef8ff.tar.bz2 |
Changed namepace and project names in preparation for merge with DotNetOpenId.
Diffstat (limited to 'samples/Consumer')
-rw-r--r-- | samples/Consumer/App_Code/InMemoryTokenManager.cs | 144 | ||||
-rw-r--r-- | samples/Consumer/App_Code/Logging.cs | 40 | ||||
-rw-r--r-- | samples/Consumer/Default.aspx | 22 | ||||
-rw-r--r-- | samples/Consumer/GoogleAddressBook.aspx.cs | 114 | ||||
-rw-r--r-- | samples/Consumer/MasterPage.master | 46 | ||||
-rw-r--r-- | samples/Consumer/SampleWcf.aspx.cs | 236 | ||||
-rw-r--r-- | samples/Consumer/Web.config | 322 |
7 files changed, 462 insertions, 462 deletions
diff --git a/samples/Consumer/App_Code/InMemoryTokenManager.cs b/samples/Consumer/App_Code/InMemoryTokenManager.cs index 6b20ad9..f36a396 100644 --- a/samples/Consumer/App_Code/InMemoryTokenManager.cs +++ b/samples/Consumer/App_Code/InMemoryTokenManager.cs @@ -1,72 +1,72 @@ -//-----------------------------------------------------------------------
-// <copyright file="InMemoryTokenManager.cs" company="Andrew Arnott">
-// Copyright (c) Andrew Arnott. All rights reserved.
-// </copyright>
-//-----------------------------------------------------------------------
-
-using System;
-using System.Collections.Generic;
-using System.Diagnostics;
-using DotNetOAuth.OAuth.ChannelElements;
-using DotNetOAuth.OAuth.Messages;
-
-public class InMemoryTokenManager : ITokenManager {
- private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>();
-
- public InMemoryTokenManager(string consumerKey, string consumerSecret) {
- this.ConsumerKey = consumerKey;
- this.ConsumerSecret = consumerSecret;
- }
-
- public string ConsumerKey { get; private set; }
-
- public string ConsumerSecret { get; private set; }
-
- #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];
- }
-
- public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) {
- 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;
- }
-
- /// <summary>
- /// Classifies a token as a request token or an access token.
- /// </summary>
- /// <param name="token">The token to classify.</param>
- /// <returns>Request or Access token, or invalid if the token is not recognized.</returns>
- public TokenType GetTokenType(string token) {
- throw new NotImplementedException();
- }
-
- #endregion
-}
+//----------------------------------------------------------------------- +// <copyright file="InMemoryTokenManager.cs" company="Andrew Arnott"> +// Copyright (c) Andrew Arnott. All rights reserved. +// </copyright> +//----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using DotNetOpenAuth.OAuth.ChannelElements; +using DotNetOpenAuth.OAuth.Messages; + +public class InMemoryTokenManager : ITokenManager { + private Dictionary<string, string> tokensAndSecrets = new Dictionary<string, string>(); + + public InMemoryTokenManager(string consumerKey, string consumerSecret) { + this.ConsumerKey = consumerKey; + this.ConsumerSecret = consumerSecret; + } + + public string ConsumerKey { get; private set; } + + public string ConsumerSecret { get; private set; } + + #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]; + } + + public void StoreNewRequestToken(UnauthorizedTokenRequest request, ITokenSecretContainingMessage response) { + 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; + } + + /// <summary> + /// Classifies a token as a request token or an access token. + /// </summary> + /// <param name="token">The token to classify.</param> + /// <returns>Request or Access token, or invalid if the token is not recognized.</returns> + public TokenType GetTokenType(string token) { + throw new NotImplementedException(); + } + + #endregion +} diff --git a/samples/Consumer/App_Code/Logging.cs b/samples/Consumer/App_Code/Logging.cs index cba9b4e..e97ff37 100644 --- a/samples/Consumer/App_Code/Logging.cs +++ b/samples/Consumer/App_Code/Logging.cs @@ -1,20 +1,20 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Web;
-
-/// <summary>
-/// Logging tools for this sample.
-/// </summary>
-public static class Logging {
- /// <summary>
- /// An application memory cache of recent log messages.
- /// </summary>
- public static StringBuilder LogMessages = new StringBuilder();
-
- /// <summary>
- /// The logger for this sample to use.
- /// </summary>
- public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOAuth.ConsumerSample");
-}
+using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Web; + +/// <summary> +/// Logging tools for this sample. +/// </summary> +public static class Logging { + /// <summary> + /// An application memory cache of recent log messages. + /// </summary> + public static StringBuilder LogMessages = new StringBuilder(); + + /// <summary> + /// The logger for this sample to use. + /// </summary> + public static log4net.ILog Logger = log4net.LogManager.GetLogger("DotNetOpenAuth.ConsumerSample"); +} diff --git a/samples/Consumer/Default.aspx b/samples/Consumer/Default.aspx index c150202..20e0f94 100644 --- a/samples/Consumer/Default.aspx +++ b/samples/Consumer/Default.aspx @@ -1,11 +1,11 @@ -<%@ Page Title="DotNetOAuth 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>Select a demo:</p>
- <ul>
- <li><a href="GoogleAddressBook.aspx">Download your Gmail address book</a></li>
- <li><a href="SampleWcf.aspx">Interop with Service Provider sample using WCF w/ OAuth</a></li>
- </ul>
-</asp:Content>
+<%@ 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>Select a demo:</p> + <ul> + <li><a href="GoogleAddressBook.aspx">Download your Gmail address book</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/Consumer/GoogleAddressBook.aspx.cs b/samples/Consumer/GoogleAddressBook.aspx.cs index 9fffdf2..838b286 100644 --- a/samples/Consumer/GoogleAddressBook.aspx.cs +++ b/samples/Consumer/GoogleAddressBook.aspx.cs @@ -1,57 +1,57 @@ -using System;
-using System.Linq;
-using System.Text;
-using System.Web;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-using System.Xml.Linq;
-using DotNetOAuth.ApplicationBlock;
-
-/// <summary>
-/// A page to demonstrate downloading a Gmail address book using OAuth.
-/// </summary>
-public partial class GoogleAddressBook : System.Web.UI.Page {
- 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);
-
- 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() });
- }
- }
- }
- }
-
- protected void authorizeButton_Click(object sender, EventArgs e) {
- if (!Page.IsValid) {
- return;
- }
-
- InMemoryTokenManager tokenManager = new InMemoryTokenManager(consumerKeyBox.Text, consumerSecretBox.Text);
- Session["TokenManager"] = tokenManager;
- var google = GoogleConsumer.CreateWebConsumer(tokenManager, consumerKeyBox.Text);
- GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts);
- }
-}
+using System; +using System.Linq; +using System.Text; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Xml.Linq; +using DotNetOpenAuth.ApplicationBlock; + +/// <summary> +/// A page to demonstrate downloading a Gmail address book using OAuth. +/// </summary> +public partial class GoogleAddressBook : System.Web.UI.Page { + 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); + + 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() }); + } + } + } + } + + protected void authorizeButton_Click(object sender, EventArgs e) { + if (!Page.IsValid) { + return; + } + + InMemoryTokenManager tokenManager = new InMemoryTokenManager(consumerKeyBox.Text, consumerSecretBox.Text); + Session["TokenManager"] = tokenManager; + var google = GoogleConsumer.CreateWebConsumer(tokenManager, consumerKeyBox.Text); + GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); + } +} diff --git a/samples/Consumer/MasterPage.master b/samples/Consumer/MasterPage.master index 08d139d..0044208 100644 --- a/samples/Consumer/MasterPage.master +++ b/samples/Consumer/MasterPage.master @@ -1,23 +1,23 @@ -<%@ Master Language="C#" %>
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<script runat="server">
-
-</script>
-
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head runat="server">
- <title>DotNetOAuth Consumer sample</title>
- <asp:ContentPlaceHolder ID="head" runat="server"/>
-</head>
-<body>
- <form id="form1" runat="server">
- <h1>DotNetOAuth Consumer ASP.NET WebForms sample</h1>
- <div>
- <asp:ContentPlaceHolder ID="Body" runat="server">
- </asp:ContentPlaceHolder>
- </div>
- </form>
-</body>
-</html>
+<%@ Master Language="C#" %> + +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + +<script runat="server"> + +</script> + +<html xmlns="http://www.w3.org/1999/xhtml"> +<head runat="server"> + <title>DotNetOpenAuth Consumer sample</title> + <asp:ContentPlaceHolder ID="head" runat="server"/> +</head> +<body> + <form id="form1" runat="server"> + <h1>DotNetOpenAuth Consumer ASP.NET WebForms sample</h1> + <div> + <asp:ContentPlaceHolder ID="Body" runat="server"> + </asp:ContentPlaceHolder> + </div> + </form> +</body> +</html> diff --git a/samples/Consumer/SampleWcf.aspx.cs b/samples/Consumer/SampleWcf.aspx.cs index ee776f1..d8cdc4f 100644 --- a/samples/Consumer/SampleWcf.aspx.cs +++ b/samples/Consumer/SampleWcf.aspx.cs @@ -1,118 +1,118 @@ -using System;
-using System.Collections.Generic;
-using System.Globalization;
-using System.Linq;
-using System.Net;
-using System.ServiceModel;
-using System.ServiceModel.Channels;
-using System.ServiceModel.Security;
-using System.Web.UI.WebControls;
-using DotNetOAuth;
-using DotNetOAuth.Messaging;
-using DotNetOAuth.OAuth;
-using DotNetOAuth.OAuth.ChannelElements;
-using SampleServiceProvider;
-
-/// <summary>
-/// Sample consumer of our Service Provider sample's WCF service.
-/// </summary>
-public partial class SampleWcf : System.Web.UI.Page {
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- if (Session["WcfTokenManager"] != null) {
- WebConsumer consumer = this.CreateConsumer();
- var accessTokenMessage = consumer.ProcessUserAuthorization();
- if (accessTokenMessage != null) {
- Session["WcfAccessToken"] = accessTokenMessage.AccessToken;
- authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken;
- }
- }
- }
- }
-
- protected void getAuthorizationButton_Click(object sender, EventArgs e) {
- WebConsumer consumer = this.CreateConsumer();
- UriBuilder callback = new UriBuilder(Request.Url);
- callback.Query = null;
- string[] scopes = (from item in scopeList.Items.OfType<ListItem>()
- where item.Selected
- select item.Value).ToArray();
- string scope = string.Join("|", scopes);
- var requestParams = new Dictionary<string, string> {
- { "scope", scope },
- };
- var response = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, null);
- consumer.Channel.Send(response).Send();
- }
-
- protected void getNameButton_Click(object sender, EventArgs e) {
- try {
- nameLabel.Text = CallService(client => client.GetName());
- } catch (SecurityAccessDeniedException) {
- nameLabel.Text = "Access denied!";
- }
- }
-
- protected void getAgeButton_Click(object sender, EventArgs e) {
- try {
- int? age = CallService(client => client.GetAge());
- ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
- } catch (SecurityAccessDeniedException) {
- ageLabel.Text = "Access denied!";
- }
- }
-
- protected void getFavoriteSites_Click(object sender, EventArgs e) {
- try {
- string[] favoriteSites = CallService(client => client.GetFavoriteSites());
- favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
- } catch (SecurityAccessDeniedException) {
- favoriteSitesLabel.Text = "Access denied!";
- }
- }
-
- private T CallService<T>(Func<DataApiClient, T> predicate) {
- DataApiClient client = new DataApiClient();
- var serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest);
- var accessToken = Session["WcfAccessToken"] as string;
- if (accessToken == null) {
- throw new InvalidOperationException("No access token!");
- }
- WebConsumer consumer = this.CreateConsumer();
- WebRequest httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken);
-
- HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty();
- httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
- using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) {
- OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
- return predicate(client);
- }
- }
-
- private WebConsumer CreateConsumer() {
- string consumerKey = "sampleconsumer";
- string consumerSecret = "samplesecret";
- var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager;
- if (tokenManager == null) {
- tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret);
- Session["WcfTokenManager"] = tokenManager;
- }
- MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint(
- new Uri("http://localhost:65169/ServiceProvider/OAuth.ashx"),
- HttpDeliveryMethods.PostRequest);
- WebConsumer consumer = new WebConsumer(
- new ServiceProviderDescription {
- RequestTokenEndpoint = oauthEndpoint,
- UserAuthorizationEndpoint = oauthEndpoint,
- AccessTokenEndpoint = oauthEndpoint,
- TamperProtectionElements = new DotNetOAuth.Messaging.ITamperProtectionChannelBindingElement[] {
- new HmacSha1SigningBindingElement(),
- },
- },
- tokenManager) {
- ConsumerKey = consumerKey,
- };
-
- return consumer;
- }
-}
+using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.ServiceModel; +using System.ServiceModel.Channels; +using System.ServiceModel.Security; +using System.Web.UI.WebControls; +using DotNetOpenAuth; +using DotNetOpenAuth.Messaging; +using DotNetOpenAuth.OAuth; +using DotNetOpenAuth.OAuth.ChannelElements; +using SampleServiceProvider; + +/// <summary> +/// Sample consumer of our Service Provider sample's WCF service. +/// </summary> +public partial class SampleWcf : System.Web.UI.Page { + protected void Page_Load(object sender, EventArgs e) { + if (!IsPostBack) { + if (Session["WcfTokenManager"] != null) { + WebConsumer consumer = this.CreateConsumer(); + var accessTokenMessage = consumer.ProcessUserAuthorization(); + if (accessTokenMessage != null) { + Session["WcfAccessToken"] = accessTokenMessage.AccessToken; + authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken; + } + } + } + } + + protected void getAuthorizationButton_Click(object sender, EventArgs e) { + WebConsumer consumer = this.CreateConsumer(); + UriBuilder callback = new UriBuilder(Request.Url); + callback.Query = null; + string[] scopes = (from item in scopeList.Items.OfType<ListItem>() + where item.Selected + select item.Value).ToArray(); + string scope = string.Join("|", scopes); + var requestParams = new Dictionary<string, string> { + { "scope", scope }, + }; + var response = consumer.PrepareRequestUserAuthorization(callback.Uri, requestParams, null); + consumer.Channel.Send(response).Send(); + } + + protected void getNameButton_Click(object sender, EventArgs e) { + try { + nameLabel.Text = CallService(client => client.GetName()); + } catch (SecurityAccessDeniedException) { + nameLabel.Text = "Access denied!"; + } + } + + protected void getAgeButton_Click(object sender, EventArgs e) { + try { + int? age = CallService(client => client.GetAge()); + ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available"; + } catch (SecurityAccessDeniedException) { + ageLabel.Text = "Access denied!"; + } + } + + protected void getFavoriteSites_Click(object sender, EventArgs e) { + try { + string[] favoriteSites = CallService(client => client.GetFavoriteSites()); + favoriteSitesLabel.Text = string.Join(", ", favoriteSites); + } catch (SecurityAccessDeniedException) { + favoriteSitesLabel.Text = "Access denied!"; + } + } + + private T CallService<T>(Func<DataApiClient, T> predicate) { + DataApiClient client = new DataApiClient(); + var serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest); + var accessToken = Session["WcfAccessToken"] as string; + if (accessToken == null) { + throw new InvalidOperationException("No access token!"); + } + WebConsumer consumer = this.CreateConsumer(); + WebRequest httpRequest = consumer.PrepareAuthorizedRequest(serviceEndpoint, accessToken); + + HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty(); + httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; + using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) { + OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; + return predicate(client); + } + } + + private WebConsumer CreateConsumer() { + string consumerKey = "sampleconsumer"; + string consumerSecret = "samplesecret"; + var tokenManager = Session["WcfTokenManager"] as InMemoryTokenManager; + if (tokenManager == null) { + tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); + Session["WcfTokenManager"] = tokenManager; + } + MessageReceivingEndpoint oauthEndpoint = new MessageReceivingEndpoint( + new Uri("http://localhost:65169/ServiceProvider/OAuth.ashx"), + HttpDeliveryMethods.PostRequest); + WebConsumer consumer = new WebConsumer( + new ServiceProviderDescription { + RequestTokenEndpoint = oauthEndpoint, + UserAuthorizationEndpoint = oauthEndpoint, + AccessTokenEndpoint = oauthEndpoint, + TamperProtectionElements = new DotNetOpenAuth.Messaging.ITamperProtectionChannelBindingElement[] { + new HmacSha1SigningBindingElement(), + }, + }, + tokenManager) { + ConsumerKey = consumerKey, + }; + + return consumer; + } +} diff --git a/samples/Consumer/Web.config b/samples/Consumer/Web.config index be02eaf..0997e8c 100644 --- a/samples/Consumer/Web.config +++ b/samples/Consumer/Web.config @@ -1,161 +1,161 @@ -<?xml version="1.0"?>
-<configuration>
- <configSections>
- <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" />
- <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"/>
- <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
- <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
- <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
- <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
- <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
- </sectionGroup>
- </sectionGroup>
- </sectionGroup>
- </configSections>
- <appSettings/>
- <connectionStrings/>
- <system.web>
- <!--
- Set compilation debug="true" to insert debugging
- symbols into the compiled page. Because this
- affects performance, set this value to true only
- during development.
- -->
- <compilation debug="true">
- <assemblies>
- <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
- <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"/>
- </assemblies>
- </compilation>
- <!--
- The <authentication> section enables configuration
- of the security authentication mode used by
- ASP.NET to identify an incoming user.
- -->
- <authentication mode="Windows"/>
- <!--
- The <customErrors> section enables configuration
- of what to do if/when an unhandled error occurs
- during the execution of a request. Specifically,
- it enables developers to configure html error pages
- to be displayed in place of a error stack trace.
-
- <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
- <error statusCode="403" redirect="NoAccess.htm" />
- <error statusCode="404" redirect="FileNotFound.htm" />
- </customErrors>
- -->
- <pages>
- <controls>
- <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- </controls>
- </pages>
- <httpHandlers>
- <remove verb="*" path="*.asmx"/>
- <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
- </httpHandlers>
- <httpModules>
- <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- </httpModules>
- </system.web>
- <system.codedom>
- <compilers>
- <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
- <providerOption name="CompilerVersion" value="v3.5"/>
- <providerOption name="WarnAsError" value="false"/>
- </compiler>
- <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
- <providerOption name="CompilerVersion" value="v3.5"/>
- <providerOption name="OptionInfer" value="true"/>
- <providerOption name="WarnAsError" value="false"/>
- </compiler>
- </compilers>
- </system.codedom>
- <!--
- The system.webServer section is required for running ASP.NET AJAX under Internet
- Information Services 7.0. It is not necessary for previous version of IIS.
- -->
- <system.webServer>
- <validation validateIntegratedModeConfiguration="false"/>
- <modules>
- <remove name="ScriptModule"/>
- <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- </modules>
- <handlers>
- <remove name="WebServiceHandlerFactory-Integrated"/>
- <remove name="ScriptHandlerFactory"/>
- <remove name="ScriptHandlerFactoryAppServices"/>
- <remove name="ScriptResource"/>
- <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
- </handlers>
- </system.webServer>
- <runtime>
- <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
- <dependentAssembly>
- <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
- <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
- </dependentAssembly>
- <dependentAssembly>
- <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
- <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
- </dependentAssembly>
- </assemblyBinding>
- </runtime>
- <log4net>
- <appender name="TracePageAppender" type="TracePageAppender, __code">
- <layout type="log4net.Layout.PatternLayout">
- <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline" />
- </layout>
- </appender>
- <!-- Setup the root category, add the appenders and set the default level -->
- <root>
- <level value="INFO" />
- <!--<appender-ref ref="RollingFileAppender" />-->
- <appender-ref ref="TracePageAppender" />
- </root>
- <!-- Specify the level for some specific categories -->
- <logger name="DotNetOAuth">
- <level value="ALL" />
- </logger>
- </log4net>
- <system.serviceModel>
- <bindings>
- <wsHttpBinding>
- <binding name="WSHttpBinding_IDataApi" closeTimeout="00:01:00"
- openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
- bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard"
- maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text"
- textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
- <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
- maxBytesPerRead="4096" maxNameTableCharCount="16384" />
- <reliableSession ordered="true" inactivityTimeout="00:10:00"
- enabled="false" />
- <security mode="Message">
- <transport clientCredentialType="Windows" proxyCredentialType="None"
- realm="" />
- <message clientCredentialType="Windows" negotiateServiceCredential="true"
- algorithmSuite="Default" establishSecurityContext="true" />
- </security>
- </binding>
- </wsHttpBinding>
- </bindings>
- <client>
- <endpoint address="http://localhost:65169/ServiceProvider/DataApi.svc"
- binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDataApi"
- contract="SampleServiceProvider.IDataApi" name="WSHttpBinding_IDataApi">
- <identity>
- <dns value="localhost" />
- </identity>
- </endpoint>
- </client>
- </system.serviceModel>
-</configuration>
+<?xml version="1.0"?> +<configuration> + <configSections> + <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler" requirePermission="false" /> + <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"/> + <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> + <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/> + <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> + <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> + <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/> + </sectionGroup> + </sectionGroup> + </sectionGroup> + </configSections> + <appSettings/> + <connectionStrings/> + <system.web> + <!-- + Set compilation debug="true" to insert debugging + symbols into the compiled page. Because this + affects performance, set this value to true only + during development. + --> + <compilation debug="true"> + <assemblies> + <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> + <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"/> + </assemblies> + </compilation> + <!-- + The <authentication> section enables configuration + of the security authentication mode used by + ASP.NET to identify an incoming user. + --> + <authentication mode="Windows"/> + <!-- + The <customErrors> section enables configuration + of what to do if/when an unhandled error occurs + during the execution of a request. Specifically, + it enables developers to configure html error pages + to be displayed in place of a error stack trace. + + <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> + <error statusCode="403" redirect="NoAccess.htm" /> + <error statusCode="404" redirect="FileNotFound.htm" /> + </customErrors> + --> + <pages> + <controls> + <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + </controls> + </pages> + <httpHandlers> + <remove verb="*" path="*.asmx"/> + <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/> + </httpHandlers> + <httpModules> + <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + </httpModules> + </system.web> + <system.codedom> + <compilers> + <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> + <providerOption name="CompilerVersion" value="v3.5"/> + <providerOption name="WarnAsError" value="false"/> + </compiler> + <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"> + <providerOption name="CompilerVersion" value="v3.5"/> + <providerOption name="OptionInfer" value="true"/> + <providerOption name="WarnAsError" value="false"/> + </compiler> + </compilers> + </system.codedom> + <!-- + The system.webServer section is required for running ASP.NET AJAX under Internet + Information Services 7.0. It is not necessary for previous version of IIS. + --> + <system.webServer> + <validation validateIntegratedModeConfiguration="false"/> + <modules> + <remove name="ScriptModule"/> + <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + </modules> + <handlers> + <remove name="WebServiceHandlerFactory-Integrated"/> + <remove name="ScriptHandlerFactory"/> + <remove name="ScriptHandlerFactoryAppServices"/> + <remove name="ScriptResource"/> + <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> + </handlers> + </system.webServer> + <runtime> + <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> + <dependentAssembly> + <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/> + <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> + </dependentAssembly> + <dependentAssembly> + <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/> + <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/> + </dependentAssembly> + </assemblyBinding> + </runtime> + <log4net> + <appender name="TracePageAppender" type="TracePageAppender, __code"> + <layout type="log4net.Layout.PatternLayout"> + <conversionPattern value="%date (GMT%date{%z}) [%thread] %-5level %logger - %message%newline" /> + </layout> + </appender> + <!-- Setup the root category, add the appenders and set the default level --> + <root> + <level value="INFO" /> + <!--<appender-ref ref="RollingFileAppender" />--> + <appender-ref ref="TracePageAppender" /> + </root> + <!-- Specify the level for some specific categories --> + <logger name="DotNetOpenAuth"> + <level value="ALL" /> + </logger> + </log4net> + <system.serviceModel> + <bindings> + <wsHttpBinding> + <binding name="WSHttpBinding_IDataApi" closeTimeout="00:01:00" + openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" + bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" + maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" + textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false"> + <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" + maxBytesPerRead="4096" maxNameTableCharCount="16384" /> + <reliableSession ordered="true" inactivityTimeout="00:10:00" + enabled="false" /> + <security mode="Message"> + <transport clientCredentialType="Windows" proxyCredentialType="None" + realm="" /> + <message clientCredentialType="Windows" negotiateServiceCredential="true" + algorithmSuite="Default" establishSecurityContext="true" /> + </security> + </binding> + </wsHttpBinding> + </bindings> + <client> + <endpoint address="http://localhost:65169/ServiceProvider/DataApi.svc" + binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IDataApi" + contract="SampleServiceProvider.IDataApi" name="WSHttpBinding_IDataApi"> + <identity> + <dns value="localhost" /> + </identity> + </endpoint> + </client> + </system.serviceModel> +</configuration> |