summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs108
-rw-r--r--samples/OAuthClient/Facebook.aspx.cs42
-rw-r--r--samples/OAuthClient/SampleWcf2.aspx.cs139
-rw-r--r--samples/OAuthClient/WindowsLive.aspx.cs56
-rw-r--r--samples/OAuthConsumer/GoogleAddressBook.aspx.cs74
-rw-r--r--samples/OAuthConsumer/GoogleApps2Legged.aspx.cs16
-rw-r--r--samples/OAuthConsumer/SampleWcf.aspx.cs106
-rw-r--r--samples/OAuthConsumer/SignInWithTwitter.aspx.cs48
-rw-r--r--samples/OAuthConsumer/Twitter.aspx.cs98
-rw-r--r--samples/OAuthConsumer/Yammer.aspx.cs46
-rw-r--r--samples/OAuthServiceProvider/Members/Authorize.aspx.cs56
-rw-r--r--samples/OpenIdProviderWebForms/Default.aspx.cs39
-rw-r--r--samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj8
-rw-r--r--samples/OpenIdProviderWebForms/WebForm1.aspx16
-rw-r--r--samples/OpenIdProviderWebForms/WebForm1.aspx.cs15
-rw-r--r--samples/OpenIdProviderWebForms/WebForm1.aspx.designer.cs24
-rw-r--r--samples/OpenIdProviderWebForms/decide.aspx.cs212
-rw-r--r--samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs70
-rw-r--r--samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs37
-rw-r--r--samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs58
-rw-r--r--samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs33
-rw-r--r--samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs70
-rw-r--r--samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs56
-rw-r--r--samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs140
-rw-r--r--samples/OpenIdWebRingSsoProvider/Default.aspx.cs28
-rw-r--r--samples/OpenIdWebRingSsoProvider/Login.aspx.cs22
-rw-r--r--samples/OpenIdWebRingSsoProvider/Server.aspx.cs8
-rw-r--r--samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs131
-rw-r--r--src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs35
29 files changed, 985 insertions, 806 deletions
diff --git a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
index 93e236b..c82b08c 100644
--- a/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
+++ b/projecttemplates/WebFormsRelyingParty/Members/OAuthAuthorize.aspx.cs
@@ -23,52 +23,80 @@ namespace WebFormsRelyingParty.Members {
public partial class OAuthAuthorize : System.Web.UI.Page {
private EndUserAuthorizationRequest pendingRequest;
- protected async void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- this.pendingRequest = await OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (this.pendingRequest == null) {
- throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!IsPostBack) {
+ this.pendingRequest =
+ await
+ OAuthServiceProvider.AuthorizationServer.ReadAuthorizationRequestAsync(
+ new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ if (this.pendingRequest == null) {
+ throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
+ }
- this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie();
- var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
- this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name);
- this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope));
+ this.csrfCheck.Value = Code.SiteUtilities.SetCsrfCookie();
+ var requestingClient =
+ Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
+ this.consumerNameLabel.Text = HttpUtility.HtmlEncode(requestingClient.Name);
+ this.scopeLabel.Text = HttpUtility.HtmlEncode(OAuthUtilities.JoinScopes(this.pendingRequest.Scope));
- // Consider auto-approving if safe to do so.
- if (((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices).CanBeAutoApproved(this.pendingRequest)) {
- var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
- var responseMessage = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
- await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
- this.Context.Response.End();
- }
- this.ViewState["AuthRequest"] = this.pendingRequest;
- } else {
- Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value);
- this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"];
- }
+ // Consider auto-approving if safe to do so.
+ if (
+ ((OAuthAuthorizationServer)OAuthServiceProvider.AuthorizationServer.AuthorizationServerServices)
+ .CanBeAutoApproved(this.pendingRequest)) {
+ var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(
+ this.pendingRequest, HttpContext.Current.User.Identity.Name);
+ var responseMessage =
+ await
+ OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(
+ response, Response.ClientDisconnectedToken);
+ await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
+ this.Context.Response.End();
+ }
+ this.ViewState["AuthRequest"] = this.pendingRequest;
+ } else {
+ Code.SiteUtilities.VerifyCsrfCookie(this.csrfCheck.Value);
+ this.pendingRequest = (EndUserAuthorizationRequest)this.ViewState["AuthRequest"];
+ }
+ }));
}
- protected async void yesButton_Click(object sender, EventArgs e) {
- var requestingClient = Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
- Database.LoggedInUser.ClientAuthorizations.Add(
- new ClientAuthorization {
- Client = requestingClient,
- Scope = OAuthUtilities.JoinScopes(this.pendingRequest.Scope),
- User = Database.LoggedInUser,
- CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
- });
- var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(this.pendingRequest, HttpContext.Current.User.Identity.Name);
- var responseMessage = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
- await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
- this.Context.Response.End();
+ protected void yesButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var requestingClient =
+ Database.DataContext.Clients.First(c => c.ClientIdentifier == this.pendingRequest.ClientIdentifier);
+ Database.LoggedInUser.ClientAuthorizations.Add(
+ new ClientAuthorization {
+ Client = requestingClient,
+ Scope = OAuthUtilities.JoinScopes(this.pendingRequest.Scope),
+ User = Database.LoggedInUser,
+ CreatedOnUtc = DateTime.UtcNow.CutToSecond(),
+ });
+ var response = OAuthServiceProvider.AuthorizationServer.PrepareApproveAuthorizationRequest(
+ this.pendingRequest, HttpContext.Current.User.Identity.Name);
+ var responseMessage =
+ await
+ OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
+ await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
+ this.Context.Response.End();
+ }));
}
- protected async void noButton_Click(object sender, EventArgs e) {
- var response = OAuthServiceProvider.AuthorizationServer.PrepareRejectAuthorizationRequest(this.pendingRequest);
- var responseMessage = await OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
- await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
- this.Context.Response.End();
+ protected void noButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var response = OAuthServiceProvider.AuthorizationServer.PrepareRejectAuthorizationRequest(this.pendingRequest);
+ var responseMessage =
+ await
+ OAuthServiceProvider.AuthorizationServer.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
+ await responseMessage.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
+ this.Context.Response.End();
+ }));
}
}
}
diff --git a/samples/OAuthClient/Facebook.aspx.cs b/samples/OAuthClient/Facebook.aspx.cs
index 3a9cf14..19211bc 100644
--- a/samples/OAuthClient/Facebook.aspx.cs
+++ b/samples/OAuthClient/Facebook.aspx.cs
@@ -3,6 +3,8 @@
using System.Configuration;
using System.Net;
using System.Web;
+ using System.Web.UI;
+
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.ApplicationBlock.Facebook;
using DotNetOpenAuth.Messaging;
@@ -14,22 +16,30 @@
ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["facebookAppSecret"]),
};
- protected async void Page_Load(object sender, EventArgs e) {
- IAuthorizationState authorization = await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (authorization == null) {
- // Kick off authorization request
- var request = await client.PrepareRequestUserAuthorizationAsync(cancellationToken: Response.ClientDisconnectedToken);
- await request.SendAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
- 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);
- }
- }
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ 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/SampleWcf2.aspx.cs b/samples/OAuthClient/SampleWcf2.aspx.cs
index af12a26..e96a5c0 100644
--- a/samples/OAuthClient/SampleWcf2.aspx.cs
+++ b/samples/OAuthClient/SampleWcf2.aspx.cs
@@ -50,72 +50,95 @@
set { HttpContext.Current.Session["Authorization"] = value; }
}
- protected async void Page_Load(object sender, EventArgs e) {
- 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 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 async void getAuthorizationButton_Click(object sender, EventArgs e) {
- 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 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 async void getNameButton_Click(object sender, EventArgs e) {
- 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 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 async void getAgeButton_Click(object sender, EventArgs e) {
- 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 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 async void getFavoriteSites_Click(object sender, EventArgs e) {
- 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!";
- }
+ 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) {
diff --git a/samples/OAuthClient/WindowsLive.aspx.cs b/samples/OAuthClient/WindowsLive.aspx.cs
index 23566c5..efe41ec 100644
--- a/samples/OAuthClient/WindowsLive.aspx.cs
+++ b/samples/OAuthClient/WindowsLive.aspx.cs
@@ -18,31 +18,39 @@
ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["WindowsLiveAppSecret"]),
};
- protected async 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 = 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);
+ protected void Page_Load(object sender, EventArgs e) {
+ 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/OAuthConsumer/GoogleAddressBook.aspx.cs b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs
index ad25536..591f658 100644
--- a/samples/OAuthConsumer/GoogleAddressBook.aspx.cs
+++ b/samples/OAuthConsumer/GoogleAddressBook.aspx.cs
@@ -20,41 +20,53 @@
set { Session["GoogleAccessToken"] = value; }
}
- protected async void Page_Load(object sender, EventArgs e) {
- var google = new GoogleConsumer();
- if (google.ConsumerKey != null) {
- this.MultiView1.ActiveViewIndex = 1;
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var google = new GoogleConsumer();
+ if (google.ConsumerKey != null) {
+ this.MultiView1.ActiveViewIndex = 1;
- if (!IsPostBack) {
- // Is Google calling back with authorization?
- var accessTokenResponse = await google.ProcessUserAuthorizationAsync(this.Request.Url);
- if (accessTokenResponse != null) {
- this.AccessToken = accessTokenResponse.AccessToken;
- } else if (this.AccessToken.Token == null) {
- // If we don't yet have access, immediately request it.
- Uri redirectUri = await google.RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts);
- this.Response.Redirect(redirectUri.AbsoluteUri);
- }
- }
- }
+ if (!IsPostBack) {
+ // Is Google calling back with authorization?
+ var accessTokenResponse = await google.ProcessUserAuthorizationAsync(this.Request.Url);
+ if (accessTokenResponse != null) {
+ this.AccessToken = accessTokenResponse.AccessToken;
+ } else if (this.AccessToken.Token == null) {
+ // If we don't yet have access, immediately request it.
+ Uri redirectUri = await google.RequestUserAuthorizationAsync(GoogleConsumer.Applications.Contacts);
+ this.Response.Redirect(redirectUri.AbsoluteUri);
+ }
+ }
+ }
+ }));
}
- protected async void getAddressBookButton_Click(object sender, EventArgs e) {
- var google = new GoogleConsumer();
+ protected void getAddressBookButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var google = new GoogleConsumer();
- XDocument contactsDocument = await google.GetContactsAsync(this.AccessToken, 5, 1, Response.ClientDisconnectedToken);
- 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() });
+ XDocument contactsDocument =
+ await google.GetContactsAsync(this.AccessToken, 5, 1, Response.ClientDisconnectedToken);
+ 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/OAuthConsumer/GoogleApps2Legged.aspx.cs b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs
index d9a886e..52cc885 100644
--- a/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs
+++ b/samples/OAuthConsumer/GoogleApps2Legged.aspx.cs
@@ -12,12 +12,16 @@
using DotNetOpenAuth.OAuth.Messages;
public partial class GoogleApps2Legged : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- var google = new GoogleConsumer();
- var accessToken = await google.RequestNewClientAccountAsync();
- using (var httpClient = google.CreateHttpClient(accessToken.AccessToken)) {
- await httpClient.GetAsync("http://someUri", Response.ClientDisconnectedToken);
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var google = new GoogleConsumer();
+ var accessToken = await google.RequestNewClientAccountAsync();
+ using (var httpClient = google.CreateHttpClient(accessToken.AccessToken)) {
+ await httpClient.GetAsync("http://someUri", Response.ClientDisconnectedToken);
+ }
+ }));
}
protected void getAddressBookButton_Click(object sender, EventArgs e) {
diff --git a/samples/OAuthConsumer/SampleWcf.aspx.cs b/samples/OAuthConsumer/SampleWcf.aspx.cs
index 4e0d6cd..764b4d7 100644
--- a/samples/OAuthConsumer/SampleWcf.aspx.cs
+++ b/samples/OAuthConsumer/SampleWcf.aspx.cs
@@ -10,6 +10,7 @@
using System.ServiceModel.Security;
using System.Threading.Tasks;
using System.Web;
+ using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth;
using DotNetOpenAuth.ApplicationBlock;
@@ -22,58 +23,75 @@
/// Sample consumer of our Service Provider sample's WCF service.
/// </summary>
public partial class SampleWcf : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- var consumer = this.CreateConsumer();
- if (consumer.ConsumerKey != null) {
- var accessTokenMessage = await consumer.ProcessUserAuthorizationAsync(this.Request.Url);
- if (accessTokenMessage != null) {
- Session["WcfAccessToken"] = accessTokenMessage.AccessToken;
- this.authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken;
- }
- }
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!IsPostBack) {
+ var consumer = this.CreateConsumer();
+ if (consumer.ConsumerKey != null) {
+ var accessTokenMessage = await consumer.ProcessUserAuthorizationAsync(this.Request.Url);
+ if (accessTokenMessage != null) {
+ Session["WcfAccessToken"] = accessTokenMessage.AccessToken;
+ this.authorizationLabel.Text = "Authorized! Access token: " + accessTokenMessage.AccessToken;
+ }
+ }
+ }
+ }));
}
- protected async void getAuthorizationButton_Click(object sender, EventArgs e) {
- var consumer = this.CreateConsumer();
- UriBuilder callback = new UriBuilder(Request.Url);
- callback.Query = null;
- string[] scopes = (from item in this.scopeList.Items.OfType<ListItem>()
- where item.Selected
- select item.Value).ToArray();
- string scope = string.Join("|", scopes);
- var requestParams = new Dictionary<string, string> {
- { "scope", scope },
- };
- Uri redirectUri = await consumer.RequestUserAuthorizationAsync(callback.Uri, requestParams);
- this.Response.Redirect(redirectUri.AbsoluteUri);
+ protected void getAuthorizationButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var consumer = this.CreateConsumer();
+ UriBuilder callback = new UriBuilder(Request.Url);
+ callback.Query = null;
+ string[] scopes =
+ (from item in this.scopeList.Items.OfType<ListItem>() where item.Selected select item.Value).ToArray();
+ string scope = string.Join("|", scopes);
+ var requestParams = new Dictionary<string, string> { { "scope", scope }, };
+ Uri redirectUri = await consumer.RequestUserAuthorizationAsync(callback.Uri, requestParams);
+ this.Response.Redirect(redirectUri.AbsoluteUri);
+ }));
}
- protected async void getNameButton_Click(object sender, EventArgs e) {
- try {
- this.nameLabel.Text = await this.CallServiceAsync(client => client.GetName());
- } catch (SecurityAccessDeniedException) {
- this.nameLabel.Text = "Access denied!";
- }
+ protected void getNameButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ try {
+ this.nameLabel.Text = await this.CallServiceAsync(client => client.GetName());
+ } catch (SecurityAccessDeniedException) {
+ this.nameLabel.Text = "Access denied!";
+ }
+ }));
}
- protected async void getAgeButton_Click(object sender, EventArgs e) {
- try {
- int? age = await this.CallServiceAsync(client => client.GetAge());
- this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
- } catch (SecurityAccessDeniedException) {
- this.ageLabel.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());
+ this.ageLabel.Text = age.HasValue ? age.Value.ToString(CultureInfo.CurrentCulture) : "not available";
+ } catch (SecurityAccessDeniedException) {
+ this.ageLabel.Text = "Access denied!";
+ }
+ }));
}
- protected async void getFavoriteSites_Click(object sender, EventArgs e) {
- try {
- string[] favoriteSites = await this.CallServiceAsync(client => client.GetFavoriteSites());
- this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
- } catch (SecurityAccessDeniedException) {
- this.favoriteSitesLabel.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());
+ this.favoriteSitesLabel.Text = string.Join(", ", favoriteSites);
+ } catch (SecurityAccessDeniedException) {
+ this.favoriteSitesLabel.Text = "Access denied!";
+ }
+ }));
}
private async Task<T> CallServiceAsync<T>(Func<DataApiClient, T> predicate) {
diff --git a/samples/OAuthConsumer/SignInWithTwitter.aspx.cs b/samples/OAuthConsumer/SignInWithTwitter.aspx.cs
index 93462d5..9e422e6 100644
--- a/samples/OAuthConsumer/SignInWithTwitter.aspx.cs
+++ b/samples/OAuthConsumer/SignInWithTwitter.aspx.cs
@@ -15,29 +15,39 @@
using DotNetOpenAuth.OAuth;
public partial class SignInWithTwitter : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- if (TwitterConsumer.IsTwitterConsumerConfigured) {
- this.MultiView1.ActiveViewIndex = 1;
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (TwitterConsumer.IsTwitterConsumerConfigured) {
+ this.MultiView1.ActiveViewIndex = 1;
- if (!IsPostBack) {
- var tuple = await TwitterConsumer.TryFinishSignInWithTwitterAsync();
- if (tuple != null) {
- string screenName = tuple.Item1;
- int userId = tuple.Item2;
- this.loggedInPanel.Visible = true;
- this.loggedInName.Text = screenName;
+ if (!IsPostBack) {
+ var tuple = await TwitterConsumer.TryFinishSignInWithTwitterAsync();
+ if (tuple != null) {
+ string screenName = tuple.Item1;
+ int userId = tuple.Item2;
+ 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);
- }
- }
- }
+ // In a real app, the Twitter username would likely be used
+ // to log the user into the application.
+ ////FormsAuthentication.RedirectFromLoginPage(screenName, false);
+ }
+ }
+ }
+ }));
}
- protected async void signInButton_Click(object sender, ImageClickEventArgs e) {
- Uri redirectUri = await TwitterConsumer.StartSignInWithTwitterAsync(this.forceLoginCheckbox.Checked, Response.ClientDisconnectedToken);
- this.Response.Redirect(redirectUri.AbsoluteUri);
+ protected void signInButton_Click(object sender, ImageClickEventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ Uri redirectUri =
+ await
+ TwitterConsumer.StartSignInWithTwitterAsync(this.forceLoginCheckbox.Checked, Response.ClientDisconnectedToken);
+ this.Response.Redirect(redirectUri.AbsoluteUri);
+ }));
}
}
} \ No newline at end of file
diff --git a/samples/OAuthConsumer/Twitter.aspx.cs b/samples/OAuthConsumer/Twitter.aspx.cs
index 6b298cc..42ffa6e 100644
--- a/samples/OAuthConsumer/Twitter.aspx.cs
+++ b/samples/OAuthConsumer/Twitter.aspx.cs
@@ -20,58 +20,70 @@
set { Session["TwitterAccessToken"] = value; }
}
- protected async void Page_Load(object sender, EventArgs e) {
- var twitter = new TwitterConsumer();
- if (twitter.ConsumerKey != null) {
- this.MultiView1.ActiveViewIndex = 1;
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var twitter = new TwitterConsumer();
+ if (twitter.ConsumerKey != null) {
+ this.MultiView1.ActiveViewIndex = 1;
- if (!IsPostBack) {
- // Is Twitter calling back with authorization?
- var accessTokenResponse = await twitter.ProcessUserAuthorizationAsync(this.Request.Url);
- if (accessTokenResponse != null) {
- this.AccessToken = accessTokenResponse.AccessToken;
- } else {
- // If we don't yet have access, immediately request it.
- Uri redirectUri = await twitter.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl());
- this.Response.Redirect(redirectUri.AbsoluteUri);
- }
- }
- }
+ if (!IsPostBack) {
+ // Is Twitter calling back with authorization?
+ var accessTokenResponse = await twitter.ProcessUserAuthorizationAsync(this.Request.Url);
+ if (accessTokenResponse != null) {
+ this.AccessToken = accessTokenResponse.AccessToken;
+ } else {
+ // If we don't yet have access, immediately request it.
+ Uri redirectUri = await twitter.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl());
+ this.Response.Redirect(redirectUri.AbsoluteUri);
+ }
+ }
+ }
+ }));
}
- protected async void downloadUpdates_Click(object sender, EventArgs e) {
- var twitter = new TwitterConsumer();
- var statusesJson = await twitter.GetUpdatesAsync(this.AccessToken);
+ protected void downloadUpdates_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var twitter = new TwitterConsumer();
+ var statusesJson = await twitter.GetUpdatesAsync(this.AccessToken);
- StringBuilder tableBuilder = new StringBuilder();
- tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");
+ StringBuilder tableBuilder = new StringBuilder();
+ tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");
- foreach (dynamic update in statusesJson) {
- if (!update.user.@protected.Value) {
- tableBuilder.AppendFormat(
- "<tr><td>{0}</td><td>{1}</td></tr>",
- HttpUtility.HtmlEncode(update.user.screen_name),
- HttpUtility.HtmlEncode(update.text));
- }
- }
+ foreach (dynamic update in statusesJson) {
+ if (!update.user.@protected.Value) {
+ tableBuilder.AppendFormat(
+ "<tr><td>{0}</td><td>{1}</td></tr>",
+ HttpUtility.HtmlEncode(update.user.screen_name),
+ HttpUtility.HtmlEncode(update.text));
+ }
+ }
- tableBuilder.Append("</table>");
- this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() });
+ tableBuilder.Append("</table>");
+ this.resultsPlaceholder.Controls.Add(new Literal { Text = tableBuilder.ToString() });
+ }));
}
- protected async 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;
- }
+ protected void uploadProfilePhotoButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (this.profilePhoto.PostedFile.ContentType == null) {
+ this.photoUploadedLabel.Visible = true;
+ this.photoUploadedLabel.Text = "Select a file first.";
+ return;
+ }
- var twitter = new TwitterConsumer();
- XDocument imageResult = await twitter.UpdateProfileImageAsync(
- this.AccessToken,
- this.profilePhoto.PostedFile.InputStream,
- this.profilePhoto.PostedFile.ContentType);
- this.photoUploadedLabel.Visible = true;
+ var twitter = new TwitterConsumer();
+ XDocument imageResult =
+ await
+ twitter.UpdateProfileImageAsync(
+ this.AccessToken, this.profilePhoto.PostedFile.InputStream, this.profilePhoto.PostedFile.ContentType);
+ this.photoUploadedLabel.Visible = true;
+ }));
}
}
} \ No newline at end of file
diff --git a/samples/OAuthConsumer/Yammer.aspx.cs b/samples/OAuthConsumer/Yammer.aspx.cs
index b1031ae..d139e4f 100644
--- a/samples/OAuthConsumer/Yammer.aspx.cs
+++ b/samples/OAuthConsumer/Yammer.aspx.cs
@@ -29,28 +29,36 @@
// TODO: code here
}
- protected async void obtainAuthorizationButton_Click(object sender, EventArgs e) {
- var yammer = new YammerConsumer();
- Uri popupWindowLocation = await yammer.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl());
- string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');";
- this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true);
- this.MultiView1.SetActiveView(this.CompleteAuthorizationView);
+ protected void obtainAuthorizationButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var yammer = new YammerConsumer();
+ Uri popupWindowLocation = await yammer.RequestUserAuthorizationAsync(MessagingUtilities.GetPublicFacingUrl());
+ string javascript = "window.open('" + popupWindowLocation.AbsoluteUri + "');";
+ this.Page.ClientScript.RegisterStartupScript(GetType(), "YammerPopup", javascript, true);
+ this.MultiView1.SetActiveView(this.CompleteAuthorizationView);
+ }));
}
- protected async void finishAuthorizationButton_Click(object sender, EventArgs e) {
- if (!Page.IsValid) {
- return;
- }
+ protected void finishAuthorizationButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!Page.IsValid) {
+ return;
+ }
- var yammer = new YammerConsumer();
- var authorizationResponse = await yammer.ProcessUserAuthorizationAsync(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;
- }
+ var yammer = new YammerConsumer();
+ var authorizationResponse = await yammer.ProcessUserAuthorizationAsync(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/OAuthServiceProvider/Members/Authorize.aspx.cs b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs
index 72ebd04..073231b 100644
--- a/samples/OAuthServiceProvider/Members/Authorize.aspx.cs
+++ b/samples/OAuthServiceProvider/Members/Authorize.aspx.cs
@@ -46,33 +46,37 @@
}
}
- protected async void allowAccessButton_Click(object sender, EventArgs e) {
- if (this.AuthorizationSecret != this.OAuthAuthorizationSecToken.Value) {
- throw new ArgumentException(); // probably someone trying to hack in.
- }
- this.AuthorizationSecret = null; // clear one time use secret
- var pending = Global.PendingOAuthAuthorization;
- Global.AuthorizePendingRequestToken();
- this.multiView.ActiveViewIndex = 1;
+ protected void allowAccessButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (this.AuthorizationSecret != this.OAuthAuthorizationSecToken.Value) {
+ throw new ArgumentException(); // probably someone trying to hack in.
+ }
+ this.AuthorizationSecret = null; // clear one time use secret
+ var pending = Global.PendingOAuthAuthorization;
+ Global.AuthorizePendingRequestToken();
+ this.multiView.ActiveViewIndex = 1;
- ServiceProvider sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager);
- var response = sp.PrepareAuthorizationResponse(pending);
- if (response != null) {
- var responseMessage = await sp.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
- await responseMessage.SendAsync();
- this.Context.Response.End();
- } else {
- if (pending.IsUnsafeRequest) {
- this.verifierMultiView.ActiveViewIndex = 1;
- } else {
- string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10);
- this.verificationCodeLabel.Text = verifier;
- ITokenContainingMessage requestTokenMessage = pending;
- var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token);
- requestToken.VerificationCode = verifier;
- Global.TokenManager.UpdateToken(requestToken);
- }
- }
+ ServiceProvider sp = new ServiceProvider(Constants.SelfDescription, Global.TokenManager);
+ var response = sp.PrepareAuthorizationResponse(pending);
+ if (response != null) {
+ var responseMessage = await sp.Channel.PrepareResponseAsync(response, Response.ClientDisconnectedToken);
+ await responseMessage.SendAsync();
+ this.Context.Response.End();
+ } else {
+ if (pending.IsUnsafeRequest) {
+ this.verifierMultiView.ActiveViewIndex = 1;
+ } else {
+ string verifier = ServiceProvider.CreateVerificationCode(VerificationCodeFormat.AlphaNumericNoLookAlikes, 10);
+ this.verificationCodeLabel.Text = verifier;
+ ITokenContainingMessage requestTokenMessage = pending;
+ var requestToken = Global.TokenManager.GetRequestToken(requestTokenMessage.Token);
+ requestToken.VerificationCode = verifier;
+ Global.TokenManager.UpdateToken(requestToken);
+ }
+ }
+ }));
}
protected void denyAccessButton_Click(object sender, EventArgs e) {
diff --git a/samples/OpenIdProviderWebForms/Default.aspx.cs b/samples/OpenIdProviderWebForms/Default.aspx.cs
index 4c572a4..5d27251 100644
--- a/samples/OpenIdProviderWebForms/Default.aspx.cs
+++ b/samples/OpenIdProviderWebForms/Default.aspx.cs
@@ -2,6 +2,7 @@
using System;
using System.Threading.Tasks;
using System.Web.Security;
+ using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
@@ -12,24 +13,32 @@
/// Page for handling logins to this server.
/// </summary>
public partial class _default : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- if (Request.QueryString["rp"] != null) {
- if (Page.User.Identity.IsAuthenticated) {
- await this.SendAssertionAsync(Request.QueryString["rp"]);
- } else {
- FormsAuthentication.RedirectToLoginPage();
- }
- } else {
- TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite");
- if (relyingPartySite != null) {
- relyingPartySite.Focus();
- }
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (Request.QueryString["rp"] != null) {
+ if (Page.User.Identity.IsAuthenticated) {
+ await this.SendAssertionAsync(Request.QueryString["rp"]);
+ } else {
+ FormsAuthentication.RedirectToLoginPage();
+ }
+ } else {
+ TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite");
+ if (relyingPartySite != null) {
+ relyingPartySite.Focus();
+ }
+ }
+ }));
}
protected async void sendAssertionButton_Click(object sender, EventArgs e) {
- TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite");
- await this.SendAssertionAsync(relyingPartySite.Text);
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ TextBox relyingPartySite = (TextBox)this.loginView.FindControl("relyingPartySite");
+ await this.SendAssertionAsync(relyingPartySite.Text);
+ }));
}
private async Task SendAssertionAsync(string relyingPartyRealm) {
diff --git a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj
index c95ee15..1ff3f44 100644
--- a/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj
+++ b/samples/OpenIdProviderWebForms/OpenIdProviderWebForms.csproj
@@ -100,7 +100,6 @@
<SubType>Designer</SubType>
</Content>
<Content Include="user_xrds.aspx" />
- <Content Include="WebForm1.aspx" />
</ItemGroup>
<ItemGroup>
<Compile Include="access_token.ashx.cs">
@@ -176,13 +175,6 @@
<Compile Include="user.aspx.designer.cs">
<DependentUpon>user.aspx</DependentUpon>
</Compile>
- <Compile Include="WebForm1.aspx.cs">
- <DependentUpon>WebForm1.aspx</DependentUpon>
- <SubType>ASPXCodeBehind</SubType>
- </Compile>
- <Compile Include="WebForm1.aspx.designer.cs">
- <DependentUpon>WebForm1.aspx</DependentUpon>
- </Compile>
</ItemGroup>
<ItemGroup>
<Content Include="favicon.ico" />
diff --git a/samples/OpenIdProviderWebForms/WebForm1.aspx b/samples/OpenIdProviderWebForms/WebForm1.aspx
deleted file mode 100644
index 8639049..0000000
--- a/samples/OpenIdProviderWebForms/WebForm1.aspx
+++ /dev/null
@@ -1,16 +0,0 @@
-<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="OpenIdProviderWebForms.WebForm1" Async="true" %>
-
-<!DOCTYPE html>
-
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head runat="server">
- <title></title>
-</head>
-<body>
- <form id="form1" runat="server">
- <div>
-
- </div>
- </form>
-</body>
-</html>
diff --git a/samples/OpenIdProviderWebForms/WebForm1.aspx.cs b/samples/OpenIdProviderWebForms/WebForm1.aspx.cs
deleted file mode 100644
index 6ec73e6..0000000
--- a/samples/OpenIdProviderWebForms/WebForm1.aspx.cs
+++ /dev/null
@@ -1,15 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Web;
-using System.Web.UI;
-using System.Web.UI.WebControls;
-
-namespace OpenIdProviderWebForms {
- public partial class WebForm1 : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- object oldValue = Session["Hi"];
- Session["Hi"] = new object();
- }
- }
-} \ No newline at end of file
diff --git a/samples/OpenIdProviderWebForms/WebForm1.aspx.designer.cs b/samples/OpenIdProviderWebForms/WebForm1.aspx.designer.cs
deleted file mode 100644
index 0e75ef7..0000000
--- a/samples/OpenIdProviderWebForms/WebForm1.aspx.designer.cs
+++ /dev/null
@@ -1,24 +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 OpenIdProviderWebForms {
-
-
- public partial class WebForm1 {
-
- /// <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;
- }
-}
diff --git a/samples/OpenIdProviderWebForms/decide.aspx.cs b/samples/OpenIdProviderWebForms/decide.aspx.cs
index d3ef6d2..00bdb6d 100644
--- a/samples/OpenIdProviderWebForms/decide.aspx.cs
+++ b/samples/OpenIdProviderWebForms/decide.aspx.cs
@@ -14,116 +14,128 @@ namespace OpenIdProviderWebForms {
/// Page for giving the user the option to continue or cancel out of authentication with a consumer.
/// </summary>
public partial class decide : Page {
- protected async void Page_Load(object src, EventArgs e) {
- if (ProviderEndpoint.PendingRequest == null) {
- // Response.Redirect(string) throws ThreadInterruptedException, and "async void Page_Load" doesn't properly catch it.
- this.Response.RedirectLocation = "/";
- this.Response.StatusCode = (int)HttpStatusCode.Redirect;
- this.Context.ApplicationInstance.CompleteRequest();
- return;
- }
-
- this.relyingPartyVerificationResultLabel.Text =
- await ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverableAsync() == RelyingPartyDiscoveryResult.Success ? "passed" : "failed";
-
- this.realmLabel.Text = ProviderEndpoint.PendingRequest.Realm.ToString();
-
- var oauthRequest = OAuthHybrid.ServiceProvider.ReadAuthorizationRequest(ProviderEndpoint.PendingRequest);
- if (oauthRequest != null) {
- this.OAuthPanel.Visible = true;
- }
-
- if (ProviderEndpoint.PendingAuthenticationRequest != null) {
- if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity) {
- ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier = Code.Util.BuildIdentityUrl();
+ protected void Page_Load(object src, EventArgs e) {
+ this.RegisterAsyncTask(new PageAsyncTask(async ct => {
+ if (ProviderEndpoint.PendingRequest == null) {
+ // Response.Redirect(string) throws ThreadInterruptedException, and "async void Page_Load" doesn't properly catch it.
+ this.Response.RedirectLocation = "/";
+ this.Response.StatusCode = (int)HttpStatusCode.Redirect;
+ this.Context.ApplicationInstance.CompleteRequest();
+ return;
}
- this.identityUrlLabel.Text = ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier.ToString();
- // check that the logged in user is the same as the user requesting authentication to the consumer. If not, then log them out.
- if (!string.Equals(User.Identity.Name, Code.Util.ExtractUserName(ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier), StringComparison.OrdinalIgnoreCase)) {
- FormsAuthentication.SignOut();
- Response.Redirect(Request.Url.AbsoluteUri);
+ this.relyingPartyVerificationResultLabel.Text =
+ await ProviderEndpoint.PendingRequest.IsReturnUrlDiscoverableAsync() == RelyingPartyDiscoveryResult.Success ? "passed" : "failed";
+
+ this.realmLabel.Text = ProviderEndpoint.PendingRequest.Realm.ToString();
+
+ var oauthRequest = OAuthHybrid.ServiceProvider.ReadAuthorizationRequest(ProviderEndpoint.PendingRequest);
+ if (oauthRequest != null) {
+ this.OAuthPanel.Visible = true;
}
- } else {
- this.identityUrlLabel.Text = "(not applicable)";
- this.siteRequestLabel.Text = "A site has asked for information about you.";
- }
-
- // if simple registration fields were used, then prompt the user for them
- var requestedFields = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>();
- if (requestedFields != null) {
- this.profileFields.Visible = true;
- this.profileFields.SetRequiredFieldsFromRequest(requestedFields);
- if (!IsPostBack) {
- var sregResponse = requestedFields.CreateResponse();
-
- // We MAY not have an entry for this user if they used Yubikey to log in.
- MembershipUser user = Membership.GetUser();
- if (user != null) {
- sregResponse.Email = Membership.GetUser().Email;
+
+ if (ProviderEndpoint.PendingAuthenticationRequest != null) {
+ if (ProviderEndpoint.PendingAuthenticationRequest.IsDirectedIdentity) {
+ ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier = Code.Util.BuildIdentityUrl();
+ }
+ this.identityUrlLabel.Text = ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier.ToString();
+
+ // check that the logged in user is the same as the user requesting authentication to the consumer. If not, then log them out.
+ if (!string.Equals(User.Identity.Name, Code.Util.ExtractUserName(ProviderEndpoint.PendingAuthenticationRequest.LocalIdentifier), StringComparison.OrdinalIgnoreCase)) {
+ FormsAuthentication.SignOut();
+ Response.Redirect(Request.Url.AbsoluteUri);
}
- this.profileFields.SetOpenIdProfileFields(sregResponse);
+ } else {
+ this.identityUrlLabel.Text = "(not applicable)";
+ this.siteRequestLabel.Text = "A site has asked for information about you.";
}
- }
- }
- protected async void Yes_Click(object sender, EventArgs e) {
- if (!Page.IsValid || ProviderEndpoint.PendingRequest == null) {
- return;
- }
-
- if (this.OAuthPanel.Visible) {
- string grantedScope = null;
- if (this.oauthPermission.Checked) {
- // This SIMPLE sample merely uses the realm as the consumerKey,
- // but in a real app this will probably involve a database lookup to translate
- // the realm to a known consumerKey.
- grantedScope = string.Empty; // we don't scope individual access rights on this sample
+ // if simple registration fields were used, then prompt the user for them
+ var requestedFields = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>();
+ if (requestedFields != null) {
+ this.profileFields.Visible = true;
+ this.profileFields.SetRequiredFieldsFromRequest(requestedFields);
+ if (!IsPostBack) {
+ var sregResponse = requestedFields.CreateResponse();
+
+ // We MAY not have an entry for this user if they used Yubikey to log in.
+ MembershipUser user = Membership.GetUser();
+ if (user != null) {
+ sregResponse.Email = Membership.GetUser().Email;
+ }
+ this.profileFields.SetOpenIdProfileFields(sregResponse);
+ }
}
+ }));
+ }
- OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope);
- }
-
- var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>();
- ClaimsResponse sregResponse = null;
- if (sregRequest != null) {
- sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest);
- ProviderEndpoint.PendingRequest.AddResponseExtension(sregResponse);
- }
- var papeRequest = ProviderEndpoint.PendingRequest.GetExtension<PolicyRequest>();
- PolicyResponse papeResponse = null;
- if (papeRequest != null) {
- papeResponse = new PolicyResponse();
- papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
- ProviderEndpoint.PendingRequest.AddResponseExtension(papeResponse);
- }
-
- if (ProviderEndpoint.PendingAuthenticationRequest != null) {
- ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
- } else {
- ProviderEndpoint.PendingAnonymousRequest.IsApproved = true;
- }
- Debug.Assert(ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
-
- var provider = new ProviderEndpoint();
- var response = await provider.PrepareResponseAsync();
- await response.SendAsync();
+ protected void Yes_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!Page.IsValid || ProviderEndpoint.PendingRequest == null) {
+ return;
+ }
+
+ if (this.OAuthPanel.Visible) {
+ string grantedScope = null;
+ if (this.oauthPermission.Checked) {
+ // This SIMPLE sample merely uses the realm as the consumerKey,
+ // but in a real app this will probably involve a database lookup to translate
+ // the realm to a known consumerKey.
+ grantedScope = string.Empty; // we don't scope individual access rights on this sample
+ }
+
+ OAuthHybrid.ServiceProvider.AttachAuthorizationResponse(ProviderEndpoint.PendingRequest, grantedScope);
+ }
+
+ var sregRequest = ProviderEndpoint.PendingRequest.GetExtension<ClaimsRequest>();
+ ClaimsResponse sregResponse = null;
+ if (sregRequest != null) {
+ sregResponse = this.profileFields.GetOpenIdProfileFields(sregRequest);
+ ProviderEndpoint.PendingRequest.AddResponseExtension(sregResponse);
+ }
+ var papeRequest = ProviderEndpoint.PendingRequest.GetExtension<PolicyRequest>();
+ PolicyResponse papeResponse = null;
+ if (papeRequest != null) {
+ papeResponse = new PolicyResponse();
+ papeResponse.NistAssuranceLevel = NistAssuranceLevel.InsufficientForLevel1;
+ ProviderEndpoint.PendingRequest.AddResponseExtension(papeResponse);
+ }
+
+ if (ProviderEndpoint.PendingAuthenticationRequest != null) {
+ ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
+ } else {
+ ProviderEndpoint.PendingAnonymousRequest.IsApproved = true;
+ }
+ Debug.Assert(
+ ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
+
+ var provider = new ProviderEndpoint();
+ var response = await provider.PrepareResponseAsync();
+ await response.SendAsync();
+ }));
}
- protected async void No_Click(object sender, EventArgs e) {
- if (ProviderEndpoint.PendingRequest == null) {
- return;
- }
-
- if (ProviderEndpoint.PendingAuthenticationRequest != null) {
- ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = false;
- } else {
- ProviderEndpoint.PendingAnonymousRequest.IsApproved = false;
- }
- Debug.Assert(ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
- var provider = new ProviderEndpoint();
- var response = await provider.PrepareResponseAsync();
- await response.SendAsync();
+ protected void No_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (ProviderEndpoint.PendingRequest == null) {
+ return;
+ }
+
+ if (ProviderEndpoint.PendingAuthenticationRequest != null) {
+ ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = false;
+ } else {
+ ProviderEndpoint.PendingAnonymousRequest.IsApproved = false;
+ }
+ Debug.Assert(
+ ProviderEndpoint.PendingRequest.IsResponseReady, "Setting authentication should be all that's necessary.");
+ var provider = new ProviderEndpoint();
+ var response = await provider.PrepareResponseAsync();
+ await response.SendAsync();
+ }));
}
}
} \ No newline at end of file
diff --git a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs
index 3af9783..909c4bc 100644
--- a/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/DetectGoogleSession.aspx.cs
@@ -1,6 +1,7 @@
namespace OpenIdRelyingPartyWebForms {
using System;
using System.Web;
+ using System.Web.UI;
using DotNetOpenAuth.ApplicationBlock.CustomExtensions;
using DotNetOpenAuth.OpenId;
@@ -12,38 +13,45 @@
private const string UIModeDetectSession = "x-has-session";
- protected async void Page_Load(object sender, EventArgs e) {
- using (var openid = new OpenIdRelyingParty()) {
- // In order to receive the UIRequest as a response, we must register a custom extension factory.
- openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory());
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ using (var openid = new OpenIdRelyingParty()) {
+ // In order to receive the UIRequest as a response, we must register a custom extension factory.
+ openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory());
- var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (response == null) {
- // Submit an OpenID request which Google must reply to immediately.
- // If the user hasn't established a trust relationship with this site yet,
- // Google will not give us the user identity, but they will tell us whether the user
- // at least has an active login session with them so we know whether to promote the
- // "Log in with Google" button.
- IAuthenticationRequest request = await openid.CreateRequestAsync("https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- request.AddExtension(new UIRequest { Mode = UIModeDetectSession });
- request.Mode = AuthenticationRequestMode.Immediate;
- await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
- } else {
- if (response.Status == AuthenticationStatus.Authenticated) {
- this.YouTrustUsLabel.Visible = true;
- } else if (response.Status == AuthenticationStatus.SetupRequired) {
- // Google refused to authenticate the user without user interaction.
- // This is either because Google doesn't know who the user is yet,
- // or because the user hasn't indicated to Google to trust this site.
- // Google uniquely offers the RP a tip as to which of the above situations is true.
- // Figure out which it is. In a real app, you might use this value to promote a
- // Google login button on your site if you detect that a Google session exists.
- var ext = response.GetUntrustedExtension<UIRequest>();
- this.YouAreLoggedInLabel.Visible = ext != null && ext.Mode == UIModeDetectSession;
- this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible;
- }
- }
- }
+ var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ if (response == null) {
+ // Submit an OpenID request which Google must reply to immediately.
+ // If the user hasn't established a trust relationship with this site yet,
+ // Google will not give us the user identity, but they will tell us whether the user
+ // at least has an active login session with them so we know whether to promote the
+ // "Log in with Google" button.
+ IAuthenticationRequest request =
+ await
+ openid.CreateRequestAsync(
+ "https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ request.AddExtension(new UIRequest { Mode = UIModeDetectSession });
+ request.Mode = AuthenticationRequestMode.Immediate;
+ await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
+ } else {
+ if (response.Status == AuthenticationStatus.Authenticated) {
+ this.YouTrustUsLabel.Visible = true;
+ } else if (response.Status == AuthenticationStatus.SetupRequired) {
+ // Google refused to authenticate the user without user interaction.
+ // This is either because Google doesn't know who the user is yet,
+ // or because the user hasn't indicated to Google to trust this site.
+ // Google uniquely offers the RP a tip as to which of the above situations is true.
+ // Figure out which it is. In a real app, you might use this value to promote a
+ // Google login button on your site if you detect that a Google session exists.
+ var ext = response.GetUntrustedExtension<UIRequest>();
+ this.YouAreLoggedInLabel.Visible = ext != null && ext.Mode == UIModeDetectSession;
+ this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible;
+ }
+ }
+ }
+ }));
}
}
} \ No newline at end of file
diff --git a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs
index 2b3b51d..d06e2f6 100644
--- a/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/MembersOnly/DisplayGoogleContacts.aspx.cs
@@ -3,28 +3,33 @@
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.OpenId.Extensions.AttributeExchange;
public partial class DisplayGoogleContacts : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- if (!string.IsNullOrEmpty(State.GoogleAccessToken.Token)) {
- this.MultiView1.ActiveViewIndex = 1;
- if (State.FetchResponse != null && State.FetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email)) {
- this.emailLabel.Text = State.FetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values[0];
- } else {
- this.emailLabel.Text = "unavailable";
- }
- this.claimedIdLabel.Text = this.User.Identity.Name;
- var google = new GoogleConsumer {
- ConsumerKey = Global.GoogleWebConsumer.ConsumerKey,
- ConsumerSecret = Global.GoogleWebConsumer.ConsumerSecret,
- };
- var contactsDocument = await google.GetContactsAsync(State.GoogleAccessToken);
- this.RenderContacts(contactsDocument);
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!string.IsNullOrEmpty(State.GoogleAccessToken.Token)) {
+ this.MultiView1.ActiveViewIndex = 1;
+ if (State.FetchResponse != null && State.FetchResponse.Attributes.Contains(WellKnownAttributes.Contact.Email)) {
+ this.emailLabel.Text = State.FetchResponse.Attributes[WellKnownAttributes.Contact.Email].Values[0];
+ } else {
+ this.emailLabel.Text = "unavailable";
+ }
+ this.claimedIdLabel.Text = this.User.Identity.Name;
+ var google = new GoogleConsumer {
+ ConsumerKey = Global.GoogleWebConsumer.ConsumerKey,
+ ConsumerSecret = Global.GoogleWebConsumer.ConsumerSecret,
+ };
+ var contactsDocument = await google.GetContactsAsync(State.GoogleAccessToken);
+ this.RenderContacts(contactsDocument);
+ }
+ }));
}
private void RenderContacts(XDocument contactsDocument) {
diff --git a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs
index 92e34df..fcfa257 100644
--- a/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/NoIdentityOpenId.aspx.cs
@@ -2,6 +2,7 @@
using System;
using System.Threading;
using System.Web;
+ using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId;
@@ -46,33 +47,40 @@
}
}
- protected async void beginButton_Click(object sender, EventArgs e) {
- if (!this.Page.IsValid) {
- return; // don't login if custom validation failed.
- }
- try {
- using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) {
- var request = await rp.CreateRequestAsync(this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- request.IsExtensionOnly = true;
+ protected void beginButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!this.Page.IsValid) {
+ return; // don't login if custom validation failed.
+ }
+ try {
+ using (OpenIdRelyingParty rp = new OpenIdRelyingParty()) {
+ var request =
+ await
+ rp.CreateRequestAsync(this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ request.IsExtensionOnly = true;
- // This is where you would add any OpenID extensions you wanted
- // to include in the request.
- request.AddExtension(new ClaimsRequest {
- Email = DemandLevel.Request,
- Country = DemandLevel.Request,
- Gender = DemandLevel.Require,
- PostalCode = DemandLevel.Require,
- TimeZone = DemandLevel.Require,
- });
+ // This is where you would add any OpenID extensions you wanted
+ // to include in the request.
+ request.AddExtension(
+ new ClaimsRequest {
+ Email = DemandLevel.Request,
+ Country = DemandLevel.Request,
+ Gender = DemandLevel.Require,
+ PostalCode = DemandLevel.Require,
+ TimeZone = DemandLevel.Require,
+ });
- await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
- }
- } catch (ProtocolException ex) {
- // The user probably entered an Identifier that
- // was not a valid OpenID endpoint.
- this.openidValidator.Text = ex.Message;
- this.openidValidator.IsValid = false;
- }
+ await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
+ }
+ } catch (ProtocolException ex) {
+ // The user probably entered an Identifier that
+ // was not a valid OpenID endpoint.
+ this.openidValidator.Text = ex.Message;
+ this.openidValidator.IsValid = false;
+ }
+ }));
}
protected void openidValidator_ServerValidate(object source, ServerValidateEventArgs args) {
diff --git a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs
index 0a479e3..ebfece3 100644
--- a/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/ajaxlogin.aspx.cs
@@ -1,5 +1,6 @@
namespace OpenIdRelyingPartyWebForms {
using System;
+ using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
using DotNetOpenAuth.OpenId.RelyingParty;
@@ -29,20 +30,24 @@
}
}
- protected async void submitButton_Click(object sender, EventArgs e) {
- if (!Page.IsValid) {
- return;
- }
-
- var response = await this.OpenIdAjaxTextBox1.GetAuthenticationResponseAsync(Response.ClientDisconnectedToken);
- if (response != null) {
- if (response.Status == AuthenticationStatus.Authenticated) {
- // Save comment here!
- this.multiView.ActiveViewIndex = 1;
- } else {
- this.multiView.ActiveViewIndex = 2;
- }
- }
+ protected void submitButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!Page.IsValid) {
+ return;
+ }
+
+ var response = await this.OpenIdAjaxTextBox1.GetAuthenticationResponseAsync(Response.ClientDisconnectedToken);
+ if (response != null) {
+ if (response.Status == AuthenticationStatus.Authenticated) {
+ // Save comment here!
+ this.multiView.ActiveViewIndex = 1;
+ } else {
+ this.multiView.ActiveViewIndex = 2;
+ }
+ }
+ }));
}
protected void editComment_Click(object sender, EventArgs e) {
diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs
index 0e6eae0..ecfaf49 100644
--- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuth.aspx.cs
@@ -3,6 +3,8 @@
using System.Threading.Tasks;
using System.Web;
using System.Web.Security;
+ using System.Web.UI;
+
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.OAuth;
using DotNetOpenAuth.OAuth.Messages;
@@ -14,39 +16,49 @@
private const string GoogleOPIdentifier = "https://www.google.com/accounts/o8/id";
private static readonly OpenIdRelyingParty relyingParty = new OpenIdRelyingParty();
- protected async void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase)) {
- // Disable the button since the scenario won't work under localhost,
- // and this will help encourage the user to read the the text above the button.
- this.beginButton.Enabled = false;
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!IsPostBack && string.Equals(Request.Url.Host, "localhost", StringComparison.OrdinalIgnoreCase)) {
+ // Disable the button since the scenario won't work under localhost,
+ // and this will help encourage the user to read the the text above the button.
+ this.beginButton.Enabled = false;
+ }
- IAuthenticationResponse authResponse = await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (authResponse != null) {
- switch (authResponse.Status) {
- case AuthenticationStatus.Authenticated:
- State.FetchResponse = authResponse.GetExtension<FetchResponse>();
- AccessTokenResponse accessToken = await Global.GoogleWebConsumer.ProcessUserAuthorizationAsync(authResponse, Response.ClientDisconnectedToken);
- if (accessToken != null) {
- State.GoogleAccessToken = accessToken.AccessToken;
- FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false);
- Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx");
- } else {
- MultiView1.SetActiveView(AuthorizationDenied);
+ IAuthenticationResponse authResponse =
+ await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ if (authResponse != null) {
+ switch (authResponse.Status) {
+ case AuthenticationStatus.Authenticated:
+ State.FetchResponse = authResponse.GetExtension<FetchResponse>();
+ AccessTokenResponse accessToken =
+ await Global.GoogleWebConsumer.ProcessUserAuthorizationAsync(authResponse, Response.ClientDisconnectedToken);
+ if (accessToken != null) {
+ State.GoogleAccessToken = accessToken.AccessToken;
+ FormsAuthentication.SetAuthCookie(authResponse.ClaimedIdentifier, false);
+ Response.Redirect("~/MembersOnly/DisplayGoogleContacts.aspx");
+ } else {
+ MultiView1.SetActiveView(AuthorizationDenied);
+ }
+ break;
+ case AuthenticationStatus.Canceled:
+ case AuthenticationStatus.Failed:
+ default:
+ this.MultiView1.SetActiveView(this.AuthenticationFailed);
+ break;
+ }
}
- break;
- case AuthenticationStatus.Canceled:
- case AuthenticationStatus.Failed:
- default:
- this.MultiView1.SetActiveView(this.AuthenticationFailed);
- break;
- }
- }
+ }));
}
- protected async void beginButton_Click(object sender, EventArgs e) {
- var request = await this.GetGoogleRequestAsync();
- await request.RedirectToProviderAsync();
+ protected void beginButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var request = await this.GetGoogleRequestAsync();
+ await request.RedirectToProviderAsync();
+ }));
}
private async Task<IAuthenticationRequest> GetGoogleRequestAsync() {
diff --git a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs
index 6133a86..0446c36 100644
--- a/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/loginPlusOAuthSampleOP.aspx.cs
@@ -2,6 +2,8 @@
using System;
using System.Web;
using System.Web.Security;
+ using System.Web.UI;
+
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OAuth;
@@ -15,12 +17,16 @@
protected void Page_Load(object sender, EventArgs e) {
}
- protected async void beginButton_Click(object sender, EventArgs e) {
- if (!Page.IsValid) {
- return;
- }
+ protected void beginButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!Page.IsValid) {
+ return;
+ }
- await this.identifierBox.LogOnAsync(Response.ClientDisconnectedToken);
+ await this.identifierBox.LogOnAsync(Response.ClientDisconnectedToken);
+ }));
}
protected void identifierBox_LoggingIn(object sender, OpenIdEventArgs e) {
@@ -28,27 +34,31 @@
consumer.AttachAuthorizationRequest(e.Request, "http://tempuri.org/IDataApi/GetName");
}
- protected async void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) {
- State.FetchResponse = e.Response.GetExtension<FetchResponse>();
+ protected void identifierBox_LoggedIn(object sender, OpenIdEventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ State.FetchResponse = e.Response.GetExtension<FetchResponse>();
- var serviceDescription = new ServiceProviderDescription {
- TokenRequestEndpoint = new Uri(e.Response.Provider.Uri, "/access_token.ashx"),
- };
- var consumer = CreateConsumer();
- consumer.ServiceProvider = serviceDescription;
- AccessTokenResponse accessToken = await consumer.ProcessUserAuthorizationAsync(e.Response);
- if (accessToken != null) {
- this.MultiView1.SetActiveView(this.AuthorizationGiven);
+ var serviceDescription = new ServiceProviderDescription {
+ TokenRequestEndpoint = new Uri(e.Response.Provider.Uri, "/access_token.ashx"),
+ };
+ var consumer = CreateConsumer();
+ consumer.ServiceProvider = serviceDescription;
+ AccessTokenResponse accessToken = await consumer.ProcessUserAuthorizationAsync(e.Response);
+ if (accessToken != null) {
+ this.MultiView1.SetActiveView(this.AuthorizationGiven);
- // At this point, the access token would be somehow associated with the user
- // account at the RP.
- ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken);
- } else {
- this.MultiView1.SetActiveView(this.AuthorizationDenied);
- }
+ // At this point, the access token would be somehow associated with the user
+ // account at the RP.
+ ////Database.Associate(e.Response.ClaimedIdentifier, accessToken.AccessToken);
+ } else {
+ this.MultiView1.SetActiveView(this.AuthorizationDenied);
+ }
- // Avoid the redirect
- e.Cancel = true;
+ // Avoid the redirect
+ e.Cancel = true;
+ }));
}
protected void identifierBox_Failed(object sender, OpenIdEventArgs e) {
diff --git a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs
index 9b27092..f47eae0 100644
--- a/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs
+++ b/samples/OpenIdRelyingPartyWebForms/loginProgrammatic.aspx.cs
@@ -16,80 +16,92 @@
args.IsValid = Identifier.IsValid(args.Value);
}
- protected async void loginButton_Click(object sender, EventArgs e) {
- if (!this.Page.IsValid) {
- return; // don't login if custom validation failed.
- }
- try {
- using (OpenIdRelyingParty openid = this.createRelyingParty()) {
- IAuthenticationRequest request = await openid.CreateRequestAsync(this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ protected void loginButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!this.Page.IsValid) {
+ return; // don't login if custom validation failed.
+ }
+ try {
+ using (OpenIdRelyingParty openid = this.createRelyingParty()) {
+ IAuthenticationRequest request =
+ await
+ openid.CreateRequestAsync(
+ this.openIdBox.Text, new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- // This is where you would add any OpenID extensions you wanted
- // to include in the authentication request.
- request.AddExtension(new ClaimsRequest {
- Country = DemandLevel.Request,
- Email = DemandLevel.Request,
- Gender = DemandLevel.Require,
- PostalCode = DemandLevel.Require,
- TimeZone = DemandLevel.Require,
- });
+ // This is where you would add any OpenID extensions you wanted
+ // to include in the authentication request.
+ request.AddExtension(
+ new ClaimsRequest {
+ Country = DemandLevel.Request,
+ Email = DemandLevel.Request,
+ Gender = DemandLevel.Require,
+ PostalCode = DemandLevel.Require,
+ TimeZone = DemandLevel.Require,
+ });
- // Send your visitor to their Provider for authentication.
- await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
- }
- } catch (ProtocolException ex) {
- // The user probably entered an Identifier that
- // was not a valid OpenID endpoint.
- this.openidValidator.Text = ex.Message;
- this.openidValidator.IsValid = false;
- }
+ // Send your visitor to their Provider for authentication.
+ await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
+ }
+ } catch (ProtocolException ex) {
+ // The user probably entered an Identifier that
+ // was not a valid OpenID endpoint.
+ this.openidValidator.Text = ex.Message;
+ this.openidValidator.IsValid = false;
+ }
+ }));
}
- protected async void Page_Load(object sender, EventArgs e) {
- this.openIdBox.Focus();
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ this.openIdBox.Focus();
- // For debugging/testing, we allow remote clearing of all associations...
- // NOT a good idea on a production site.
- if (Request.QueryString["clearAssociations"] == "1") {
- Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore");
+ // For debugging/testing, we allow remote clearing of all associations...
+ // NOT a good idea on a production site.
+ if (Request.QueryString["clearAssociations"] == "1") {
+ Application.Remove("DotNetOpenAuth.OpenId.RelyingParty.OpenIdRelyingParty.ApplicationStore");
- // Force a redirect now to prevent the user from logging in while associations
- // are constantly being cleared.
- UriBuilder builder = new UriBuilder(Request.Url);
- builder.Query = null;
- Response.Redirect(builder.Uri.AbsoluteUri);
- }
+ // Force a redirect now to prevent the user from logging in while associations
+ // are constantly being cleared.
+ UriBuilder builder = new UriBuilder(Request.Url);
+ builder.Query = null;
+ Response.Redirect(builder.Uri.AbsoluteUri);
+ }
- OpenIdRelyingParty openid = this.createRelyingParty();
- var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (response != null) {
- switch (response.Status) {
- case AuthenticationStatus.Authenticated:
- // This is where you would look for any OpenID extension responses included
- // in the authentication assertion.
- var claimsResponse = response.GetExtension<ClaimsResponse>();
- State.ProfileFields = claimsResponse;
+ OpenIdRelyingParty openid = this.createRelyingParty();
+ var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ if (response != null) {
+ switch (response.Status) {
+ case AuthenticationStatus.Authenticated:
+ // This is where you would look for any OpenID extension responses included
+ // in the authentication assertion.
+ var claimsResponse = response.GetExtension<ClaimsResponse>();
+ State.ProfileFields = claimsResponse;
- // Store off the "friendly" username to display -- NOT for username lookup
- State.FriendlyLoginName = response.FriendlyIdentifierForDisplay;
+ // Store off the "friendly" username to display -- NOT for username lookup
+ State.FriendlyLoginName = response.FriendlyIdentifierForDisplay;
- // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
- // with the OpenID Claimed Identifier as their username.
- FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
- break;
- case AuthenticationStatus.Canceled:
- this.loginCanceledLabel.Visible = true;
- break;
- case AuthenticationStatus.Failed:
- this.loginFailedLabel.Visible = true;
- break;
+ // Use FormsAuthentication to tell ASP.NET that the user is now logged in,
+ // with the OpenID Claimed Identifier as their username.
+ FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, false);
+ break;
+ case AuthenticationStatus.Canceled:
+ this.loginCanceledLabel.Visible = true;
+ break;
+ case AuthenticationStatus.Failed:
+ this.loginFailedLabel.Visible = true;
+ break;
- // We don't need to handle SetupRequired because we're not setting
- // IAuthenticationRequest.Mode to immediate mode.
- ////case AuthenticationStatus.SetupRequired:
- //// break;
- }
- }
+ // We don't need to handle SetupRequired because we're not setting
+ // IAuthenticationRequest.Mode to immediate mode.
+ ////case AuthenticationStatus.SetupRequired:
+ //// break;
+ }
+ }
+ }));
}
private OpenIdRelyingParty createRelyingParty() {
diff --git a/samples/OpenIdWebRingSsoProvider/Default.aspx.cs b/samples/OpenIdWebRingSsoProvider/Default.aspx.cs
index a1ffeec..6a930bd 100644
--- a/samples/OpenIdWebRingSsoProvider/Default.aspx.cs
+++ b/samples/OpenIdWebRingSsoProvider/Default.aspx.cs
@@ -10,17 +10,23 @@
using OpenIdWebRingSsoProvider.Code;
public partial class _Default : System.Web.UI.Page {
- protected async void Page_Load(object sender, EventArgs e) {
- // The user may have just completed a login. If they're logged in, see if we can complete the OpenID login.
- if (User.Identity.IsAuthenticated && ProviderEndpoint.PendingAuthenticationRequest != null) {
- await Util.ProcessAuthenticationChallengeAsync(ProviderEndpoint.PendingAuthenticationRequest, Response.ClientDisconnectedToken);
- if (ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated.HasValue) {
- var providerEndpoint = new ProviderEndpoint();
- var responseMessage = await providerEndpoint.PrepareResponseAsync(this.Response.ClientDisconnectedToken);
- await responseMessage.SendAsync(new HttpContextWrapper(this.Context), this.Response.ClientDisconnectedToken);
- this.Context.Response.End();
- }
- }
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ // The user may have just completed a login. If they're logged in, see if we can complete the OpenID login.
+ if (User.Identity.IsAuthenticated && ProviderEndpoint.PendingAuthenticationRequest != null) {
+ await
+ Util.ProcessAuthenticationChallengeAsync(
+ ProviderEndpoint.PendingAuthenticationRequest, Response.ClientDisconnectedToken);
+ if (ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated.HasValue) {
+ var providerEndpoint = new ProviderEndpoint();
+ var responseMessage = await providerEndpoint.PrepareResponseAsync(this.Response.ClientDisconnectedToken);
+ await responseMessage.SendAsync(new HttpContextWrapper(this.Context), this.Response.ClientDisconnectedToken);
+ this.Context.Response.End();
+ }
+ }
+ }));
}
}
}
diff --git a/samples/OpenIdWebRingSsoProvider/Login.aspx.cs b/samples/OpenIdWebRingSsoProvider/Login.aspx.cs
index c734ba9..10e5aad 100644
--- a/samples/OpenIdWebRingSsoProvider/Login.aspx.cs
+++ b/samples/OpenIdWebRingSsoProvider/Login.aspx.cs
@@ -35,15 +35,19 @@
}
}
- protected async void cancelButton_Click(object sender, EventArgs e) {
- var req = ProviderEndpoint.PendingAuthenticationRequest;
- if (req != null) {
- req.IsAuthenticated = false;
- var providerEndpoint = new ProviderEndpoint();
- var response = await providerEndpoint.PrepareResponseAsync(Response.ClientDisconnectedToken);
- await response.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
- this.Context.Response.End();
- }
+ protected void cancelButton_Click(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ var req = ProviderEndpoint.PendingAuthenticationRequest;
+ if (req != null) {
+ req.IsAuthenticated = false;
+ var providerEndpoint = new ProviderEndpoint();
+ var response = await providerEndpoint.PrepareResponseAsync(Response.ClientDisconnectedToken);
+ await response.SendAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
+ this.Context.Response.End();
+ }
+ }));
}
}
} \ No newline at end of file
diff --git a/samples/OpenIdWebRingSsoProvider/Server.aspx.cs b/samples/OpenIdWebRingSsoProvider/Server.aspx.cs
index 328f85d..805e38f 100644
--- a/samples/OpenIdWebRingSsoProvider/Server.aspx.cs
+++ b/samples/OpenIdWebRingSsoProvider/Server.aspx.cs
@@ -12,8 +12,12 @@
protected void Page_Load(object sender, EventArgs e) {
}
- protected async void providerEndpoint1_AuthenticationChallenge(object sender, AuthenticationChallengeEventArgs e) {
- await Util.ProcessAuthenticationChallengeAsync(e.Request, Response.ClientDisconnectedToken);
+ protected void providerEndpoint1_AuthenticationChallenge(object sender, AuthenticationChallengeEventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ await Util.ProcessAuthenticationChallengeAsync(e.Request, ct);
+ }));
}
}
}
diff --git a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs
index 9705bfd..d1b1413 100644
--- a/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs
+++ b/samples/OpenIdWebRingSsoRelyingParty/Login.aspx.cs
@@ -21,73 +21,78 @@
relyingParty.EndpointFilter = ep => ep.Uri.AbsoluteUri == ConfigurationManager.AppSettings["SsoProviderOPEndpoint"];
}
- protected async void Page_Load(object sender, EventArgs e) {
- UriBuilder returnToBuilder = new UriBuilder(Request.Url);
- returnToBuilder.Path = "/login.aspx";
- returnToBuilder.Query = null;
- returnToBuilder.Fragment = null;
- Uri returnTo = returnToBuilder.Uri;
- returnToBuilder.Path = "/";
- Realm realm = returnToBuilder.Uri;
+ protected void Page_Load(object sender, EventArgs e) {
+ this.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ UriBuilder returnToBuilder = new UriBuilder(Request.Url);
+ returnToBuilder.Path = "/login.aspx";
+ returnToBuilder.Query = null;
+ returnToBuilder.Fragment = null;
+ Uri returnTo = returnToBuilder.Uri;
+ returnToBuilder.Path = "/";
+ Realm realm = returnToBuilder.Uri;
- var response = await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
- if (response == null) {
- if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) {
- // The user must have been directed here because he has insufficient
- // permissions to access something.
- this.MultiView1.ActiveViewIndex = 1;
- } else {
- // Because this is a sample of a controlled SSO environment,
- // we don't ask the user which Provider to use... we just send
- // them straight off to the one Provider we trust.
- var request = await relyingParty.CreateRequestAsync(
- ConfigurationManager.AppSettings["SsoProviderOPIdentifier"],
- realm,
- returnTo,
- Response.ClientDisconnectedToken);
- var fetchRequest = new FetchRequest();
- fetchRequest.Attributes.AddOptional(RolesAttribute);
- request.AddExtension(fetchRequest);
- await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
- }
- } else {
- switch (response.Status) {
- case AuthenticationStatus.Canceled:
- this.errorLabel.Text = "Login canceled.";
- break;
- case AuthenticationStatus.Failed:
- this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message);
- break;
- case AuthenticationStatus.Authenticated:
- IList<string> roles = null;
- var fetchResponse = response.GetExtension<FetchResponse>();
- if (fetchResponse != null) {
- if (fetchResponse.Attributes.Contains(RolesAttribute)) {
- roles = fetchResponse.Attributes[RolesAttribute].Values;
+ var response =
+ await relyingParty.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
+ if (response == null) {
+ if (Request.QueryString["ReturnUrl"] != null && User.Identity.IsAuthenticated) {
+ // The user must have been directed here because he has insufficient
+ // permissions to access something.
+ this.MultiView1.ActiveViewIndex = 1;
+ } else {
+ // Because this is a sample of a controlled SSO environment,
+ // we don't ask the user which Provider to use... we just send
+ // them straight off to the one Provider we trust.
+ var request =
+ await
+ relyingParty.CreateRequestAsync(
+ ConfigurationManager.AppSettings["SsoProviderOPIdentifier"], realm, returnTo, Response.ClientDisconnectedToken);
+ var fetchRequest = new FetchRequest();
+ fetchRequest.Attributes.AddOptional(RolesAttribute);
+ request.AddExtension(fetchRequest);
+ await request.RedirectToProviderAsync(new HttpContextWrapper(Context), Response.ClientDisconnectedToken);
}
- }
- if (roles == null) {
- roles = new List<string>(0);
- }
+ } else {
+ switch (response.Status) {
+ case AuthenticationStatus.Canceled:
+ this.errorLabel.Text = "Login canceled.";
+ break;
+ case AuthenticationStatus.Failed:
+ this.errorLabel.Text = HttpUtility.HtmlEncode(response.Exception.Message);
+ break;
+ case AuthenticationStatus.Authenticated:
+ IList<string> roles = null;
+ var fetchResponse = response.GetExtension<FetchResponse>();
+ if (fetchResponse != null) {
+ if (fetchResponse.Attributes.Contains(RolesAttribute)) {
+ roles = fetchResponse.Attributes[RolesAttribute].Values;
+ }
+ }
+ if (roles == null) {
+ roles = new List<string>(0);
+ }
- // Apply the roles to this auth ticket
- const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file
- var ticket = new FormsAuthenticationTicket(
- 2,
- response.ClaimedIdentifier,
- DateTime.Now,
- DateTime.Now.AddMinutes(TimeoutInMinutes),
- false, // non-persistent, since login is automatic and we wanted updated roles
- string.Join(";", roles.ToArray()));
+ // Apply the roles to this auth ticket
+ const int TimeoutInMinutes = 100; // TODO: look up the right value from the web.config file
+ var ticket = new FormsAuthenticationTicket(
+ 2,
+ response.ClaimedIdentifier,
+ DateTime.Now,
+ DateTime.Now.AddMinutes(TimeoutInMinutes),
+ false,
+ // non-persistent, since login is automatic and we wanted updated roles
+ string.Join(";", roles.ToArray()));
- HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
- Response.SetCookie(cookie);
- Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
- break;
- default:
- break;
- }
- }
+ HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
+ Response.SetCookie(cookie);
+ Response.Redirect(Request.QueryString["ReturnUrl"] ?? FormsAuthentication.DefaultUrl);
+ break;
+ default:
+ break;
+ }
+ }
+ }));
}
protected void retryButton_Click(object sender, EventArgs e) {
diff --git a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs
index f61f824..2f0a65c 100644
--- a/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs
+++ b/src/DotNetOpenAuth.OpenId.RelyingParty.UI/OpenId/RelyingParty/OpenIdLogin.cs
@@ -934,21 +934,26 @@ idselector_input_id = '" + this.ClientID + @"';
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
- private async void LoginButton_Click(object sender, EventArgs e) {
- if (!this.Page.IsValid) {
- return;
- }
-
- var authenticationRequests = await this.CreateRequestsAsync(CancellationToken.None);
- IAuthenticationRequest request = authenticationRequests.FirstOrDefault();
- if (request != null) {
- await this.LogOnAsync(request, CancellationToken.None);
- } else {
- if (!string.IsNullOrEmpty(this.FailedMessageText)) {
- this.errorLabel.Text = string.Format(CultureInfo.CurrentCulture, this.FailedMessageText, OpenIdStrings.OpenIdEndpointNotFound);
- this.errorLabel.Visible = true;
- }
- }
+ private void LoginButton_Click(object sender, EventArgs e) {
+ this.Page.RegisterAsyncTask(
+ new PageAsyncTask(
+ async ct => {
+ if (!this.Page.IsValid) {
+ return;
+ }
+
+ var authenticationRequests = await this.CreateRequestsAsync(CancellationToken.None);
+ IAuthenticationRequest request = authenticationRequests.FirstOrDefault();
+ if (request != null) {
+ await this.LogOnAsync(request, CancellationToken.None);
+ } else {
+ if (!string.IsNullOrEmpty(this.FailedMessageText)) {
+ this.errorLabel.Text = string.Format(
+ CultureInfo.CurrentCulture, this.FailedMessageText, OpenIdStrings.OpenIdEndpointNotFound);
+ this.errorLabel.Visible = true;
+ }
+ }
+ }));
}
/// <summary>