Added the OpenIdAjaxTextBox control.
[dotnetoauth.git] / src / DotNetOpenAuth / OpenId / RelyingParty / OpenIdTextBox.cs
blob25088ab76e3d86dcfd8ef03efb10ec866cace057
1 //-----------------------------------------------------------------------
2 // <copyright file="OpenIdTextBox.cs" company="Andrew Arnott">
3 // Copyright (c) Andrew Arnott. All rights reserved.
4 // </copyright>
5 //-----------------------------------------------------------------------
7 [assembly: System.Web.UI.WebResource(DotNetOpenAuth.OpenId.RelyingParty.OpenIdTextBox.EmbeddedLogoResourceName, "image/gif")]
9 #pragma warning disable 0809 // marking inherited, unsupported properties as obsolete to discourage their use
11 namespace DotNetOpenAuth.OpenId.RelyingParty {
12 using System;
13 using System.Collections.Generic;
14 using System.Collections.Specialized;
15 using System.ComponentModel;
16 using System.Diagnostics;
17 using System.Diagnostics.CodeAnalysis;
18 using System.Globalization;
19 using System.Net;
20 using System.Text.RegularExpressions;
21 using System.Web;
22 using System.Web.Security;
23 using System.Web.UI;
24 using System.Web.UI.WebControls;
25 using DotNetOpenAuth.Configuration;
26 using DotNetOpenAuth.Messaging;
27 using DotNetOpenAuth.OpenId.Extensions.SimpleRegistration;
29 /// <summary>
30 /// An ASP.NET control that provides a minimal text box that is OpenID-aware.
31 /// </summary>
32 /// <remarks>
33 /// This control offers greater UI flexibility than the <see cref="OpenIdLogin"/>
34 /// control, but requires more work to be done by the hosting web site to
35 /// assemble a complete login experience.
36 /// </remarks>
37 [DefaultProperty("Text"), ValidationProperty("Text")]
38 [ToolboxData("<{0}:OpenIdTextBox runat=\"server\" />")]
39 public class OpenIdTextBox : CompositeControl, IEditableTextControl, ITextControl {
40 /// <summary>
41 /// The name of the manifest stream containing the
42 /// OpenID logo that is placed inside the text box.
43 /// </summary>
44 internal const string EmbeddedLogoResourceName = Util.DefaultNamespace + ".OpenId.RelyingParty.openid_login.gif";
46 /// <summary>
47 /// Default value for <see cref="TabIndex"/> property.
48 /// </summary>
49 protected const short TabIndexDefault = 0;
51 /// <summary>
52 /// Default value of <see cref="UsePersistentCookie"/>.
53 /// </summary>
54 protected const bool UsePersistentCookieDefault = false;
56 #region Property category constants
58 /// <summary>
59 /// The "Appearance" category for properties.
60 /// </summary>
61 private const string AppearanceCategory = "Appearance";
63 /// <summary>
64 /// The "Simple Registration" category for properties.
65 /// </summary>
66 private const string ProfileCategory = "Simple Registration";
68 /// <summary>
69 /// The "Behavior" category for properties.
70 /// </summary>
71 private const string BehaviorCategory = "Behavior";
73 #endregion
75 #region Property viewstate keys
77 /// <summary>
78 /// The viewstate key to use for the <see cref="RequestEmail"/> property.
79 /// </summary>
80 private const string RequestEmailViewStateKey = "RequestEmail";
82 /// <summary>
83 /// The viewstate key to use for the <see cref="RequestNickname"/> property.
84 /// </summary>
85 private const string RequestNicknameViewStateKey = "RequestNickname";
87 /// <summary>
88 /// The viewstate key to use for the <see cref="RequestPostalCode"/> property.
89 /// </summary>
90 private const string RequestPostalCodeViewStateKey = "RequestPostalCode";
92 /// <summary>
93 /// The viewstate key to use for the <see cref="RequestCountry"/> property.
94 /// </summary>
95 private const string RequestCountryViewStateKey = "RequestCountry";
97 /// <summary>
98 /// The viewstate key to use for the <see cref="RequireSsl"/> property.
99 /// </summary>
100 private const string RequireSslViewStateKey = "RequireSsl";
102 /// <summary>
103 /// The viewstate key to use for the <see cref="RequestLanguage"/> property.
104 /// </summary>
105 private const string RequestLanguageViewStateKey = "RequestLanguage";
107 /// <summary>
108 /// The viewstate key to use for the <see cref="RequestTimeZone"/> property.
109 /// </summary>
110 private const string RequestTimeZoneViewStateKey = "RequestTimeZone";
112 /// <summary>
113 /// The viewstate key to use for the <see cref="EnableRequestProfile"/> property.
114 /// </summary>
115 private const string EnableRequestProfileViewStateKey = "EnableRequestProfile";
117 /// <summary>
118 /// The viewstate key to use for the <see cref="PolicyUrl"/> property.
119 /// </summary>
120 private const string PolicyUrlViewStateKey = "PolicyUrl";
122 /// <summary>
123 /// The viewstate key to use for the <see cref="RequestFullName"/> property.
124 /// </summary>
125 private const string RequestFullNameViewStateKey = "RequestFullName";
127 /// <summary>
128 /// The viewstate key to use for the <see cref="PresetBorder"/> property.
129 /// </summary>
130 private const string PresetBorderViewStateKey = "PresetBorder";
132 /// <summary>
133 /// The viewstate key to use for the <see cref="ShowLogo"/> property.
134 /// </summary>
135 private const string ShowLogoViewStateKey = "ShowLogo";
137 /// <summary>
138 /// The viewstate key to use for the <see cref="UsePersistentCookie"/> property.
139 /// </summary>
140 private const string UsePersistentCookieViewStateKey = "UsePersistentCookie";
142 /// <summary>
143 /// The viewstate key to use for the <see cref="RequestGender"/> property.
144 /// </summary>
145 private const string RequestGenderViewStateKey = "RequestGender";
147 /// <summary>
148 /// The viewstate key to use for the <see cref="ReturnToUrl"/> property.
149 /// </summary>
150 private const string ReturnToUrlViewStateKey = "ReturnToUrl";
152 /// <summary>
153 /// The viewstate key to use for the <see cref="Stateless"/> property.
154 /// </summary>
155 private const string StatelessViewStateKey = "Stateless";
157 /// <summary>
158 /// The viewstate key to use for the <see cref="ImmediateMode"/> property.
159 /// </summary>
160 private const string ImmediateModeViewStateKey = "ImmediateMode";
162 /// <summary>
163 /// The viewstate key to use for the <see cref="RequestBirthDate"/> property.
164 /// </summary>
165 private const string RequestBirthDateViewStateKey = "RequestBirthDate";
167 /// <summary>
168 /// The viewstate key to use for the <see cref="RealmUrl"/> property.
169 /// </summary>
170 private const string RealmUrlViewStateKey = "RealmUrl";
172 #endregion
174 #region Property defaults
176 /// <summary>
177 /// The default value for the <see cref="Columns"/> property.
178 /// </summary>
179 private const int ColumnsDefault = 40;
181 /// <summary>
182 /// The default value for the <see cref="MaxLength"/> property.
183 /// </summary>
184 private const int MaxLengthDefault = 40;
186 /// <summary>
187 /// The default value for the <see cref="EnableRequestProfile"/> property.
188 /// </summary>
189 private const bool EnableRequestProfileDefault = true;
191 /// <summary>
192 /// The default value for the <see cref="RequireSsl"/> property.
193 /// </summary>
194 private const bool RequireSslDefault = false;
196 /// <summary>
197 /// The default value for the <see cref="ImmediateMode"/> property.
198 /// </summary>
199 private const bool ImmediateModeDefault = false;
201 /// <summary>
202 /// The default value for the <see cref="Stateless"/> property.
203 /// </summary>
204 private const bool StatelessDefault = false;
206 /// <summary>
207 /// The default value for the <see cref="ShowLogo"/> property.
208 /// </summary>
209 private const bool ShowLogoDefault = true;
211 /// <summary>
212 /// The default value for the <see cref="PresetBorder"/> property.
213 /// </summary>
214 private const bool PresetBorderDefault = true;
216 /// <summary>
217 /// The default value for the <see cref="PolicyUrl"/> property.
218 /// </summary>
219 private const string PolicyUrlDefault = "";
221 /// <summary>
222 /// The default value for the <see cref="CssClass"/> property.
223 /// </summary>
224 private const string CssClassDefault = "openid";
226 /// <summary>
227 /// The default value for the <see cref="ReturnToUrl"/> property.
228 /// </summary>
229 private const string ReturnToUrlDefault = "";
231 /// <summary>
232 /// The default value for the <see cref="Text"/> property.
233 /// </summary>
234 private const string TextDefault = "";
236 /// <summary>
237 /// The default value for the <see cref="RealmUrl"/> property.
238 /// </summary>
239 private const string RealmUrlDefault = "~/";
241 /// <summary>
242 /// The default value for the <see cref="RequestEmail"/> property.
243 /// </summary>
244 private const DemandLevel RequestEmailDefault = DemandLevel.NoRequest;
246 /// <summary>
247 /// The default value for the <see cref="RequestPostalCode"/> property.
248 /// </summary>
249 private const DemandLevel RequestPostalCodeDefault = DemandLevel.NoRequest;
251 /// <summary>
252 /// The default value for the <see cref="RequestCountry"/> property.
253 /// </summary>
254 private const DemandLevel RequestCountryDefault = DemandLevel.NoRequest;
256 /// <summary>
257 /// The default value for the <see cref="RequestLanguage"/> property.
258 /// </summary>
259 private const DemandLevel RequestLanguageDefault = DemandLevel.NoRequest;
261 /// <summary>
262 /// The default value for the <see cref="RequestTimeZone"/> property.
263 /// </summary>
264 private const DemandLevel RequestTimeZoneDefault = DemandLevel.NoRequest;
266 /// <summary>
267 /// The default value for the <see cref="RequestNickname"/> property.
268 /// </summary>
269 private const DemandLevel RequestNicknameDefault = DemandLevel.NoRequest;
271 /// <summary>
272 /// The default value for the <see cref="RequestFullName"/> property.
273 /// </summary>
274 private const DemandLevel RequestFullNameDefault = DemandLevel.NoRequest;
276 /// <summary>
277 /// The default value for the <see cref="RequestBirthDate"/> property.
278 /// </summary>
279 private const DemandLevel RequestBirthDateDefault = DemandLevel.NoRequest;
281 /// <summary>
282 /// The default value for the <see cref="RequestGender"/> property.
283 /// </summary>
284 private const DemandLevel RequestGenderDefault = DemandLevel.NoRequest;
286 #endregion
288 /// <summary>
289 /// The callback parameter for use with persisting the <see cref="UsePersistentCookie"/> property.
290 /// </summary>
291 private const string UsePersistentCookieCallbackKey = "OpenIdTextBox_UsePersistentCookie";
293 /// <summary>
294 /// The text in the text box before the text box is instantiated.
295 /// </summary>
296 private string text = TextDefault;
298 /// <summary>
299 /// The text box itself.
300 /// </summary>
301 private TextBox wrappedTextBox;
303 /// <summary>
304 /// Initializes a new instance of the <see cref="OpenIdTextBox"/> class.
305 /// </summary>
306 public OpenIdTextBox() {
307 this.InitializeControls();
310 /// <summary>
311 /// Fired upon completion of a successful login.
312 /// </summary>
313 [Description("Fired upon completion of a successful login.")]
314 public event EventHandler<OpenIdEventArgs> LoggedIn;
316 /// <summary>
317 /// Fired when a login attempt fails.
318 /// </summary>
319 [Description("Fired when a login attempt fails.")]
320 public event EventHandler<OpenIdEventArgs> Failed;
322 /// <summary>
323 /// Fired when an authentication attempt is canceled at the OpenID Provider.
324 /// </summary>
325 [Description("Fired when an authentication attempt is canceled at the OpenID Provider.")]
326 public event EventHandler<OpenIdEventArgs> Canceled;
328 /// <summary>
329 /// Fired when an Immediate authentication attempt fails, and the Provider suggests using non-Immediate mode.
330 /// </summary>
331 [Description("Fired when an Immediate authentication attempt fails, and the Provider suggests using non-Immediate mode.")]
332 public event EventHandler<OpenIdEventArgs> SetupRequired;
334 #region IEditableTextControl Members
336 /// <summary>
337 /// Occurs when the content of the text changes between posts to the server.
338 /// </summary>
339 public event EventHandler TextChanged {
340 add { this.WrappedTextBox.TextChanged += value; }
341 remove { this.WrappedTextBox.TextChanged -= value; }
344 #endregion
346 #region Properties
348 /// <summary>
349 /// Gets or sets the content of the text box.
350 /// </summary>
351 [Bindable(true), DefaultValue(""), Category(AppearanceCategory)]
352 [Description("The content of the text box.")]
353 public string Text {
354 get {
355 return this.WrappedTextBox != null ? this.WrappedTextBox.Text : this.text;
358 set {
359 this.text = value;
360 if (this.WrappedTextBox != null) {
361 this.WrappedTextBox.Text = value;
366 /// <summary>
367 /// Gets or sets the OpenID <see cref="Realm"/> of the relying party web site.
368 /// </summary>
369 [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Uri", Justification = "Using Uri.ctor for validation.")]
370 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
371 [Bindable(true), DefaultValue(RealmUrlDefault), Category(BehaviorCategory)]
372 [Description("The OpenID Realm of the relying party web site.")]
373 public string RealmUrl {
374 get {
375 return (string)(ViewState[RealmUrlViewStateKey] ?? RealmUrlDefault);
378 set {
379 if (Page != null && !DesignMode) {
380 // Validate new value by trying to construct a Realm object based on it.
381 new Realm(OpenIdUtilities.GetResolvedRealm(Page, value)); // throws an exception on failure.
382 } else {
383 // We can't fully test it, but it should start with either ~/ or a protocol.
384 if (Regex.IsMatch(value, @"^https?://")) {
385 new Uri(value.Replace("*.", string.Empty)); // make sure it's fully-qualified, but ignore wildcards
386 } else if (value.StartsWith("~/", StringComparison.Ordinal)) {
387 // this is valid too
388 } else {
389 throw new UriFormatException();
392 ViewState[RealmUrlViewStateKey] = value;
396 /// <summary>
397 /// Gets or sets the OpenID ReturnTo of the relying party web site.
398 /// </summary>
399 [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Uri", Justification = "Using Uri.ctor for validation.")]
400 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
401 [Bindable(true), DefaultValue(ReturnToUrlDefault), Category(BehaviorCategory)]
402 [Description("The OpenID ReturnTo of the relying party web site.")]
403 public string ReturnToUrl {
404 get {
405 return (string)(ViewState[ReturnToUrlViewStateKey] ?? ReturnToUrlDefault);
408 set {
409 if (Page != null && !DesignMode) {
410 // Validate new value by trying to construct a Uri based on it.
411 new Uri(MessagingUtilities.GetRequestUrlFromContext(), Page.ResolveUrl(value)); // throws an exception on failure.
412 } else {
413 // We can't fully test it, but it should start with either ~/ or a protocol.
414 if (Regex.IsMatch(value, @"^https?://")) {
415 new Uri(value); // make sure it's fully-qualified, but ignore wildcards
416 } else if (value.StartsWith("~/", StringComparison.Ordinal)) {
417 // this is valid too
418 } else {
419 throw new UriFormatException();
423 ViewState[ReturnToUrlViewStateKey] = value;
427 /// <summary>
428 /// Gets or sets a value indicating whether to use immediate mode in the
429 /// OpenID protocol.
430 /// </summary>
431 /// <value>
432 /// True if a Provider should reply immediately to the authentication request
433 /// without interacting with the user. False if the Provider can take time
434 /// to authenticate the user in order to complete an authentication attempt.
435 /// </value>
436 /// <remarks>
437 /// Setting this to true is sometimes useful in AJAX scenarios. Setting this to
438 /// true can cause failed authentications when the user truly controls an
439 /// Identifier, but must complete an authentication step with the Provider before
440 /// the Provider will approve the login from this relying party.
441 /// </remarks>
442 [Bindable(true), DefaultValue(ImmediateModeDefault), Category(BehaviorCategory)]
443 [Description("Whether the Provider should respond immediately to an authentication attempt without interacting with the user.")]
444 public bool ImmediateMode {
445 get { return (bool)(ViewState[ImmediateModeViewStateKey] ?? ImmediateModeDefault); }
446 set { ViewState[ImmediateModeViewStateKey] = value; }
449 /// <summary>
450 /// Gets or sets a value indicating whether stateless mode is used.
451 /// </summary>
452 [Bindable(true), DefaultValue(StatelessDefault), Category(BehaviorCategory)]
453 [Description("Controls whether stateless mode is used.")]
454 public bool Stateless {
455 get { return (bool)(ViewState[StatelessViewStateKey] ?? StatelessDefault); }
456 set { ViewState[StatelessViewStateKey] = value; }
459 /// <summary>
460 /// Gets or sets the CSS class assigned to the text box.
461 /// </summary>
462 [Bindable(true), DefaultValue(CssClassDefault), Category(AppearanceCategory)]
463 [Description("The CSS class assigned to the text box.")]
464 public override string CssClass {
465 get { return this.WrappedTextBox.CssClass; }
466 set { this.WrappedTextBox.CssClass = value; }
469 /// <summary>
470 /// Gets or sets a value indicating whether to show the OpenID logo in the text box.
471 /// </summary>
472 [Bindable(true), DefaultValue(ShowLogoDefault), Category(AppearanceCategory)]
473 [Description("The visibility of the OpenID logo in the text box.")]
474 public bool ShowLogo {
475 get { return (bool)(this.ViewState[ShowLogoViewStateKey] ?? ShowLogoDefault); }
476 set { this.ViewState[ShowLogoViewStateKey] = value; }
479 /// <summary>
480 /// Gets or sets a value indicating whether to use inline styling to force a solid gray border.
481 /// </summary>
482 [Bindable(true), DefaultValue(PresetBorderDefault), Category(AppearanceCategory)]
483 [Description("Whether to use inline styling to force a solid gray border.")]
484 public bool PresetBorder {
485 get { return (bool)(this.ViewState[PresetBorderViewStateKey] ?? PresetBorderDefault); }
486 set { this.ViewState[PresetBorderViewStateKey] = value; }
489 /// <summary>
490 /// Gets or sets a value indicating whether to send a persistent cookie upon successful
491 /// login so the user does not have to log in upon returning to this site.
492 /// </summary>
493 [Bindable(true), DefaultValue(UsePersistentCookieDefault), Category(BehaviorCategory)]
494 [Description("Whether to send a persistent cookie upon successful " +
495 "login so the user does not have to log in upon returning to this site.")]
496 public virtual bool UsePersistentCookie {
497 get { return (bool)(this.ViewState[UsePersistentCookieViewStateKey] ?? UsePersistentCookieDefault); }
498 set { this.ViewState[UsePersistentCookieViewStateKey] = value; }
501 /// <summary>
502 /// Gets or sets the width of the text box in characters.
503 /// </summary>
504 [Bindable(true), DefaultValue(ColumnsDefault), Category(AppearanceCategory)]
505 [Description("The width of the text box in characters.")]
506 public int Columns {
507 get { return this.WrappedTextBox.Columns; }
508 set { this.WrappedTextBox.Columns = value; }
511 /// <summary>
512 /// Gets or sets the maximum number of characters the browser should allow
513 /// </summary>
514 [Bindable(true), DefaultValue(MaxLengthDefault), Category(AppearanceCategory)]
515 [Description("The maximum number of characters the browser should allow.")]
516 public int MaxLength {
517 get { return this.WrappedTextBox.MaxLength; }
518 set { this.WrappedTextBox.MaxLength = value; }
521 /// <summary>
522 /// Gets or sets the tab index of the Web server control.
523 /// </summary>
524 /// <value></value>
525 /// <returns>
526 /// The tab index of the Web server control. The default is 0, which indicates that this property is not set.
527 /// </returns>
528 /// <exception cref="T:System.ArgumentOutOfRangeException">
529 /// The specified tab index is not between -32768 and 32767.
530 /// </exception>
531 [Bindable(true), DefaultValue(TabIndexDefault), Category(BehaviorCategory)]
532 [Description("The tab index of the text box control.")]
533 public override short TabIndex {
534 get { return this.WrappedTextBox.TabIndex; }
535 set { this.WrappedTextBox.TabIndex = value; }
538 /// <summary>
539 /// Gets or sets your level of interest in receiving the user's nickname from the Provider.
540 /// </summary>
541 [Bindable(true), DefaultValue(RequestNicknameDefault), Category(ProfileCategory)]
542 [Description("Your level of interest in receiving the user's nickname from the Provider.")]
543 public DemandLevel RequestNickname {
544 get { return (DemandLevel)(ViewState[RequestNicknameViewStateKey] ?? RequestNicknameDefault); }
545 set { ViewState[RequestNicknameViewStateKey] = value; }
548 /// <summary>
549 /// Gets or sets your level of interest in receiving the user's email address from the Provider.
550 /// </summary>
551 [Bindable(true), DefaultValue(RequestEmailDefault), Category(ProfileCategory)]
552 [Description("Your level of interest in receiving the user's email address from the Provider.")]
553 public DemandLevel RequestEmail {
554 get { return (DemandLevel)(ViewState[RequestEmailViewStateKey] ?? RequestEmailDefault); }
555 set { ViewState[RequestEmailViewStateKey] = value; }
558 /// <summary>
559 /// Gets or sets your level of interest in receiving the user's full name from the Provider.
560 /// </summary>
561 [Bindable(true), DefaultValue(RequestFullNameDefault), Category(ProfileCategory)]
562 [Description("Your level of interest in receiving the user's full name from the Provider")]
563 public DemandLevel RequestFullName {
564 get { return (DemandLevel)(ViewState[RequestFullNameViewStateKey] ?? RequestFullNameDefault); }
565 set { ViewState[RequestFullNameViewStateKey] = value; }
568 /// <summary>
569 /// Gets or sets your level of interest in receiving the user's birthdate from the Provider.
570 /// </summary>
571 [Bindable(true), DefaultValue(RequestBirthDateDefault), Category(ProfileCategory)]
572 [Description("Your level of interest in receiving the user's birthdate from the Provider.")]
573 public DemandLevel RequestBirthDate {
574 get { return (DemandLevel)(ViewState[RequestBirthDateViewStateKey] ?? RequestBirthDateDefault); }
575 set { ViewState[RequestBirthDateViewStateKey] = value; }
578 /// <summary>
579 /// Gets or sets your level of interest in receiving the user's gender from the Provider.
580 /// </summary>
581 [Bindable(true), DefaultValue(RequestGenderDefault), Category(ProfileCategory)]
582 [Description("Your level of interest in receiving the user's gender from the Provider.")]
583 public DemandLevel RequestGender {
584 get { return (DemandLevel)(ViewState[RequestGenderViewStateKey] ?? RequestGenderDefault); }
585 set { ViewState[RequestGenderViewStateKey] = value; }
588 /// <summary>
589 /// Gets or sets your level of interest in receiving the user's postal code from the Provider.
590 /// </summary>
591 [Bindable(true), DefaultValue(RequestPostalCodeDefault), Category(ProfileCategory)]
592 [Description("Your level of interest in receiving the user's postal code from the Provider.")]
593 public DemandLevel RequestPostalCode {
594 get { return (DemandLevel)(ViewState[RequestPostalCodeViewStateKey] ?? RequestPostalCodeDefault); }
595 set { ViewState[RequestPostalCodeViewStateKey] = value; }
598 /// <summary>
599 /// Gets or sets your level of interest in receiving the user's country from the Provider.
600 /// </summary>
601 [Bindable(true)]
602 [Category(ProfileCategory)]
603 [DefaultValue(RequestCountryDefault)]
604 [Description("Your level of interest in receiving the user's country from the Provider.")]
605 public DemandLevel RequestCountry {
606 get { return (DemandLevel)(ViewState[RequestCountryViewStateKey] ?? RequestCountryDefault); }
607 set { ViewState[RequestCountryViewStateKey] = value; }
610 /// <summary>
611 /// Gets or sets your level of interest in receiving the user's preferred language from the Provider.
612 /// </summary>
613 [Bindable(true), DefaultValue(RequestLanguageDefault), Category(ProfileCategory)]
614 [Description("Your level of interest in receiving the user's preferred language from the Provider.")]
615 public DemandLevel RequestLanguage {
616 get { return (DemandLevel)(ViewState[RequestLanguageViewStateKey] ?? RequestLanguageDefault); }
617 set { ViewState[RequestLanguageViewStateKey] = value; }
620 /// <summary>
621 /// Gets or sets your level of interest in receiving the user's time zone from the Provider.
622 /// </summary>
623 [Bindable(true), DefaultValue(RequestTimeZoneDefault), Category(ProfileCategory)]
624 [Description("Your level of interest in receiving the user's time zone from the Provider.")]
625 public DemandLevel RequestTimeZone {
626 get { return (DemandLevel)(ViewState[RequestTimeZoneViewStateKey] ?? RequestTimeZoneDefault); }
627 set { ViewState[RequestTimeZoneViewStateKey] = value; }
630 /// <summary>
631 /// Gets or sets the URL to your privacy policy page that describes how
632 /// claims will be used and/or shared.
633 /// </summary>
634 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
635 [Bindable(true), DefaultValue(PolicyUrlDefault), Category(ProfileCategory)]
636 [Description("The URL to your privacy policy page that describes how claims will be used and/or shared.")]
637 public string PolicyUrl {
638 get {
639 return (string)ViewState[PolicyUrlViewStateKey] ?? PolicyUrlDefault;
642 set {
643 UriUtil.ValidateResolvableUrl(Page, DesignMode, value);
644 ViewState[PolicyUrlViewStateKey] = value;
648 /// <summary>
649 /// Gets or sets a value indicating whether to use OpenID extensions
650 /// to retrieve profile data of the authenticating user.
651 /// </summary>
652 [Bindable(true), DefaultValue(EnableRequestProfileDefault), Category(ProfileCategory)]
653 [Description("Turns the entire Simple Registration extension on or off.")]
654 public bool EnableRequestProfile {
655 get { return (bool)(ViewState[EnableRequestProfileViewStateKey] ?? EnableRequestProfileDefault); }
656 set { ViewState[EnableRequestProfileViewStateKey] = value; }
659 /// <summary>
660 /// Gets or sets a value indicating whether to enforce on high security mode,
661 /// which requires the full authentication pipeline to be protected by SSL.
662 /// </summary>
663 [Bindable(true), DefaultValue(RequireSslDefault), Category(BehaviorCategory)]
664 [Description("Turns on high security mode, requiring the full authentication pipeline to be protected by SSL.")]
665 public bool RequireSsl {
666 get { return (bool)(ViewState[RequireSslViewStateKey] ?? RequireSslDefault); }
667 set { ViewState[RequireSslViewStateKey] = value; }
670 /// <summary>
671 /// Gets or sets the type of the custom application store to use, or <c>null</c> to use the default.
672 /// </summary>
673 /// <remarks>
674 /// If set, this property must be set in each Page Load event
675 /// as it is not persisted across postbacks.
676 /// </remarks>
677 public IRelyingPartyApplicationStore CustomApplicationStore { get; set; }
679 #endregion
681 #region Properties to hide
683 /// <summary>
684 /// Gets or sets the foreground color (typically the color of the text) of the Web server control.
685 /// </summary>
686 /// <returns>
687 /// A <see cref="T:System.Drawing.Color"/> that represents the foreground color of the control. The default is <see cref="F:System.Drawing.Color.Empty"/>.
688 /// </returns>
689 [Obsolete, Browsable(false), Bindable(false)]
690 public override System.Drawing.Color ForeColor {
691 get { throw new NotSupportedException(); }
692 set { throw new NotSupportedException(); }
695 /// <summary>
696 /// Gets or sets the background color of the Web server control.
697 /// </summary>
698 /// <returns>
699 /// A <see cref="T:System.Drawing.Color"/> that represents the background color of the control. The default is <see cref="F:System.Drawing.Color.Empty"/>, which indicates that this property is not set.
700 /// </returns>
701 [Obsolete, Browsable(false), Bindable(false)]
702 public override System.Drawing.Color BackColor {
703 get { throw new NotSupportedException(); }
704 set { throw new NotSupportedException(); }
707 /// <summary>
708 /// Gets or sets the border color of the Web control.
709 /// </summary>
710 /// <returns>
711 /// A <see cref="T:System.Drawing.Color"/> that represents the border color of the control. The default is <see cref="F:System.Drawing.Color.Empty"/>, which indicates that this property is not set.
712 /// </returns>
713 [Obsolete, Browsable(false), Bindable(false)]
714 public override System.Drawing.Color BorderColor {
715 get { throw new NotSupportedException(); }
716 set { throw new NotSupportedException(); }
719 /// <summary>
720 /// Gets or sets the border width of the Web server control.
721 /// </summary>
722 /// <returns>
723 /// A <see cref="T:System.Web.UI.WebControls.Unit"/> that represents the border width of a Web server control. The default value is <see cref="F:System.Web.UI.WebControls.Unit.Empty"/>, which indicates that this property is not set.
724 /// </returns>
725 /// <exception cref="T:System.ArgumentException">
726 /// The specified border width is a negative value.
727 /// </exception>
728 [Obsolete, Browsable(false), Bindable(false)]
729 public override Unit BorderWidth {
730 get { return Unit.Empty; }
731 set { throw new NotSupportedException(); }
734 /// <summary>
735 /// Gets or sets the border style of the Web server control.
736 /// </summary>
737 /// <returns>
738 /// One of the <see cref="T:System.Web.UI.WebControls.BorderStyle"/> enumeration values. The default is NotSet.
739 /// </returns>
740 [Obsolete, Browsable(false), Bindable(false)]
741 public override BorderStyle BorderStyle {
742 get { return BorderStyle.None; }
743 set { throw new NotSupportedException(); }
746 /// <summary>
747 /// Gets the font properties associated with the Web server control.
748 /// </summary>
749 /// <returns>
750 /// A <see cref="T:System.Web.UI.WebControls.FontInfo"/> that represents the font properties of the Web server control.
751 /// </returns>
752 [Obsolete, Browsable(false), Bindable(false)]
753 public override FontInfo Font {
754 get { return null; }
757 /// <summary>
758 /// Gets or sets the height of the Web server control.
759 /// </summary>
760 /// <returns>
761 /// A <see cref="T:System.Web.UI.WebControls.Unit"/> that represents the height of the control. The default is <see cref="F:System.Web.UI.WebControls.Unit.Empty"/>.
762 /// </returns>
763 /// <exception cref="T:System.ArgumentException">
764 /// The height was set to a negative value.
765 /// </exception>
766 [Obsolete, Browsable(false), Bindable(false)]
767 public override Unit Height {
768 get { return Unit.Empty; }
769 set { throw new NotSupportedException(); }
772 /// <summary>
773 /// Gets or sets the width of the Web server control.
774 /// </summary>
775 /// <returns>
776 /// A <see cref="T:System.Web.UI.WebControls.Unit"/> that represents the width of the control. The default is <see cref="F:System.Web.UI.WebControls.Unit.Empty"/>.
777 /// </returns>
778 /// <exception cref="T:System.ArgumentException">
779 /// The width of the Web server control was set to a negative value.
780 /// </exception>
781 [Obsolete, Browsable(false), Bindable(false)]
782 public override Unit Width {
783 get { return Unit.Empty; }
784 set { throw new NotSupportedException(); }
787 /// <summary>
788 /// Gets or sets the text displayed when the mouse pointer hovers over the Web server control.
789 /// </summary>
790 /// <returns>
791 /// The text displayed when the mouse pointer hovers over the Web server control. The default is <see cref="F:System.String.Empty"/>.
792 /// </returns>
793 [Obsolete, Browsable(false), Bindable(false)]
794 public override string ToolTip {
795 get { return string.Empty; }
796 set { throw new NotSupportedException(); }
799 /// <summary>
800 /// Gets or sets the skin to apply to the control.
801 /// </summary>
802 /// <returns>
803 /// The name of the skin to apply to the control. The default is <see cref="F:System.String.Empty"/>.
804 /// </returns>
805 /// <exception cref="T:System.ArgumentException">
806 /// The skin specified in the <see cref="P:System.Web.UI.WebControls.WebControl.SkinID"/> property does not exist in the theme.
807 /// </exception>
808 [Obsolete, Browsable(false), Bindable(false)]
809 public override string SkinID {
810 get { return string.Empty; }
811 set { throw new NotSupportedException(); }
814 /// <summary>
815 /// Gets or sets a value indicating whether themes apply to this control.
816 /// </summary>
817 /// <returns>true to use themes; otherwise, false. The default is false.
818 /// </returns>
819 [Obsolete, Browsable(false), Bindable(false)]
820 public override bool EnableTheming {
821 get { return false; }
822 set { throw new NotSupportedException(); }
825 #endregion
827 /// <summary>
828 /// Gets the <see cref="TextBox"/> control that this control wraps.
829 /// </summary>
830 protected TextBox WrappedTextBox {
831 get { return this.wrappedTextBox; }
834 /// <summary>
835 /// Gets or sets a value indicating whether the text box should
836 /// receive input focus when the web page appears.
837 /// </summary>
838 protected bool ShouldBeFocused { get; set; }
840 /// <summary>
841 /// Gets or sets the OpenID authentication request that is about to be sent.
842 /// </summary>
843 protected IAuthenticationRequest Request { get; set; }
845 /// <summary>
846 /// Sets the input focus to start on the text box when the page appears
847 /// in the user's browser.
848 /// </summary>
849 public override void Focus() {
850 if (Controls.Count == 0) {
851 this.ShouldBeFocused = true;
852 } else {
853 this.WrappedTextBox.Focus();
857 /// <summary>
858 /// Constructs the authentication request and returns it.
859 /// </summary>
860 /// <returns>The instantiated authentication request.</returns>
861 /// <remarks>
862 /// <para>This method need not be called before calling the <see cref="LogOn"/> method,
863 /// but is offered in the event that adding extensions to the request is desired.</para>
864 /// <para>The Simple Registration extension arguments are added to the request
865 /// before returning if <see cref="EnableRequestProfile"/> is set to true.</para>
866 /// </remarks>
867 public IAuthenticationRequest CreateRequest() {
868 ErrorUtilities.VerifyOperation(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled);
869 ErrorUtilities.VerifyOperation(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty);
871 try {
872 var consumer = this.CreateRelyingParty();
874 // Resolve the trust root, and swap out the scheme and port if necessary to match the
875 // return_to URL, since this match is required by OpenId, and the consumer app
876 // may be using HTTP at some times and HTTPS at others.
877 UriBuilder realm = OpenIdUtilities.GetResolvedRealm(this.Page, this.RealmUrl);
878 realm.Scheme = Page.Request.Url.Scheme;
879 realm.Port = Page.Request.Url.Port;
881 // Initiate openid request
882 // We use TryParse here to avoid throwing an exception which
883 // might slip through our validator control if it is disabled.
884 Identifier userSuppliedIdentifier;
885 if (Identifier.TryParse(this.Text, out userSuppliedIdentifier)) {
886 Realm typedRealm = new Realm(realm);
887 if (string.IsNullOrEmpty(this.ReturnToUrl)) {
888 this.Request = consumer.CreateRequest(userSuppliedIdentifier, typedRealm);
889 } else {
890 Uri returnTo = new Uri(MessagingUtilities.GetRequestUrlFromContext(), this.ReturnToUrl);
891 this.Request = consumer.CreateRequest(userSuppliedIdentifier, typedRealm, returnTo);
893 this.Request.Mode = this.ImmediateMode ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
894 if (this.EnableRequestProfile) {
895 this.AddProfileArgs(this.Request);
898 // Add state that needs to survive across the redirect.
899 this.Request.AddCallbackArguments(UsePersistentCookieCallbackKey, this.UsePersistentCookie.ToString(CultureInfo.InvariantCulture));
900 } else {
901 Logger.WarnFormat("An invalid identifier was entered ({0}), but not caught by any validation routine.", this.Text);
902 this.Request = null;
904 } catch (ProtocolException ex) {
905 this.OnFailed(new FailedAuthenticationResponse(ex));
908 return this.Request;
911 /// <summary>
912 /// Immediately redirects to the OpenID Provider to verify the Identifier
913 /// provided in the text box.
914 /// </summary>
915 public void LogOn() {
916 if (this.Request == null) {
917 this.CreateRequest(); // sets this.Request
920 if (this.Request != null) {
921 this.Request.RedirectToProvider();
925 /// <summary>
926 /// Creates the text box control.
927 /// </summary>
928 protected override void CreateChildControls() {
929 base.CreateChildControls();
931 this.Controls.Add(this.wrappedTextBox);
932 if (this.ShouldBeFocused) {
933 this.WrappedTextBox.Focus();
937 /// <summary>
938 /// Initializes the text box control.
939 /// </summary>
940 protected virtual void InitializeControls() {
941 this.wrappedTextBox = new TextBox();
942 this.wrappedTextBox.ID = "wrappedTextBox";
943 this.wrappedTextBox.CssClass = CssClassDefault;
944 this.wrappedTextBox.Columns = ColumnsDefault;
945 this.wrappedTextBox.Text = this.text;
946 this.wrappedTextBox.TabIndex = TabIndexDefault;
949 /// <summary>
950 /// Checks for incoming OpenID authentication responses and fires appropriate events.
951 /// </summary>
952 /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
953 protected override void OnLoad(EventArgs e) {
954 base.OnLoad(e);
956 if (!Enabled || Page.IsPostBack) {
957 return;
960 var consumer = this.CreateRelyingParty();
961 var response = consumer.GetResponse();
962 if (response != null) {
963 string persistentString = response.GetCallbackArgument(UsePersistentCookieCallbackKey);
964 bool persistentBool;
965 if (persistentString != null && bool.TryParse(persistentString, out persistentBool)) {
966 this.UsePersistentCookie = persistentBool;
969 switch (response.Status) {
970 case AuthenticationStatus.Canceled:
971 this.OnCanceled(response);
972 break;
973 case AuthenticationStatus.Authenticated:
974 this.OnLoggedIn(response);
975 break;
976 case AuthenticationStatus.SetupRequired:
977 this.OnSetupRequired(response);
978 break;
979 case AuthenticationStatus.Failed:
980 this.OnFailed(response);
981 break;
982 default:
983 throw new InvalidOperationException("Unexpected response status code.");
988 /// <summary>
989 /// Prepares the text box to be rendered.
990 /// </summary>
991 /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
992 protected override void OnPreRender(EventArgs e) {
993 base.OnPreRender(e);
995 if (this.ShowLogo) {
996 string logoUrl = Page.ClientScript.GetWebResourceUrl(
997 typeof(OpenIdTextBox), EmbeddedLogoResourceName);
998 this.WrappedTextBox.Style[HtmlTextWriterStyle.BackgroundImage] = string.Format(
999 CultureInfo.InvariantCulture, "url({0})", HttpUtility.HtmlEncode(logoUrl));
1000 this.WrappedTextBox.Style["background-repeat"] = "no-repeat";
1001 this.WrappedTextBox.Style["background-position"] = "0 50%";
1002 this.WrappedTextBox.Style[HtmlTextWriterStyle.PaddingLeft] = "18px";
1005 if (this.PresetBorder) {
1006 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderStyle] = "solid";
1007 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderWidth] = "1px";
1008 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderColor] = "lightgray";
1012 #region Events
1014 /// <summary>
1015 /// Fires the <see cref="LoggedIn"/> event.
1016 /// </summary>
1017 /// <param name="response">The response.</param>
1018 protected virtual void OnLoggedIn(IAuthenticationResponse response) {
1019 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1020 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Authenticated, "Firing OnLoggedIn event without an authenticated response.");
1022 var loggedIn = this.LoggedIn;
1023 OpenIdEventArgs args = new OpenIdEventArgs(response);
1024 if (loggedIn != null) {
1025 loggedIn(this, args);
1028 if (!args.Cancel) {
1029 FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, this.UsePersistentCookie);
1033 /// <summary>
1034 /// Fires the <see cref="Failed"/> event.
1035 /// </summary>
1036 /// <param name="response">The response.</param>
1037 protected virtual void OnFailed(IAuthenticationResponse response) {
1038 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1039 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Failed, "Firing Failed event for the wrong response type.");
1041 var failed = this.Failed;
1042 if (failed != null) {
1043 failed(this, new OpenIdEventArgs(response));
1047 /// <summary>
1048 /// Fires the <see cref="Canceled"/> event.
1049 /// </summary>
1050 /// <param name="response">The response.</param>
1051 protected virtual void OnCanceled(IAuthenticationResponse response) {
1052 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1053 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Canceled, "Firing Canceled event for the wrong response type.");
1055 var canceled = this.Canceled;
1056 if (canceled != null) {
1057 canceled(this, new OpenIdEventArgs(response));
1061 /// <summary>
1062 /// Fires the <see cref="SetupRequired"/> event.
1063 /// </summary>
1064 /// <param name="response">The response.</param>
1065 protected virtual void OnSetupRequired(IAuthenticationResponse response) {
1066 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1067 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.SetupRequired, "Firing SetupRequired event for the wrong response type.");
1069 // Why are we firing Failed when we're OnSetupRequired? Backward compatibility.
1070 var setupRequired = this.SetupRequired;
1071 if (setupRequired != null) {
1072 setupRequired(this, new OpenIdEventArgs(response));
1076 #endregion
1078 /// <summary>
1079 /// Adds extensions to a given authentication request to ask the Provider
1080 /// for user profile data.
1081 /// </summary>
1082 /// <param name="request">The authentication request to add the extensions to.</param>
1083 private void AddProfileArgs(IAuthenticationRequest request) {
1084 ErrorUtilities.VerifyArgumentNotNull(request, "request");
1086 request.AddExtension(new ClaimsRequest() {
1087 Nickname = this.RequestNickname,
1088 Email = this.RequestEmail,
1089 FullName = this.RequestFullName,
1090 BirthDate = this.RequestBirthDate,
1091 Gender = this.RequestGender,
1092 PostalCode = this.RequestPostalCode,
1093 Country = this.RequestCountry,
1094 Language = this.RequestLanguage,
1095 TimeZone = this.RequestTimeZone,
1096 PolicyUrl = string.IsNullOrEmpty(this.PolicyUrl) ?
1097 null : new Uri(MessagingUtilities.GetRequestUrlFromContext(), this.Page.ResolveUrl(this.PolicyUrl)),
1101 /// <summary>
1102 /// Creates the relying party instance used to generate authentication requests.
1103 /// </summary>
1104 /// <returns>The instantiated relying party.</returns>
1105 private OpenIdRelyingParty CreateRelyingParty() {
1106 // If we're in stateful mode, first use the explicitly given one on this control if there
1107 // is one. Then try the configuration file specified one. Finally, use the default
1108 // in-memory one that's built into OpenIdRelyingParty.
1109 IRelyingPartyApplicationStore store = this.Stateless ? null :
1110 (this.CustomApplicationStore ?? DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore));
1111 var rp = new OpenIdRelyingParty(store);
1113 // Only set RequireSsl to true, as we don't want to override
1114 // a .config setting of true with false.
1115 if (this.RequireSsl) {
1116 rp.SecuritySettings.RequireSsl = true;
1118 return rp;