diff options
Diffstat (limited to 'samples/OAuthClient')
24 files changed, 238 insertions, 1097 deletions
diff --git a/samples/OAuthClient/Facebook.aspx b/samples/OAuthClient/Facebook.aspx index c227814..4cdc4b1 100644 --- a/samples/OAuthClient/Facebook.aspx +++ b/samples/OAuthClient/Facebook.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" Inherits="OAuthClient.Facebook" Codebehind="Facebook.aspx.cs" %> +<%@ Page Language="C#" AutoEventWireup="true" Inherits="OAuthClient.Facebook" Codebehind="Facebook.aspx.cs" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OAuthClient/Facebook.aspx.cs b/samples/OAuthClient/Facebook.aspx.cs index 4701d24..19211bc 100644 --- a/samples/OAuthClient/Facebook.aspx.cs +++ b/samples/OAuthClient/Facebook.aspx.cs @@ -3,8 +3,11 @@ using System.Configuration; using System.Net; using System.Web; + using System.Web.UI; + using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.ApplicationBlock.Facebook; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; public partial class Facebook : System.Web.UI.Page { @@ -14,19 +17,29 @@ }; protected void Page_Load(object sender, EventArgs e) { - IAuthorizationState authorization = client.ProcessUserAuthorization(); - if (authorization == null) { - // Kick off authorization request - client.RequestUserAuthorization(); - } else { - var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); - using (var response = request.GetResponse()) { - using (var responseStream = response.GetResponseStream()) { - var graph = FacebookGraph.Deserialize(responseStream); - this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); - } - } - } + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + IAuthorizationState authorization = + await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), ct); + if (authorization == null) { + // Kick off authorization request + var request = + await client.PrepareRequestUserAuthorizationAsync(cancellationToken: ct); + await request.SendAsync(new HttpContextWrapper(Context), ct); + this.Context.Response.End(); + } else { + var request = + WebRequest.Create( + "https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + var graph = FacebookGraph.Deserialize(responseStream); + this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + } + } + } + })); } } }
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleAddressBook.aspx b/samples/OAuthClient/GoogleAddressBook.aspx deleted file mode 100644 index 11891f2..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx +++ /dev/null @@ -1,26 +0,0 @@ -<%@ Page Title="Gmail address book demo" Language="C#" MasterPageFile="~/MasterPage.master" - AutoEventWireup="true" Inherits="OAuthClient.GoogleAddressBook" Codebehind="GoogleAddressBook.aspx.cs" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View runat="server"> - <h2>Google setup</h2> - <p>A Google client app must be endorsed by a Google user. </p> - <ol> - <li><a target="_blank" href="https://www.google.com/accounts/ManageDomains">Visit Google - and create a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Google has authorized us to download your contacts. Click 'Get address book' - to download the first 5 contacts to this sample. Notice how we never asked you - for your Google username or password. </p> - <asp:Button ID="getAddressBookButton" runat="server" OnClick="getAddressBookButton_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/GoogleAddressBook.aspx.cs b/samples/OAuthClient/GoogleAddressBook.aspx.cs deleted file mode 100644 index b7221af..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx.cs +++ /dev/null @@ -1,75 +0,0 @@ -namespace OAuthClient { - using System; - using System.Configuration; - using System.Linq; - using System.Text; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - /// <summary> - /// A page to demonstrate downloading a Gmail address book using OAuth. - /// </summary> - public partial class GoogleAddressBook : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["GoogleAccessToken"]; } - set { Session["GoogleAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - - // Is Google calling back with authorization? - var accessTokenResponse = google.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - GoogleConsumer.RequestAuthorization(google, GoogleConsumer.Applications.Contacts); - } - } - } - } - - protected void getAddressBookButton_Click(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - - XDocument contactsDocument = GoogleConsumer.GetContacts(google, this.AccessToken, 5, 1); - 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>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs b/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs deleted file mode 100644 index 576072e..0000000 --- a/samples/OAuthClient/GoogleAddressBook.aspx.designer.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class GoogleAddressBook { - - /// <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> - /// getAddressBookButton 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 getAddressBookButton; - - /// <summary> - /// resultsPlaceholder 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.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx b/samples/OAuthClient/GoogleApps2Legged.aspx deleted file mode 100644 index cd9d9a1..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx +++ /dev/null @@ -1,25 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master"CodeBehind="GoogleApps2Legged.aspx.cs" Inherits="OAuthConsumer.GoogleApps2Legged" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View runat="server"> - <h2>Google setup</h2> - <p>A Google client app must be endorsed by a Google user. </p> - <ol> - <li><a target="_blank" href="https://www.google.com/accounts/ManageDomains">Visit Google - and create a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Google has authorized us to download your contacts. Click 'Get address book' - to download the first 5 contacts to this sample. Notice how we never asked you - for your Google username or password. </p> - <asp:Button ID="getAddressBookButton" runat="server" OnClick="getAddressBookButton_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx.cs b/samples/OAuthClient/GoogleApps2Legged.aspx.cs deleted file mode 100644 index afb156b..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace OAuthConsumer { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth; - using DotNetOpenAuth.OAuth.Messages; - - public partial class GoogleApps2Legged : System.Web.UI.Page { - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["GoogleTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["googleConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["googleConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["GoogleTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - var google = new WebConsumer(GoogleConsumer.ServiceDescription, this.TokenManager); - string accessToken = google.RequestNewClientAccount(); - ////string tokenSecret = google.TokenManager.GetTokenSecret(accessToken); - MessageReceivingEndpoint ep = null; // set up your authorized call here. - google.PrepareAuthorizedRequestAndSend(ep, accessToken); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs b/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs deleted file mode 100644 index f952937..0000000 --- a/samples/OAuthClient/GoogleApps2Legged.aspx.designer.cs +++ /dev/null @@ -1,42 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthConsumer { - - - public partial class GoogleApps2Legged { - - /// <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> - /// getAddressBookButton 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 getAddressBookButton; - - /// <summary> - /// resultsPlaceholder 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.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/OAuthClient.csproj b/samples/OAuthClient/OAuthClient.csproj index 8a5cc88..3c94f38 100644 --- a/samples/OAuthClient/OAuthClient.csproj +++ b/samples/OAuthClient/OAuthClient.csproj @@ -55,6 +55,8 @@ <Reference Include="System" /> <Reference Include="System.Data" /> <Reference Include="System.Data.DataSetExtensions" /> + <Reference Include="System.Net.Http" /> + <Reference Include="System.Net.Http.WebRequest" /> <Reference Include="System.Runtime.Serialization" /> <Reference Include="System.ServiceModel" /> <Reference Include="System.Web.Abstractions" /> @@ -75,15 +77,12 @@ <Content Include="Facebook.aspx" /> <Content Include="favicon.ico" /> <Content Include="Global.asax" /> - <Content Include="GoogleAddressBook.aspx" /> - <Content Include="GoogleApps2Legged.aspx" /> <Content Include="images\Sign-in-with-Twitter-darker.png" /> <Content Include="SampleWcf2Javascript.html" /> <Content Include="SampleWcf2Javascript.js" /> <Content Include="Scripts\jquery-1.6.1.js" /> <Content Include="Scripts\jquery-1.6.1.min.js" /> <Content Include="WindowsLive.aspx" /> - <Content Include="Yammer.aspx" /> <Content Include="packages.config" /> <None Include="Service References\SampleResourceServer\DataApi.disco" /> <None Include="Service References\SampleResourceServer\configuration91.svcinfo" /> @@ -93,9 +92,7 @@ <LastGenOutput>Reference.cs</LastGenOutput> </None> <Content Include="SampleWcf2.aspx" /> - <Content Include="SignInWithTwitter.aspx" /> <Content Include="TracePage.aspx" /> - <Content Include="Twitter.aspx" /> <Content Include="Web.config" /> <None Include="Service References\SampleResourceServer\DataApi1.xsd"> <SubType>Designer</SubType> @@ -105,9 +102,7 @@ </None> </ItemGroup> <ItemGroup> - <Compile Include="..\DotNetOpenAuth.ApplicationBlock\InMemoryTokenManager.cs"> - <Link>Code\InMemoryTokenManager.cs</Link> - </Compile> + <Compile Include="Code\Logging.cs" /> <Compile Include="Facebook.aspx.cs"> <DependentUpon>Facebook.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -118,20 +113,10 @@ <Compile Include="Global.asax.cs"> <DependentUpon>Global.asax</DependentUpon> </Compile> - <Compile Include="GoogleAddressBook.aspx.designer.cs"> - <DependentUpon>GoogleAddressBook.aspx</DependentUpon> - </Compile> <Compile Include="SampleWcf2.aspx.cs"> <DependentUpon>SampleWcf2.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> </Compile> - <Compile Include="GoogleApps2Legged.aspx.cs"> - <DependentUpon>GoogleApps2Legged.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="GoogleApps2Legged.aspx.designer.cs"> - <DependentUpon>GoogleApps2Legged.aspx</DependentUpon> - </Compile> <Compile Include="SampleWcf2.aspx.designer.cs"> <DependentUpon>SampleWcf2.aspx</DependentUpon> </Compile> @@ -140,13 +125,6 @@ <DesignTime>True</DesignTime> <DependentUpon>Reference.svcmap</DependentUpon> </Compile> - <Compile Include="SignInWithTwitter.aspx.cs"> - <DependentUpon>SignInWithTwitter.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="SignInWithTwitter.aspx.designer.cs"> - <DependentUpon>SignInWithTwitter.aspx</DependentUpon> - </Compile> <Compile Include="TracePage.aspx.cs"> <DependentUpon>TracePage.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -154,20 +132,8 @@ <Compile Include="TracePage.aspx.designer.cs"> <DependentUpon>TracePage.aspx</DependentUpon> </Compile> - <Compile Include="Twitter.aspx.cs"> - <DependentUpon>Twitter.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="Code\Logging.cs" /> <Compile Include="Code\TracePageAppender.cs" /> - <Compile Include="GoogleAddressBook.aspx.cs"> - <DependentUpon>GoogleAddressBook.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> <Compile Include="Properties\AssemblyInfo.cs" /> - <Compile Include="Twitter.aspx.designer.cs"> - <DependentUpon>Twitter.aspx</DependentUpon> - </Compile> <Compile Include="WindowsLive.aspx.cs"> <DependentUpon>WindowsLive.aspx</DependentUpon> <SubType>ASPXCodeBehind</SubType> @@ -175,13 +141,6 @@ <Compile Include="WindowsLive.aspx.designer.cs"> <DependentUpon>WindowsLive.aspx</DependentUpon> </Compile> - <Compile Include="Yammer.aspx.cs"> - <DependentUpon>Yammer.aspx</DependentUpon> - <SubType>ASPXCodeBehind</SubType> - </Compile> - <Compile Include="Yammer.aspx.designer.cs"> - <DependentUpon>Yammer.aspx</DependentUpon> - </Compile> </ItemGroup> <ItemGroup> <Folder Include="App_Data\" /> diff --git a/samples/OAuthClient/SampleWcf2.aspx b/samples/OAuthClient/SampleWcf2.aspx index cfacaf1..457a409 100644 --- a/samples/OAuthClient/SampleWcf2.aspx +++ b/samples/OAuthClient/SampleWcf2.aspx @@ -1,4 +1,4 @@ -<%@ Page Title="OAuth 2.0 client (web server flow)" Language="C#" MasterPageFile="~/MasterPage.master" +<%@ Page Title="OAuth 2.0 client (web server flow)" Language="C#" MasterPageFile="~/MasterPage.master" Async="true" AutoEventWireup="true" Inherits="OAuthClient.SampleWcf2" CodeBehind="SampleWcf2.aspx.cs" %> <asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> diff --git a/samples/OAuthClient/SampleWcf2.aspx.cs b/samples/OAuthClient/SampleWcf2.aspx.cs index 06bbe9b..e96a5c0 100644 --- a/samples/OAuthClient/SampleWcf2.aspx.cs +++ b/samples/OAuthClient/SampleWcf2.aspx.cs @@ -1,143 +1,170 @@ -namespace OAuthClient {
- 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;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using DotNetOpenAuth.OAuth2;
-
- using SampleResourceServer;
-
- public partial class SampleWcf2 : System.Web.UI.Page {
- /// <summary>
- /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests.
- /// </summary>
- private static readonly WebServerClient Client;
-
- /// <summary>
- /// The details about the sample OAuth-enabled WCF service that this sample client calls into.
- /// </summary>
- private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription {
- TokenEndpoint = new Uri("http://localhost:50172/OAuth/Token"),
- AuthorizationEndpoint = new Uri("http://localhost:50172/OAuth/Authorize"),
- };
-
- /// <summary>
- /// Initializes static members of the <see cref="SampleWcf2"/> class.
- /// </summary>
- static SampleWcf2() {
- Client = new WebServerClient(authServerDescription, "sampleconsumer", "samplesecret");
- }
-
- /// <summary>
- /// Gets or sets the authorization details for the logged in user.
- /// </summary>
- /// <value>The authorization details.</value>
- /// <remarks>
- /// Because this is a sample, we simply store the authorization information in memory with the user session.
- /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user.
- /// </remarks>
- private static IAuthorizationState Authorization {
- get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; }
- set { HttpContext.Current.Session["Authorization"] = value; }
- }
-
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- // Check to see if we're receiving a end user authorization response.
- var authorization = Client.ProcessUserAuthorization();
- if (authorization != null) {
- // We are receiving an authorization response. Store it and associate it with this user.
- Authorization = authorization;
- Response.Redirect(Request.Path); // get rid of the /?code= parameter
- }
- }
-
- if (Authorization != null) {
- // Indicate to the user that we have already obtained authorization on some of these.
- foreach (var li in this.scopeList.Items.OfType<ListItem>().Where(li => Authorization.Scope.Contains(li.Value))) {
- li.Selected = true;
- }
- this.authorizationLabel.Text = "Authorization received!";
- if (Authorization.AccessTokenExpirationUtc.HasValue) {
- TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
- this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " (access token expires in {0} minutes)", Math.Round(timeLeft.TotalMinutes, 1));
- }
- }
-
- this.getNameButton.Enabled = this.getAgeButton.Enabled = this.getFavoriteSites.Enabled = Authorization != null;
- }
-
- protected void getAuthorizationButton_Click(object sender, EventArgs e) {
- string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
- where item.Selected
- select item.Value).ToArray();
-
- Client.RequestUserAuthorization(scopes);
- }
-
- protected void getNameButton_Click(object sender, EventArgs e) {
- try {
- this.nameLabel.Text = this.CallService(client => client.GetName());
- } catch (SecurityAccessDeniedException) {
- this.nameLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.nameLabel.Text = "Access denied!";
- }
- }
-
- protected void getAgeButton_Click(object sender, EventArgs e) {
- try {
- int? age = this.CallService(client => client.GetAge());
- this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
- } catch (SecurityAccessDeniedException) {
- this.ageLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.ageLabel.Text = "Access denied!";
- }
- }
-
- protected void getFavoriteSites_Click(object sender, EventArgs e) {
- try {
- string[] favoriteSites = this.CallService(client => client.GetFavoriteSites());
- this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
- } catch (SecurityAccessDeniedException) {
- this.favoriteSitesLabel.Text = "Access denied!";
- } catch (MessageSecurityException) {
- this.favoriteSitesLabel.Text = "Access denied!";
- }
- }
-
- private T CallService<T>(Func<DataApiClient, T> predicate) {
- if (Authorization == null) {
- throw new InvalidOperationException("No access token!");
- }
-
- var wcfClient = new DataApiClient();
-
- // Refresh the access token if it expires and if its lifetime is too short to be of use.
- if (Authorization.AccessTokenExpirationUtc.HasValue) {
- if (Client.RefreshAuthorization(Authorization, TimeSpan.FromSeconds(30))) {
- TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
- this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1));
- }
- }
-
- var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri);
- ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken);
-
- var httpDetails = new HttpRequestMessageProperty();
- httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
- using (var scope = new OperationContextScope(wcfClient.InnerChannel)) {
- OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
- return predicate(wcfClient);
- }
- }
- }
+namespace OAuthClient { + 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.Threading; + using System.Threading.Tasks; + using System.Web; + using System.Web.UI; + using System.Web.UI.WebControls; + using DotNetOpenAuth.Messaging; + using DotNetOpenAuth.OAuth2; + using SampleResourceServer; + + public partial class SampleWcf2 : System.Web.UI.Page { + /// <summary> + /// The OAuth 2.0 client object to use to obtain authorization and authorize outgoing HTTP requests. + /// </summary> + private static readonly WebServerClient Client; + + /// <summary> + /// The details about the sample OAuth-enabled WCF service that this sample client calls into. + /// </summary> + private static AuthorizationServerDescription authServerDescription = new AuthorizationServerDescription { + TokenEndpoint = new Uri("http://localhost:50172/OAuth/Token"), + AuthorizationEndpoint = new Uri("http://localhost:50172/OAuth/Authorize"), + }; + + /// <summary> + /// Initializes static members of the <see cref="SampleWcf2"/> class. + /// </summary> + static SampleWcf2() { + Client = new WebServerClient(authServerDescription, "sampleconsumer", "samplesecret"); + } + + /// <summary> + /// Gets or sets the authorization details for the logged in user. + /// </summary> + /// <value>The authorization details.</value> + /// <remarks> + /// Because this is a sample, we simply store the authorization information in memory with the user session. + /// A real web app should store at least the access and refresh tokens in this object in a database associated with the user. + /// </remarks> + private static IAuthorizationState Authorization { + get { return (AuthorizationState)HttpContext.Current.Session["Authorization"]; } + set { HttpContext.Current.Session["Authorization"] = value; } + } + + protected void Page_Load(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (!IsPostBack) { + // Check to see if we're receiving a end user authorization response. + var authorization = + await Client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (authorization != null) { + // We are receiving an authorization response. Store it and associate it with this user. + Authorization = authorization; + Response.Redirect(Request.Path); // get rid of the /?code= parameter + } + } + + if (Authorization != null) { + // Indicate to the user that we have already obtained authorization on some of these. + foreach (var li in this.scopeList.Items.OfType<ListItem>().Where(li => Authorization.Scope.Contains(li.Value))) { + li.Selected = true; + } + this.authorizationLabel.Text = "Authorization received!"; + if (Authorization.AccessTokenExpirationUtc.HasValue) { + TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; + this.authorizationLabel.Text += string.Format( + CultureInfo.CurrentCulture, " (access token expires in {0} minutes)", Math.Round(timeLeft.TotalMinutes, 1)); + } + } + + this.getNameButton.Enabled = this.getAgeButton.Enabled = this.getFavoriteSites.Enabled = Authorization != null; + })); + } + + protected void getAuthorizationButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + string[] scopes = + (from item in this.scopeList.Items.OfType<ListItem>() where item.Selected select item.Value).ToArray(); + + var request = + await Client.PrepareRequestUserAuthorizationAsync(scopes, cancellationToken: Response.ClientDisconnectedToken); + await request.SendAsync(); + this.Context.Response.End(); + })); + } + + protected void getNameButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + this.nameLabel.Text = await this.CallServiceAsync(client => client.GetName(), Response.ClientDisconnectedToken); + } catch (SecurityAccessDeniedException) { + this.nameLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.nameLabel.Text = "Access denied!"; + } + })); + } + + protected void getAgeButton_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + int? age = await this.CallServiceAsync(client => client.GetAge(), Response.ClientDisconnectedToken); + this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available"; + } catch (SecurityAccessDeniedException) { + this.ageLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.ageLabel.Text = "Access denied!"; + } + })); + } + + protected void getFavoriteSites_Click(object sender, EventArgs e) { + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + try { + string[] favoriteSites = + await this.CallServiceAsync(client => client.GetFavoriteSites(), Response.ClientDisconnectedToken); + this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites); + } catch (SecurityAccessDeniedException) { + this.favoriteSitesLabel.Text = "Access denied!"; + } catch (MessageSecurityException) { + this.favoriteSitesLabel.Text = "Access denied!"; + } + })); + } + + private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate, CancellationToken cancellationToken) { + if (Authorization == null) { + throw new InvalidOperationException("No access token!"); + } + + var wcfClient = new DataApiClient(); + + // Refresh the access token if it expires and if its lifetime is too short to be of use. + if (Authorization.AccessTokenExpirationUtc.HasValue) { + if (await Client.RefreshAuthorizationAsync(Authorization, TimeSpan.FromSeconds(30))) { + TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow; + this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1)); + } + } + + var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri); + ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken); + + var httpDetails = new HttpRequestMessageProperty(); + httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization]; + using (var scope = new OperationContextScope(wcfClient.InnerChannel)) { + OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails; + return predicate(wcfClient); + } + } + } }
\ No newline at end of file diff --git a/samples/OAuthClient/SignInWithTwitter.aspx b/samples/OAuthClient/SignInWithTwitter.aspx deleted file mode 100644 index 9fda5c1..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx +++ /dev/null @@ -1,38 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" - Inherits="OAuthClient.SignInWithTwitter" Codebehind="SignInWithTwitter.aspx.cs" %> - -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head runat="server"> - <title>Sign-in with Twitter</title> -</head> -<body> - <form id="form1" runat="server"> - <div> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="View1" runat="server"> - <h2> - Twitter setup</h2> - <p> - A Twitter client app must be endorsed by a Twitter user. - </p> - <ol> - <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create - a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret.</li> - </ol> - </asp:View> - <asp:View ID="View2" runat="server"> - <asp:ImageButton ImageUrl="~/images/Sign-in-with-Twitter-darker.png" runat="server" - AlternateText="Sign In With Twitter" ID="signInButton" OnClick="signInButton_Click" /> - <asp:CheckBox Text="force re-login" runat="server" ID="forceLoginCheckbox" /> - <br /> - <asp:Panel runat="server" ID="loggedInPanel" Visible="false"> - Now logged in as - <asp:Label Text="[name]" runat="server" ID="loggedInName" /> - </asp:Panel> - </asp:View> - </asp:MultiView> - </form> -</body> -</html> diff --git a/samples/OAuthClient/SignInWithTwitter.aspx.cs b/samples/OAuthClient/SignInWithTwitter.aspx.cs deleted file mode 100644 index 04b302c..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx.cs +++ /dev/null @@ -1,39 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.Security; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using System.Xml.XPath; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - public partial class SignInWithTwitter : System.Web.UI.Page { - protected void Page_Load(object sender, EventArgs e) { - if (TwitterConsumer.IsTwitterConsumerConfigured) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - string screenName; - int userId; - if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId)) { - this.loggedInPanel.Visible = true; - this.loggedInName.Text = screenName; - - // In a real app, the Twitter username would likely be used - // to log the user into the application. - ////FormsAuthentication.RedirectFromLoginPage(screenName, false); - } - } - } - } - - protected void signInButton_Click(object sender, ImageClickEventArgs e) { - TwitterConsumer.StartSignInWithTwitter(this.forceLoginCheckbox.Checked).Send(); - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs b/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs deleted file mode 100644 index 00126de..0000000 --- a/samples/OAuthClient/SignInWithTwitter.aspx.designer.cs +++ /dev/null @@ -1,87 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class SignInWithTwitter { - - /// <summary> - /// form1 control. - /// </summary> - /// <remarks> - /// Auto-generated field. - /// To modify move field declaration from designer file to code-behind file. - /// </remarks> - protected global::System.Web.UI.HtmlControls.HtmlForm form1; - - /// <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> - /// View2 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 View2; - - /// <summary> - /// signInButton 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.ImageButton signInButton; - - /// <summary> - /// forceLoginCheckbox 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 forceLoginCheckbox; - - /// <summary> - /// loggedInPanel 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 loggedInPanel; - - /// <summary> - /// loggedInName 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 loggedInName; - } -} diff --git a/samples/OAuthClient/Twitter.aspx b/samples/OAuthClient/Twitter.aspx deleted file mode 100644 index cb60851..0000000 --- a/samples/OAuthClient/Twitter.aspx +++ /dev/null @@ -1,35 +0,0 @@ -<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" Inherits="OAuthClient.Twitter" Codebehind="Twitter.aspx.cs" %> - -<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> -</asp:Content> -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="View1" runat="server"> - <h2>Twitter setup</h2> - <p>A Twitter client app must be endorsed by a Twitter user. </p> - <ol> - <li><a target="_blank" href="https://twitter.com/oauth_clients">Visit Twitter and create - a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret.</li> - </ol> - </asp:View> - <asp:View runat="server"> - <h2>Updates</h2> - <p>Ok, Twitter has authorized us to download your feeds. 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> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/Twitter.aspx.cs b/samples/OAuthClient/Twitter.aspx.cs deleted file mode 100644 index 9c0cb9a..0000000 --- a/samples/OAuthClient/Twitter.aspx.cs +++ /dev/null @@ -1,96 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Text; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using System.Xml.Linq; - using System.Xml.XPath; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.OAuth; - - public partial class Twitter : System.Web.UI.Page { - private string AccessToken { - get { return (string)Session["TwitterAccessToken"]; } - set { Session["TwitterAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["TwitterTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["TwitterTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.ActiveViewIndex = 1; - - if (!IsPostBack) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - - // Is Twitter calling back with authorization? - var accessTokenResponse = twitter.ProcessUserAuthorization(); - if (accessTokenResponse != null) { - this.AccessToken = accessTokenResponse.AccessToken; - } else if (this.AccessToken == null) { - // If we don't yet have access, immediately request it. - twitter.Channel.Send(twitter.PrepareRequestUserAuthorization()); - } - } - } - } - - protected void downloadUpdates_Click(object sender, EventArgs e) { - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader()); - XPathNavigator nav = updates.CreateNavigator(); - var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>() - where !status.SelectSingleNode("user/protected").ValueAsBoolean - select new { - User = status.SelectSingleNode("user/name").InnerXml, - Status = status.SelectSingleNode("text").InnerXml, - }; - - StringBuilder tableBuilder = new StringBuilder(); - tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>"); - - foreach (var update in parsedUpdates) { - tableBuilder.AppendFormat( - "<tr><td>{0}</td><td>{1}</td></tr>", - HttpUtility.HtmlEncode(update.User), - HttpUtility.HtmlEncode(update.Status)); - } - tableBuilder.Append("</table>"); - this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() }); - } - - protected void uploadProfilePhotoButton_Click(object sender, EventArgs e) { - if (this.profilePhoto.PostedFile.ContentType == null) { - this.photoUploadedLabel.Visible = true; - this.photoUploadedLabel.Text = "Select a file first."; - return; - } - - var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager); - XDocument imageResult = TwitterConsumer.UpdateProfileImage( - twitter, - this.AccessToken, - this.profilePhoto.PostedFile.InputStream, - this.profilePhoto.PostedFile.ContentType); - this.photoUploadedLabel.Visible = true; - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/Twitter.aspx.designer.cs b/samples/OAuthClient/Twitter.aspx.designer.cs deleted file mode 100644 index e82f477..0000000 --- a/samples/OAuthClient/Twitter.aspx.designer.cs +++ /dev/null @@ -1,78 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class Twitter { - - /// <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> - /// profilePhoto 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.FileUpload profilePhoto; - - /// <summary> - /// uploadProfilePhotoButton 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 uploadProfilePhotoButton; - - /// <summary> - /// photoUploadedLabel 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 photoUploadedLabel; - - /// <summary> - /// downloadUpdates 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 downloadUpdates; - - /// <summary> - /// resultsPlaceholder 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.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/Web.config b/samples/OAuthClient/Web.config index b17ae43..5fbb439 100644 --- a/samples/OAuthClient/Web.config +++ b/samples/OAuthClient/Web.config @@ -55,21 +55,20 @@ <!-- Windows Live sign-up: http://go.microsoft.com/fwlink/p/?LinkId=193157 --> <add key="windowsLiveAppID" value="000000004408E558" /> <add key="windowsLiveAppSecret" value="od8NVdanEIWqmlKu9hOepBE3AfUu4jCw" /> + + <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /> </appSettings> <connectionStrings/> <system.web> + <httpRuntime targetFramework="4.5" /> <!-- 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" targetFramework="4.0"> - <assemblies> - <remove assembly="DotNetOpenAuth.Contracts"/> - </assemblies> - </compilation> + <compilation debug="true" targetFramework="4.0" /> <!-- The <authentication> section enables configuration of the security authentication mode used by diff --git a/samples/OAuthClient/WindowsLive.aspx b/samples/OAuthClient/WindowsLive.aspx index ef51223..efdc582 100644 --- a/samples/OAuthClient/WindowsLive.aspx +++ b/samples/OAuthClient/WindowsLive.aspx @@ -1,4 +1,4 @@ -<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WindowsLive.aspx.cs" Inherits="OAuthClient.WindowsLive" %> +<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WindowsLive.aspx.cs" Inherits="OAuthClient.WindowsLive" Async="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> diff --git a/samples/OAuthClient/WindowsLive.aspx.cs b/samples/OAuthClient/WindowsLive.aspx.cs index 05101a7..efe41ec 100644 --- a/samples/OAuthClient/WindowsLive.aspx.cs +++ b/samples/OAuthClient/WindowsLive.aspx.cs @@ -9,6 +9,7 @@ using System.Web.UI.WebControls; using DotNetOpenAuth.ApplicationBlock; using DotNetOpenAuth.ApplicationBlock.Facebook; + using DotNetOpenAuth.Messaging; using DotNetOpenAuth.OAuth2; public partial class WindowsLive : System.Web.UI.Page { @@ -18,28 +19,38 @@ }; protected void Page_Load(object sender, EventArgs e) { - if (string.Equals("localhost", this.Request.Headers["Host"].Split(':')[0], StringComparison.OrdinalIgnoreCase)) { - this.localhostDoesNotWorkPanel.Visible = true; - var builder = new UriBuilder(this.publicLink.NavigateUrl); - builder.Port = this.Request.Url.Port; - this.publicLink.NavigateUrl = builder.Uri.AbsoluteUri; - this.publicLink.Text = builder.Uri.AbsoluteUri; - } else { - IAuthorizationState authorization = client.ProcessUserAuthorization(); - if (authorization == null) { - // Kick off authorization request - client.RequestUserAuthorization(scope: new[] { WindowsLiveClient.Scopes.Basic }); // this scope isn't even required just to log in - } else { - var request = - WebRequest.Create("https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); - using (var response = request.GetResponse()) { - using (var responseStream = response.GetResponseStream()) { - var graph = WindowsLiveGraph.Deserialize(responseStream); - this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + this.RegisterAsyncTask( + new PageAsyncTask( + async ct => { + if (string.Equals("localhost", this.Request.Headers["Host"].Split(':')[0], StringComparison.OrdinalIgnoreCase)) { + this.localhostDoesNotWorkPanel.Visible = true; + var builder = new UriBuilder(this.publicLink.NavigateUrl); + builder.Port = this.Request.Url.Port; + this.publicLink.NavigateUrl = builder.Uri.AbsoluteUri; + this.publicLink.Text = builder.Uri.AbsoluteUri; + } else { + IAuthorizationState authorization = + await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken); + if (authorization == null) { + // Kick off authorization request + var request = + await client.PrepareRequestUserAuthorizationAsync(scopes: new[] { WindowsLiveClient.Scopes.Basic }); + // this scope isn't even required just to log in + await request.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken); + this.Context.Response.End(); + } else { + var request = + WebRequest.Create( + "https://apis.live.net/v5.0/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken)); + using (var response = request.GetResponse()) { + using (var responseStream = response.GetResponseStream()) { + var graph = WindowsLiveGraph.Deserialize(responseStream); + this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name); + } + } + } } - } - } - } + })); } } } diff --git a/samples/OAuthClient/Yammer.aspx b/samples/OAuthClient/Yammer.aspx deleted file mode 100644 index a900a2e..0000000 --- a/samples/OAuthClient/Yammer.aspx +++ /dev/null @@ -1,48 +0,0 @@ -<%@ Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterPage.master" - CodeBehind="Yammer.aspx.cs" Inherits="OAuthClient.Yammer" %> - -<asp:Content ID="Content2" ContentPlaceHolderID="Body" runat="Server"> - <asp:MultiView ID="MultiView1" runat="server" ActiveViewIndex="0"> - <asp:View ID="ClientRegistrationRequiredView" runat="server"> - <h2> - Yammer setup</h2> - <p> - A Yammer client app must be registered. - </p> - <ol> - <li><a target="_blank" href="https://www.yammer.com/client_applications/new">Visit Yammer - and register a client app</a>. </li> - <li>Modify your web.config file to include your consumer key and consumer secret. - </li> - </ol> - </asp:View> - <asp:View ID="BeginAuthorizationView" runat="server"> - <asp:Label Text="An error occurred in authorization. You may try again." EnableViewState="false" Visible="false" ForeColor="Red" ID="authorizationErrorLabel" runat="server" /> - <asp:Button Text="Obtain authorization now" runat="server" ID="obtainAuthorizationButton" - OnClick="obtainAuthorizationButton_Click" /> - </asp:View> - <asp:View ID="CompleteAuthorizationView" runat="server"> - After you have authorized Yammer to share your information, please enter the code - Yammer gives you here: - <asp:TextBox runat="server" ID="yammerUserCode" EnableViewState="false" /> - <asp:RequiredFieldValidator ErrorMessage="*" ControlToValidate="yammerUserCode" runat="server" /> - <asp:Button Text="Finish" runat="server" ID="finishAuthorizationButton" OnClick="finishAuthorizationButton_Click" /> - </asp:View> - <asp:View ID="AuthorizationCompleteView" runat="server"> - <h2> - Updates - </h2> - <p>The access token we have obtained is: - <asp:Label ID="accessTokenLabel" runat="server" /> - </p> - <p> - Ok, Yammer has authorized us to download your messages. Click 'Get messages' - to download the latest few messages to this sample. Notice how we never asked you - for your Yammer username or password. - </p> - <asp:Button ID="getYammerMessagesButton" runat="server" OnClick="getYammerMessages_Click" - Text="Get address book" /> - <asp:PlaceHolder ID="resultsPlaceholder" runat="server" /> - </asp:View> - </asp:MultiView> -</asp:Content> diff --git a/samples/OAuthClient/Yammer.aspx.cs b/samples/OAuthClient/Yammer.aspx.cs deleted file mode 100644 index 2e87a62..0000000 --- a/samples/OAuthClient/Yammer.aspx.cs +++ /dev/null @@ -1,76 +0,0 @@ -namespace OAuthClient { - using System; - using System.Collections.Generic; - using System.Configuration; - using System.Linq; - using System.Web; - using System.Web.UI; - using System.Web.UI.WebControls; - using DotNetOpenAuth.ApplicationBlock; - using DotNetOpenAuth.Messaging; - using DotNetOpenAuth.OAuth; - - public partial class Yammer : System.Web.UI.Page { - private string RequestToken { - get { return (string)ViewState["YammerRequestToken"]; } - set { ViewState["YammerRequestToken"] = value; } - } - - private string AccessToken { - get { return (string)Session["YammerAccessToken"]; } - set { Session["YammerAccessToken"] = value; } - } - - private InMemoryTokenManager TokenManager { - get { - var tokenManager = (InMemoryTokenManager)Application["YammerTokenManager"]; - if (tokenManager == null) { - string consumerKey = ConfigurationManager.AppSettings["YammerConsumerKey"]; - string consumerSecret = ConfigurationManager.AppSettings["YammerConsumerSecret"]; - if (!string.IsNullOrEmpty(consumerKey)) { - tokenManager = new InMemoryTokenManager(consumerKey, consumerSecret); - Application["YammerTokenManager"] = tokenManager; - } - } - - return tokenManager; - } - } - - protected void Page_Load(object sender, EventArgs e) { - if (this.TokenManager != null) { - this.MultiView1.SetActiveView(this.BeginAuthorizationView); - } - } - - protected void getYammerMessages_Click(object sender, EventArgs e) { - var yammer = new WebConsumer(YammerConsumer.ServiceDescription, this.TokenManager); - } - - protected void obtainAuthorizationButton_Click(object sender, EventArgs e) { - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - string requestToken; - Uri popupWindowLocation = YammerConsumer.PrepareRequestAuthorization(yammer, out requestToken); - this.RequestToken = requestToken; - string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');"; - this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true); - this.MultiView1.SetActiveView(this.CompleteAuthorizationView); - } - - protected void finishAuthorizationButton_Click(object sender, EventArgs e) { - if (!Page.IsValid) { - return; - } - - var yammer = YammerConsumer.CreateConsumer(this.TokenManager); - var authorizationResponse = YammerConsumer.CompleteAuthorization(yammer, this.RequestToken, this.yammerUserCode.Text); - if (authorizationResponse != null) { - this.accessTokenLabel.Text = HttpUtility.HtmlEncode(authorizationResponse.AccessToken); - this.MultiView1.SetActiveView(this.AuthorizationCompleteView); - } else { - this.MultiView1.SetActiveView(this.BeginAuthorizationView); - this.authorizationErrorLabel.Visible = true; - } - } - } -}
\ No newline at end of file diff --git a/samples/OAuthClient/Yammer.aspx.designer.cs b/samples/OAuthClient/Yammer.aspx.designer.cs deleted file mode 100644 index 84d75b8..0000000 --- a/samples/OAuthClient/Yammer.aspx.designer.cs +++ /dev/null @@ -1,123 +0,0 @@ -//------------------------------------------------------------------------------ -// <auto-generated> -// This code was generated by a tool. -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// </auto-generated> -//------------------------------------------------------------------------------ - -namespace OAuthClient { - - - public partial class Yammer { - - /// <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> - /// ClientRegistrationRequiredView 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 ClientRegistrationRequiredView; - - /// <summary> - /// BeginAuthorizationView 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 BeginAuthorizationView; - - /// <summary> - /// authorizationErrorLabel 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 authorizationErrorLabel; - - /// <summary> - /// obtainAuthorizationButton 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 obtainAuthorizationButton; - - /// <summary> - /// CompleteAuthorizationView 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 CompleteAuthorizationView; - - /// <summary> - /// yammerUserCode 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.TextBox yammerUserCode; - - /// <summary> - /// finishAuthorizationButton 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 finishAuthorizationButton; - - /// <summary> - /// AuthorizationCompleteView 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 AuthorizationCompleteView; - - /// <summary> - /// accessTokenLabel 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 accessTokenLabel; - - /// <summary> - /// getYammerMessagesButton 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 getYammerMessagesButton; - - /// <summary> - /// resultsPlaceholder 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.PlaceHolder resultsPlaceholder; - } -} diff --git a/samples/OAuthClient/packages.config b/samples/OAuthClient/packages.config index 6562527..8e40260 100644 --- a/samples/OAuthClient/packages.config +++ b/samples/OAuthClient/packages.config @@ -1,4 +1,5 @@ <?xml version="1.0" encoding="utf-8"?> <packages> <package id="log4net" version="2.0.0" targetFramework="net45" /> + <package id="Microsoft.Net.Http" version="2.0.20710.0" targetFramework="net45" /> </packages>
\ No newline at end of file |