Added the OpenIdMobileTextBox ASP.NET control.
[dotnetoauth.git] / src / DotNetOpenAuth / OpenId / RelyingParty / OpenIdTextBox.cs
blob767d925c127184f7d4976a60765952431cbe8f42
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 #region Events
312 /// <summary>
313 /// Fired upon completion of a successful login.
314 /// </summary>
315 [Description("Fired upon completion of a successful login.")]
316 public event EventHandler<OpenIdEventArgs> LoggedIn;
318 /// <summary>
319 /// Fired when a login attempt fails.
320 /// </summary>
321 [Description("Fired when a login attempt fails.")]
322 public event EventHandler<OpenIdEventArgs> Failed;
324 /// <summary>
325 /// Fired when an authentication attempt is canceled at the OpenID Provider.
326 /// </summary>
327 [Description("Fired when an authentication attempt is canceled at the OpenID Provider.")]
328 public event EventHandler<OpenIdEventArgs> Canceled;
330 /// <summary>
331 /// Fired when an Immediate authentication attempt fails, and the Provider suggests using non-Immediate mode.
332 /// </summary>
333 [Description("Fired when an Immediate authentication attempt fails, and the Provider suggests using non-Immediate mode.")]
334 public event EventHandler<OpenIdEventArgs> SetupRequired;
336 #endregion
337 #region IEditableTextControl Members
339 /// <summary>
340 /// Occurs when the content of the text changes between posts to the server.
341 /// </summary>
342 public event EventHandler TextChanged {
343 add { this.WrappedTextBox.TextChanged += value; }
344 remove { this.WrappedTextBox.TextChanged -= value; }
347 #endregion
349 #region Properties
351 /// <summary>
352 /// Gets or sets the content of the text box.
353 /// </summary>
354 [Bindable(true), DefaultValue(""), Category(AppearanceCategory)]
355 [Description("The content of the text box.")]
356 public string Text {
357 get {
358 return this.WrappedTextBox != null ? this.WrappedTextBox.Text : this.text;
361 set {
362 this.text = value;
363 if (this.WrappedTextBox != null) {
364 this.WrappedTextBox.Text = value;
369 /// <summary>
370 /// Gets or sets the OpenID <see cref="Realm"/> of the relying party web site.
371 /// </summary>
372 [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Uri", Justification = "Using Uri.ctor for validation.")]
373 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
374 [Bindable(true), DefaultValue(RealmUrlDefault), Category(BehaviorCategory)]
375 [Description("The OpenID Realm of the relying party web site.")]
376 public string RealmUrl {
377 get {
378 return (string)(ViewState[RealmUrlViewStateKey] ?? RealmUrlDefault);
381 set {
382 if (Page != null && !DesignMode) {
383 // Validate new value by trying to construct a Realm object based on it.
384 new Realm(OpenIdUtilities.GetResolvedRealm(Page, value)); // throws an exception on failure.
385 } else {
386 // We can't fully test it, but it should start with either ~/ or a protocol.
387 if (Regex.IsMatch(value, @"^https?://")) {
388 new Uri(value.Replace("*.", string.Empty)); // make sure it's fully-qualified, but ignore wildcards
389 } else if (value.StartsWith("~/", StringComparison.Ordinal)) {
390 // this is valid too
391 } else {
392 throw new UriFormatException();
395 ViewState[RealmUrlViewStateKey] = value;
399 /// <summary>
400 /// Gets or sets the OpenID ReturnTo of the relying party web site.
401 /// </summary>
402 [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.Uri", Justification = "Using Uri.ctor for validation.")]
403 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
404 [Bindable(true), DefaultValue(ReturnToUrlDefault), Category(BehaviorCategory)]
405 [Description("The OpenID ReturnTo of the relying party web site.")]
406 public string ReturnToUrl {
407 get {
408 return (string)(ViewState[ReturnToUrlViewStateKey] ?? ReturnToUrlDefault);
411 set {
412 if (Page != null && !DesignMode) {
413 // Validate new value by trying to construct a Uri based on it.
414 new Uri(MessagingUtilities.GetRequestUrlFromContext(), Page.ResolveUrl(value)); // throws an exception on failure.
415 } else {
416 // We can't fully test it, but it should start with either ~/ or a protocol.
417 if (Regex.IsMatch(value, @"^https?://")) {
418 new Uri(value); // make sure it's fully-qualified, but ignore wildcards
419 } else if (value.StartsWith("~/", StringComparison.Ordinal)) {
420 // this is valid too
421 } else {
422 throw new UriFormatException();
426 ViewState[ReturnToUrlViewStateKey] = value;
430 /// <summary>
431 /// Gets or sets a value indicating whether to use immediate mode in the
432 /// OpenID protocol.
433 /// </summary>
434 /// <value>
435 /// True if a Provider should reply immediately to the authentication request
436 /// without interacting with the user. False if the Provider can take time
437 /// to authenticate the user in order to complete an authentication attempt.
438 /// </value>
439 /// <remarks>
440 /// Setting this to true is sometimes useful in AJAX scenarios. Setting this to
441 /// true can cause failed authentications when the user truly controls an
442 /// Identifier, but must complete an authentication step with the Provider before
443 /// the Provider will approve the login from this relying party.
444 /// </remarks>
445 [Bindable(true), DefaultValue(ImmediateModeDefault), Category(BehaviorCategory)]
446 [Description("Whether the Provider should respond immediately to an authentication attempt without interacting with the user.")]
447 public bool ImmediateMode {
448 get { return (bool)(ViewState[ImmediateModeViewStateKey] ?? ImmediateModeDefault); }
449 set { ViewState[ImmediateModeViewStateKey] = value; }
452 /// <summary>
453 /// Gets or sets a value indicating whether stateless mode is used.
454 /// </summary>
455 [Bindable(true), DefaultValue(StatelessDefault), Category(BehaviorCategory)]
456 [Description("Controls whether stateless mode is used.")]
457 public bool Stateless {
458 get { return (bool)(ViewState[StatelessViewStateKey] ?? StatelessDefault); }
459 set { ViewState[StatelessViewStateKey] = value; }
462 /// <summary>
463 /// Gets or sets the CSS class assigned to the text box.
464 /// </summary>
465 [Bindable(true), DefaultValue(CssClassDefault), Category(AppearanceCategory)]
466 [Description("The CSS class assigned to the text box.")]
467 public override string CssClass {
468 get { return this.WrappedTextBox.CssClass; }
469 set { this.WrappedTextBox.CssClass = value; }
472 /// <summary>
473 /// Gets or sets a value indicating whether to show the OpenID logo in the text box.
474 /// </summary>
475 [Bindable(true), DefaultValue(ShowLogoDefault), Category(AppearanceCategory)]
476 [Description("The visibility of the OpenID logo in the text box.")]
477 public bool ShowLogo {
478 get { return (bool)(this.ViewState[ShowLogoViewStateKey] ?? ShowLogoDefault); }
479 set { this.ViewState[ShowLogoViewStateKey] = value; }
482 /// <summary>
483 /// Gets or sets a value indicating whether to use inline styling to force a solid gray border.
484 /// </summary>
485 [Bindable(true), DefaultValue(PresetBorderDefault), Category(AppearanceCategory)]
486 [Description("Whether to use inline styling to force a solid gray border.")]
487 public bool PresetBorder {
488 get { return (bool)(this.ViewState[PresetBorderViewStateKey] ?? PresetBorderDefault); }
489 set { this.ViewState[PresetBorderViewStateKey] = value; }
492 /// <summary>
493 /// Gets or sets a value indicating whether to send a persistent cookie upon successful
494 /// login so the user does not have to log in upon returning to this site.
495 /// </summary>
496 [Bindable(true), DefaultValue(UsePersistentCookieDefault), Category(BehaviorCategory)]
497 [Description("Whether to send a persistent cookie upon successful " +
498 "login so the user does not have to log in upon returning to this site.")]
499 public virtual bool UsePersistentCookie {
500 get { return (bool)(this.ViewState[UsePersistentCookieViewStateKey] ?? UsePersistentCookieDefault); }
501 set { this.ViewState[UsePersistentCookieViewStateKey] = value; }
504 /// <summary>
505 /// Gets or sets the width of the text box in characters.
506 /// </summary>
507 [Bindable(true), DefaultValue(ColumnsDefault), Category(AppearanceCategory)]
508 [Description("The width of the text box in characters.")]
509 public int Columns {
510 get { return this.WrappedTextBox.Columns; }
511 set { this.WrappedTextBox.Columns = value; }
514 /// <summary>
515 /// Gets or sets the maximum number of characters the browser should allow
516 /// </summary>
517 [Bindable(true), DefaultValue(MaxLengthDefault), Category(AppearanceCategory)]
518 [Description("The maximum number of characters the browser should allow.")]
519 public int MaxLength {
520 get { return this.WrappedTextBox.MaxLength; }
521 set { this.WrappedTextBox.MaxLength = value; }
524 /// <summary>
525 /// Gets or sets the tab index of the Web server control.
526 /// </summary>
527 /// <value></value>
528 /// <returns>
529 /// The tab index of the Web server control. The default is 0, which indicates that this property is not set.
530 /// </returns>
531 /// <exception cref="T:System.ArgumentOutOfRangeException">
532 /// The specified tab index is not between -32768 and 32767.
533 /// </exception>
534 [Bindable(true), DefaultValue(TabIndexDefault), Category(BehaviorCategory)]
535 [Description("The tab index of the text box control.")]
536 public override short TabIndex {
537 get { return this.WrappedTextBox.TabIndex; }
538 set { this.WrappedTextBox.TabIndex = value; }
541 /// <summary>
542 /// Gets or sets your level of interest in receiving the user's nickname from the Provider.
543 /// </summary>
544 [Bindable(true), DefaultValue(RequestNicknameDefault), Category(ProfileCategory)]
545 [Description("Your level of interest in receiving the user's nickname from the Provider.")]
546 public DemandLevel RequestNickname {
547 get { return (DemandLevel)(ViewState[RequestNicknameViewStateKey] ?? RequestNicknameDefault); }
548 set { ViewState[RequestNicknameViewStateKey] = value; }
551 /// <summary>
552 /// Gets or sets your level of interest in receiving the user's email address from the Provider.
553 /// </summary>
554 [Bindable(true), DefaultValue(RequestEmailDefault), Category(ProfileCategory)]
555 [Description("Your level of interest in receiving the user's email address from the Provider.")]
556 public DemandLevel RequestEmail {
557 get { return (DemandLevel)(ViewState[RequestEmailViewStateKey] ?? RequestEmailDefault); }
558 set { ViewState[RequestEmailViewStateKey] = value; }
561 /// <summary>
562 /// Gets or sets your level of interest in receiving the user's full name from the Provider.
563 /// </summary>
564 [Bindable(true), DefaultValue(RequestFullNameDefault), Category(ProfileCategory)]
565 [Description("Your level of interest in receiving the user's full name from the Provider")]
566 public DemandLevel RequestFullName {
567 get { return (DemandLevel)(ViewState[RequestFullNameViewStateKey] ?? RequestFullNameDefault); }
568 set { ViewState[RequestFullNameViewStateKey] = value; }
571 /// <summary>
572 /// Gets or sets your level of interest in receiving the user's birthdate from the Provider.
573 /// </summary>
574 [Bindable(true), DefaultValue(RequestBirthDateDefault), Category(ProfileCategory)]
575 [Description("Your level of interest in receiving the user's birthdate from the Provider.")]
576 public DemandLevel RequestBirthDate {
577 get { return (DemandLevel)(ViewState[RequestBirthDateViewStateKey] ?? RequestBirthDateDefault); }
578 set { ViewState[RequestBirthDateViewStateKey] = value; }
581 /// <summary>
582 /// Gets or sets your level of interest in receiving the user's gender from the Provider.
583 /// </summary>
584 [Bindable(true), DefaultValue(RequestGenderDefault), Category(ProfileCategory)]
585 [Description("Your level of interest in receiving the user's gender from the Provider.")]
586 public DemandLevel RequestGender {
587 get { return (DemandLevel)(ViewState[RequestGenderViewStateKey] ?? RequestGenderDefault); }
588 set { ViewState[RequestGenderViewStateKey] = value; }
591 /// <summary>
592 /// Gets or sets your level of interest in receiving the user's postal code from the Provider.
593 /// </summary>
594 [Bindable(true), DefaultValue(RequestPostalCodeDefault), Category(ProfileCategory)]
595 [Description("Your level of interest in receiving the user's postal code from the Provider.")]
596 public DemandLevel RequestPostalCode {
597 get { return (DemandLevel)(ViewState[RequestPostalCodeViewStateKey] ?? RequestPostalCodeDefault); }
598 set { ViewState[RequestPostalCodeViewStateKey] = value; }
601 /// <summary>
602 /// Gets or sets your level of interest in receiving the user's country from the Provider.
603 /// </summary>
604 [Bindable(true)]
605 [Category(ProfileCategory)]
606 [DefaultValue(RequestCountryDefault)]
607 [Description("Your level of interest in receiving the user's country from the Provider.")]
608 public DemandLevel RequestCountry {
609 get { return (DemandLevel)(ViewState[RequestCountryViewStateKey] ?? RequestCountryDefault); }
610 set { ViewState[RequestCountryViewStateKey] = value; }
613 /// <summary>
614 /// Gets or sets your level of interest in receiving the user's preferred language from the Provider.
615 /// </summary>
616 [Bindable(true), DefaultValue(RequestLanguageDefault), Category(ProfileCategory)]
617 [Description("Your level of interest in receiving the user's preferred language from the Provider.")]
618 public DemandLevel RequestLanguage {
619 get { return (DemandLevel)(ViewState[RequestLanguageViewStateKey] ?? RequestLanguageDefault); }
620 set { ViewState[RequestLanguageViewStateKey] = value; }
623 /// <summary>
624 /// Gets or sets your level of interest in receiving the user's time zone from the Provider.
625 /// </summary>
626 [Bindable(true), DefaultValue(RequestTimeZoneDefault), Category(ProfileCategory)]
627 [Description("Your level of interest in receiving the user's time zone from the Provider.")]
628 public DemandLevel RequestTimeZone {
629 get { return (DemandLevel)(ViewState[RequestTimeZoneViewStateKey] ?? RequestTimeZoneDefault); }
630 set { ViewState[RequestTimeZoneViewStateKey] = value; }
633 /// <summary>
634 /// Gets or sets the URL to your privacy policy page that describes how
635 /// claims will be used and/or shared.
636 /// </summary>
637 [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings", Justification = "Bindable property must be simple type")]
638 [Bindable(true), DefaultValue(PolicyUrlDefault), Category(ProfileCategory)]
639 [Description("The URL to your privacy policy page that describes how claims will be used and/or shared.")]
640 public string PolicyUrl {
641 get {
642 return (string)ViewState[PolicyUrlViewStateKey] ?? PolicyUrlDefault;
645 set {
646 UriUtil.ValidateResolvableUrl(Page, DesignMode, value);
647 ViewState[PolicyUrlViewStateKey] = value;
651 /// <summary>
652 /// Gets or sets a value indicating whether to use OpenID extensions
653 /// to retrieve profile data of the authenticating user.
654 /// </summary>
655 [Bindable(true), DefaultValue(EnableRequestProfileDefault), Category(ProfileCategory)]
656 [Description("Turns the entire Simple Registration extension on or off.")]
657 public bool EnableRequestProfile {
658 get { return (bool)(ViewState[EnableRequestProfileViewStateKey] ?? EnableRequestProfileDefault); }
659 set { ViewState[EnableRequestProfileViewStateKey] = value; }
662 /// <summary>
663 /// Gets or sets a value indicating whether to enforce on high security mode,
664 /// which requires the full authentication pipeline to be protected by SSL.
665 /// </summary>
666 [Bindable(true), DefaultValue(RequireSslDefault), Category(BehaviorCategory)]
667 [Description("Turns on high security mode, requiring the full authentication pipeline to be protected by SSL.")]
668 public bool RequireSsl {
669 get { return (bool)(ViewState[RequireSslViewStateKey] ?? RequireSslDefault); }
670 set { ViewState[RequireSslViewStateKey] = value; }
673 /// <summary>
674 /// Gets or sets the type of the custom application store to use, or <c>null</c> to use the default.
675 /// </summary>
676 /// <remarks>
677 /// If set, this property must be set in each Page Load event
678 /// as it is not persisted across postbacks.
679 /// </remarks>
680 public IRelyingPartyApplicationStore CustomApplicationStore { get; set; }
682 #endregion
684 #region Properties to hide
686 /// <summary>
687 /// Gets or sets the foreground color (typically the color of the text) of the Web server control.
688 /// </summary>
689 /// <returns>
690 /// 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"/>.
691 /// </returns>
692 [Obsolete, Browsable(false), Bindable(false)]
693 public override System.Drawing.Color ForeColor {
694 get { throw new NotSupportedException(); }
695 set { throw new NotSupportedException(); }
698 /// <summary>
699 /// Gets or sets the background color of the Web server control.
700 /// </summary>
701 /// <returns>
702 /// 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.
703 /// </returns>
704 [Obsolete, Browsable(false), Bindable(false)]
705 public override System.Drawing.Color BackColor {
706 get { throw new NotSupportedException(); }
707 set { throw new NotSupportedException(); }
710 /// <summary>
711 /// Gets or sets the border color of the Web control.
712 /// </summary>
713 /// <returns>
714 /// 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.
715 /// </returns>
716 [Obsolete, Browsable(false), Bindable(false)]
717 public override System.Drawing.Color BorderColor {
718 get { throw new NotSupportedException(); }
719 set { throw new NotSupportedException(); }
722 /// <summary>
723 /// Gets or sets the border width of the Web server control.
724 /// </summary>
725 /// <returns>
726 /// 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.
727 /// </returns>
728 /// <exception cref="T:System.ArgumentException">
729 /// The specified border width is a negative value.
730 /// </exception>
731 [Obsolete, Browsable(false), Bindable(false)]
732 public override Unit BorderWidth {
733 get { return Unit.Empty; }
734 set { throw new NotSupportedException(); }
737 /// <summary>
738 /// Gets or sets the border style of the Web server control.
739 /// </summary>
740 /// <returns>
741 /// One of the <see cref="T:System.Web.UI.WebControls.BorderStyle"/> enumeration values. The default is NotSet.
742 /// </returns>
743 [Obsolete, Browsable(false), Bindable(false)]
744 public override BorderStyle BorderStyle {
745 get { return BorderStyle.None; }
746 set { throw new NotSupportedException(); }
749 /// <summary>
750 /// Gets the font properties associated with the Web server control.
751 /// </summary>
752 /// <returns>
753 /// A <see cref="T:System.Web.UI.WebControls.FontInfo"/> that represents the font properties of the Web server control.
754 /// </returns>
755 [Obsolete, Browsable(false), Bindable(false)]
756 public override FontInfo Font {
757 get { return null; }
760 /// <summary>
761 /// Gets or sets the height of the Web server control.
762 /// </summary>
763 /// <returns>
764 /// 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"/>.
765 /// </returns>
766 /// <exception cref="T:System.ArgumentException">
767 /// The height was set to a negative value.
768 /// </exception>
769 [Obsolete, Browsable(false), Bindable(false)]
770 public override Unit Height {
771 get { return Unit.Empty; }
772 set { throw new NotSupportedException(); }
775 /// <summary>
776 /// Gets or sets the width of the Web server control.
777 /// </summary>
778 /// <returns>
779 /// 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"/>.
780 /// </returns>
781 /// <exception cref="T:System.ArgumentException">
782 /// The width of the Web server control was set to a negative value.
783 /// </exception>
784 [Obsolete, Browsable(false), Bindable(false)]
785 public override Unit Width {
786 get { return Unit.Empty; }
787 set { throw new NotSupportedException(); }
790 /// <summary>
791 /// Gets or sets the text displayed when the mouse pointer hovers over the Web server control.
792 /// </summary>
793 /// <returns>
794 /// The text displayed when the mouse pointer hovers over the Web server control. The default is <see cref="F:System.String.Empty"/>.
795 /// </returns>
796 [Obsolete, Browsable(false), Bindable(false)]
797 public override string ToolTip {
798 get { return string.Empty; }
799 set { throw new NotSupportedException(); }
802 /// <summary>
803 /// Gets or sets the skin to apply to the control.
804 /// </summary>
805 /// <returns>
806 /// The name of the skin to apply to the control. The default is <see cref="F:System.String.Empty"/>.
807 /// </returns>
808 /// <exception cref="T:System.ArgumentException">
809 /// The skin specified in the <see cref="P:System.Web.UI.WebControls.WebControl.SkinID"/> property does not exist in the theme.
810 /// </exception>
811 [Obsolete, Browsable(false), Bindable(false)]
812 public override string SkinID {
813 get { return string.Empty; }
814 set { throw new NotSupportedException(); }
817 /// <summary>
818 /// Gets or sets a value indicating whether themes apply to this control.
819 /// </summary>
820 /// <returns>true to use themes; otherwise, false. The default is false.
821 /// </returns>
822 [Obsolete, Browsable(false), Bindable(false)]
823 public override bool EnableTheming {
824 get { return false; }
825 set { throw new NotSupportedException(); }
828 #endregion
830 /// <summary>
831 /// Gets the <see cref="TextBox"/> control that this control wraps.
832 /// </summary>
833 protected TextBox WrappedTextBox {
834 get { return this.wrappedTextBox; }
837 /// <summary>
838 /// Gets or sets a value indicating whether the text box should
839 /// receive input focus when the web page appears.
840 /// </summary>
841 protected bool ShouldBeFocused { get; set; }
843 /// <summary>
844 /// Gets or sets the OpenID authentication request that is about to be sent.
845 /// </summary>
846 protected IAuthenticationRequest Request { get; set; }
848 /// <summary>
849 /// Sets the input focus to start on the text box when the page appears
850 /// in the user's browser.
851 /// </summary>
852 public override void Focus() {
853 if (Controls.Count == 0) {
854 this.ShouldBeFocused = true;
855 } else {
856 this.WrappedTextBox.Focus();
860 /// <summary>
861 /// Constructs the authentication request and returns it.
862 /// </summary>
863 /// <returns>The instantiated authentication request.</returns>
864 /// <remarks>
865 /// <para>This method need not be called before calling the <see cref="LogOn"/> method,
866 /// but is offered in the event that adding extensions to the request is desired.</para>
867 /// <para>The Simple Registration extension arguments are added to the request
868 /// before returning if <see cref="EnableRequestProfile"/> is set to true.</para>
869 /// </remarks>
870 public IAuthenticationRequest CreateRequest() {
871 ErrorUtilities.VerifyOperation(this.Request == null, OpenIdStrings.CreateRequestAlreadyCalled);
872 ErrorUtilities.VerifyOperation(!string.IsNullOrEmpty(this.Text), OpenIdStrings.OpenIdTextBoxEmpty);
874 try {
875 var consumer = this.CreateRelyingParty();
877 // Resolve the trust root, and swap out the scheme and port if necessary to match the
878 // return_to URL, since this match is required by OpenId, and the consumer app
879 // may be using HTTP at some times and HTTPS at others.
880 UriBuilder realm = OpenIdUtilities.GetResolvedRealm(this.Page, this.RealmUrl);
881 realm.Scheme = Page.Request.Url.Scheme;
882 realm.Port = Page.Request.Url.Port;
884 // Initiate openid request
885 // We use TryParse here to avoid throwing an exception which
886 // might slip through our validator control if it is disabled.
887 Identifier userSuppliedIdentifier;
888 if (Identifier.TryParse(this.Text, out userSuppliedIdentifier)) {
889 Realm typedRealm = new Realm(realm);
890 if (string.IsNullOrEmpty(this.ReturnToUrl)) {
891 this.Request = consumer.CreateRequest(userSuppliedIdentifier, typedRealm);
892 } else {
893 Uri returnTo = new Uri(MessagingUtilities.GetRequestUrlFromContext(), this.ReturnToUrl);
894 this.Request = consumer.CreateRequest(userSuppliedIdentifier, typedRealm, returnTo);
896 this.Request.Mode = this.ImmediateMode ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
897 if (this.EnableRequestProfile) {
898 this.AddProfileArgs(this.Request);
901 // Add state that needs to survive across the redirect.
902 this.Request.AddCallbackArguments(UsePersistentCookieCallbackKey, this.UsePersistentCookie.ToString(CultureInfo.InvariantCulture));
903 } else {
904 Logger.WarnFormat("An invalid identifier was entered ({0}), but not caught by any validation routine.", this.Text);
905 this.Request = null;
907 } catch (ProtocolException ex) {
908 this.OnFailed(new FailedAuthenticationResponse(ex));
911 return this.Request;
914 /// <summary>
915 /// Immediately redirects to the OpenID Provider to verify the Identifier
916 /// provided in the text box.
917 /// </summary>
918 public void LogOn() {
919 if (this.Request == null) {
920 this.CreateRequest(); // sets this.Request
923 if (this.Request != null) {
924 this.Request.RedirectToProvider();
928 /// <summary>
929 /// Creates the text box control.
930 /// </summary>
931 protected override void CreateChildControls() {
932 base.CreateChildControls();
934 this.Controls.Add(this.wrappedTextBox);
935 if (this.ShouldBeFocused) {
936 this.WrappedTextBox.Focus();
940 /// <summary>
941 /// Initializes the text box control.
942 /// </summary>
943 protected virtual void InitializeControls() {
944 this.wrappedTextBox = new TextBox();
945 this.wrappedTextBox.ID = "wrappedTextBox";
946 this.wrappedTextBox.CssClass = CssClassDefault;
947 this.wrappedTextBox.Columns = ColumnsDefault;
948 this.wrappedTextBox.Text = this.text;
949 this.wrappedTextBox.TabIndex = TabIndexDefault;
952 /// <summary>
953 /// Checks for incoming OpenID authentication responses and fires appropriate events.
954 /// </summary>
955 /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
956 protected override void OnLoad(EventArgs e) {
957 base.OnLoad(e);
959 if (!Enabled || Page.IsPostBack) {
960 return;
963 var rp = this.CreateRelyingParty();
964 var response = rp.GetResponse();
965 if (response != null) {
966 string persistentString = response.GetCallbackArgument(UsePersistentCookieCallbackKey);
967 bool persistentBool;
968 if (persistentString != null && bool.TryParse(persistentString, out persistentBool)) {
969 this.UsePersistentCookie = persistentBool;
972 switch (response.Status) {
973 case AuthenticationStatus.Canceled:
974 this.OnCanceled(response);
975 break;
976 case AuthenticationStatus.Authenticated:
977 this.OnLoggedIn(response);
978 break;
979 case AuthenticationStatus.SetupRequired:
980 this.OnSetupRequired(response);
981 break;
982 case AuthenticationStatus.Failed:
983 this.OnFailed(response);
984 break;
985 default:
986 throw new InvalidOperationException("Unexpected response status code.");
991 /// <summary>
992 /// Prepares the text box to be rendered.
993 /// </summary>
994 /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
995 protected override void OnPreRender(EventArgs e) {
996 base.OnPreRender(e);
998 if (this.ShowLogo) {
999 string logoUrl = Page.ClientScript.GetWebResourceUrl(
1000 typeof(OpenIdTextBox), EmbeddedLogoResourceName);
1001 this.WrappedTextBox.Style[HtmlTextWriterStyle.BackgroundImage] = string.Format(
1002 CultureInfo.InvariantCulture, "url({0})", HttpUtility.HtmlEncode(logoUrl));
1003 this.WrappedTextBox.Style["background-repeat"] = "no-repeat";
1004 this.WrappedTextBox.Style["background-position"] = "0 50%";
1005 this.WrappedTextBox.Style[HtmlTextWriterStyle.PaddingLeft] = "18px";
1008 if (this.PresetBorder) {
1009 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderStyle] = "solid";
1010 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderWidth] = "1px";
1011 this.WrappedTextBox.Style[HtmlTextWriterStyle.BorderColor] = "lightgray";
1015 #region Events
1017 /// <summary>
1018 /// Fires the <see cref="LoggedIn"/> event.
1019 /// </summary>
1020 /// <param name="response">The response.</param>
1021 protected virtual void OnLoggedIn(IAuthenticationResponse response) {
1022 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1023 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Authenticated, "Firing OnLoggedIn event without an authenticated response.");
1025 var loggedIn = this.LoggedIn;
1026 OpenIdEventArgs args = new OpenIdEventArgs(response);
1027 if (loggedIn != null) {
1028 loggedIn(this, args);
1031 if (!args.Cancel) {
1032 FormsAuthentication.RedirectFromLoginPage(response.ClaimedIdentifier, this.UsePersistentCookie);
1036 /// <summary>
1037 /// Fires the <see cref="Failed"/> event.
1038 /// </summary>
1039 /// <param name="response">The response.</param>
1040 protected virtual void OnFailed(IAuthenticationResponse response) {
1041 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1042 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Failed, "Firing Failed event for the wrong response type.");
1044 var failed = this.Failed;
1045 if (failed != null) {
1046 failed(this, new OpenIdEventArgs(response));
1050 /// <summary>
1051 /// Fires the <see cref="Canceled"/> event.
1052 /// </summary>
1053 /// <param name="response">The response.</param>
1054 protected virtual void OnCanceled(IAuthenticationResponse response) {
1055 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1056 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.Canceled, "Firing Canceled event for the wrong response type.");
1058 var canceled = this.Canceled;
1059 if (canceled != null) {
1060 canceled(this, new OpenIdEventArgs(response));
1064 /// <summary>
1065 /// Fires the <see cref="SetupRequired"/> event.
1066 /// </summary>
1067 /// <param name="response">The response.</param>
1068 protected virtual void OnSetupRequired(IAuthenticationResponse response) {
1069 ErrorUtilities.VerifyArgumentNotNull(response, "response");
1070 ErrorUtilities.VerifyInternal(response.Status == AuthenticationStatus.SetupRequired, "Firing SetupRequired event for the wrong response type.");
1072 // Why are we firing Failed when we're OnSetupRequired? Backward compatibility.
1073 var setupRequired = this.SetupRequired;
1074 if (setupRequired != null) {
1075 setupRequired(this, new OpenIdEventArgs(response));
1079 #endregion
1081 /// <summary>
1082 /// Adds extensions to a given authentication request to ask the Provider
1083 /// for user profile data.
1084 /// </summary>
1085 /// <param name="request">The authentication request to add the extensions to.</param>
1086 private void AddProfileArgs(IAuthenticationRequest request) {
1087 ErrorUtilities.VerifyArgumentNotNull(request, "request");
1089 request.AddExtension(new ClaimsRequest() {
1090 Nickname = this.RequestNickname,
1091 Email = this.RequestEmail,
1092 FullName = this.RequestFullName,
1093 BirthDate = this.RequestBirthDate,
1094 Gender = this.RequestGender,
1095 PostalCode = this.RequestPostalCode,
1096 Country = this.RequestCountry,
1097 Language = this.RequestLanguage,
1098 TimeZone = this.RequestTimeZone,
1099 PolicyUrl = string.IsNullOrEmpty(this.PolicyUrl) ?
1100 null : new Uri(MessagingUtilities.GetRequestUrlFromContext(), this.Page.ResolveUrl(this.PolicyUrl)),
1104 /// <summary>
1105 /// Creates the relying party instance used to generate authentication requests.
1106 /// </summary>
1107 /// <returns>The instantiated relying party.</returns>
1108 private OpenIdRelyingParty CreateRelyingParty() {
1109 // If we're in stateful mode, first use the explicitly given one on this control if there
1110 // is one. Then try the configuration file specified one. Finally, use the default
1111 // in-memory one that's built into OpenIdRelyingParty.
1112 IRelyingPartyApplicationStore store = this.Stateless ? null :
1113 (this.CustomApplicationStore ?? DotNetOpenAuthSection.Configuration.OpenId.RelyingParty.ApplicationStore.CreateInstance(OpenIdRelyingParty.HttpApplicationStore));
1114 var rp = new OpenIdRelyingParty(store);
1116 // Only set RequireSsl to true, as we don't want to override
1117 // a .config setting of true with false.
1118 if (this.RequireSsl) {
1119 rp.SecuritySettings.RequireSsl = true;
1121 return rp;