コード例 #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoResponsiveRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request message.</param>
        /// <param name="request">The request message.</param>
        /// <param name="response">The response that is ready for transmittal.</param>
        internal AutoResponsiveRequest(OpenIdProvider provider, IDirectedProtocolMessage request, IProtocolMessage response)
            : base(provider, request)
        {
            ErrorUtilities.VerifyArgumentNotNull(response, "response");

            this.response = response;
        }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AutoResponsiveRequest"/> class
        /// for a response to an unrecognizable request.
        /// </summary>
        /// <param name="provider">The provider that received the request message.</param>
        /// <param name="response">The response that is ready for transmittal.</param>
        internal AutoResponsiveRequest(OpenIdProvider provider, IProtocolMessage response)
            : base(provider, IndirectResponseBase.GetVersion(response))
        {
            ErrorUtilities.VerifyArgumentNotNull(response, "response");

            this.response = response;
        }
コード例 #3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request.</param>
        /// <param name="request">The incoming request message.</param>
        protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(request, provider.SecuritySettings)
        {
            Contract.Requires(provider != null);

            this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
        }
コード例 #4
0
		internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(provider, request) {
			Contract.Requires<ArgumentNullException>(provider != null);
			Contract.Requires<ArgumentException>(!(request is CheckIdRequest), "Instantiate " + typeof(AuthenticationRequest).Name + " to handle this kind of message.");

			this.positiveResponse = new IndirectSignedResponse(request);
		}
コード例 #5
0
		internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(provider, request) {
			Contract.Requires<ArgumentNullException>(provider != null);
			Contract.Requires<ArgumentException>(!(request is CheckIdRequest));

			this.positiveResponse = new IndirectSignedResponse(request);
		}
コード例 #6
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
		/// </summary>
		/// <param name="provider">The provider that received the request.</param>
		/// <param name="request">The incoming request message.</param>
		protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(request, provider.SecuritySettings) {
			Contract.Requires<ArgumentNullException>(provider != null);

			this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
			Reporting.RecordEventOccurrence(this, request.Realm);
		}
コード例 #7
0
ファイル: Acme.cs プロジェクト: haoasqui/ONLYOFFICE-Server
		public static void Register(OpenIdProvider provider) {
			if (provider == null) {
				throw new ArgumentNullException("provider");
			}

			provider.ExtensionFactories.Add(new Acme());
		}
コード例 #8
0
        /// <summary>
        /// Checks for incoming OpenID requests, responds to ones it can
        /// respond to without policy checks, and fires events for custom
        /// handling of the ones it cannot decide on automatically.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.Enabled)
            {
                // Use the explicitly given state store on this control if there is one.
                // Then try the configuration file specified one.  Finally, use the default
                // in-memory one that's built into OpenIdProvider.
                using (OpenIdProvider provider = new OpenIdProvider(this.CustomApplicationStore ?? DotNetOpenAuthSection.Configuration.OpenId.Provider.ApplicationStore.CreateInstance(OpenIdProvider.HttpApplicationStore))) {
                    // determine what incoming message was received
                    IRequest request = provider.GetRequest();
                    if (request != null)
                    {
                        // process the incoming message appropriately and send the response
                        if (!request.IsResponseReady)
                        {
                            var idrequest = (IAuthenticationRequest)request;
                            PendingAuthenticationRequest = idrequest;
                            this.OnAuthenticationChallenge(idrequest);
                        }
                        else
                        {
                            PendingAuthenticationRequest = null;
                        }
                        if (request.IsResponseReady)
                        {
                            request.Response.Send();
                            Page.Response.End();
                            PendingAuthenticationRequest = null;
                        }
                    }
                }
            }
        }
コード例 #9
0
		internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(provider, request) {
			Requires.NotNull(provider, "provider");
			Requires.True(!(request is CheckIdRequest), "request");

			this.positiveResponse = new IndirectSignedResponse(request);
		}
コード例 #10
0
		public async Task UnsolicitedAssertion() {
			var opStore = new StandardProviderApplicationStore();
			Handle(RPUri).By(
				async req => {
					var rp = new OpenIdRelyingParty(new StandardRelyingPartyApplicationStore(), this.HostFactories);
					IAuthenticationResponse response = await rp.GetResponseAsync(req);
					Assert.That(response, Is.Not.Null);
					Assert.AreEqual(AuthenticationStatus.Authenticated, response.Status);
					return new HttpResponseMessage();
				});
			Handle(OPUri).By(
				async (req, ct) => {
					var op = new OpenIdProvider(opStore, this.HostFactories);
					return await this.AutoProviderActionAsync(op, req, ct);
				});
			this.RegisterMockRPDiscovery(ssl: false);

			{
				var op = new OpenIdProvider(opStore, this.HostFactories);
				Identifier id = GetMockIdentifier(ProtocolVersion.V20);
				var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]);

				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
						response.EnsureSuccessStatusCode();
					}
				}
			}
		}
コード例 #11
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
		/// </summary>
		/// <param name="provider">The provider that received the request.</param>
		/// <param name="request">The incoming request message.</param>
		protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(request, provider.SecuritySettings) {
			Requires.NotNull(provider, "provider");

			this.SharedInitialization(provider);
			Reporting.RecordEventOccurrence(this, request.Realm);
		}
コード例 #12
0
		/// <summary>
		/// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
		/// </summary>
		/// <param name="provider">The provider that received the request.</param>
		/// <param name="request">The incoming request message.</param>
		protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
			: base(request, provider.SecuritySettings) {
			Requires.NotNull(provider, "provider");

			this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
			Reporting.RecordEventOccurrence(this, request.Realm);
		}
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request.</param>
        /// <param name="request">The incoming request message.</param>
        protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(request, provider.SecuritySettings)
        {
            Contract.Requires <ArgumentNullException>(provider != null);

            this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
            Reporting.RecordEventOccurrence(this, request.Realm);
        }
コード例 #14
0
        internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(provider, request)
        {
            Requires.NotNull(provider, "provider");
            Requires.That(!(request is CheckIdRequest), "request", "request cannot be CheckIdRequest");

            this.positiveResponse = new IndirectSignedResponse(request);
        }
コード例 #15
0
        internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(provider, request)
        {
            Contract.Requires <ArgumentNullException>(provider != null);
            Contract.Requires <ArgumentException>(!(request is CheckIdRequest), "Instantiate " + typeof(AuthenticationRequest).Name + " to handle this kind of message.");

            this.positiveResponse = new IndirectSignedResponse(request);
        }
コード例 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="version">The version.</param>
        protected Request(OpenIdProvider provider, Version version)
        {
            ErrorUtilities.VerifyArgumentNotNull(provider, "provider");
            ErrorUtilities.VerifyArgumentNotNull(version, "version");

            this.provider = provider;
            this.Protocol = Protocol.Lookup(version);
        }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request.</param>
        /// <param name="request">The incoming request message.</param>
        protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(request, provider.SecuritySettings)
        {
            Requires.NotNull(provider, "provider");

            this.SharedInitialization(provider);
            Reporting.RecordEventOccurrence(this, request.Realm);
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HostProcessedRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request.</param>
        /// <param name="request">The incoming request message.</param>
        protected HostProcessedRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(request, provider.SecuritySettings)
        {
            Requires.NotNull(provider, "provider");

            this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);
            Reporting.RecordEventOccurrence(this, request.Realm);
        }
コード例 #19
0
        /// <summary>
        /// Gets a value indicating whether verification of the return URL claimed by the Relying Party
        /// succeeded.
        /// </summary>
        /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
        /// <returns>Result of realm discovery.</returns>
        /// <remarks>
        /// Return URL verification is only attempted if this property is queried.
        /// The result of the verification is cached per request so calling this
        /// property getter multiple times in one request is not a performance hit.
        /// See OpenID Authentication 2.0 spec section 9.2.1.
        /// </remarks>
        public RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(OpenIdProvider provider)
        {
            if (!this.realmDiscoveryResult.HasValue)
            {
                this.realmDiscoveryResult = this.IsReturnUrlDiscoverableCore(provider);
            }

            return(this.realmDiscoveryResult.Value);
        }
コード例 #20
0
        internal AnonymousRequest(OpenIdProvider provider, SignedResponseRequest request)
            : base(provider, request)
        {
            Contract.Requires(provider != null);
            Contract.Requires(!(request is CheckIdRequest), "Instantiate " + typeof(AuthenticationRequest).Name + " to handle this kind of message.");
            ErrorUtilities.VerifyInternal(!(request is CheckIdRequest), "Instantiate {0} to handle this kind of message.", typeof(AuthenticationRequest).Name);

            this.positiveResponse = new IndirectSignedResponse(request);
        }
コード例 #21
0
		public override void SetUp() {
			base.SetUp();

			this.protocol = Protocol.Default;
			this.provider = this.CreateProvider();
			this.checkIdRequest = new CheckIdRequest(this.protocol.Version, OPUri, DotNetOpenAuth.OpenId.AuthenticationRequestMode.Setup);
			this.checkIdRequest.Realm = RPRealmUri;
			this.checkIdRequest.ReturnTo = RPUri;
			this.request = new AuthenticationRequest(this.provider, this.checkIdRequest);
		}
コード例 #22
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Request"/> class.
        /// </summary>
        /// <param name="provider">The Provider.</param>
        /// <param name="request">The incoming request message.</param>
        protected Request(OpenIdProvider provider, IDirectedProtocolMessage request)
        {
            ErrorUtilities.VerifyArgumentNotNull(provider, "provider");
            ErrorUtilities.VerifyArgumentNotNull(request, "request");

            this.provider          = provider;
            this.request           = request;
            this.Protocol          = Protocol.Lookup(this.request.Version);
            this.extensibleMessage = request as IProtocolMessageWithExtensions;
        }
コード例 #23
0
ファイル: Default.aspx.cs プロジェクト: enslam/dotnetopenid
		private void SendAssertion(string relyingPartyRealm) {
			Uri providerEndpoint = new Uri(Request.Url, Page.ResolveUrl("~/server.aspx"));
			OpenIdProvider op = new OpenIdProvider();
			try {
				// Send user input through identifier parser so we accept more free-form input.
				string rpSite = Identifier.Parse(relyingPartyRealm);
				op.PrepareUnsolicitedAssertion(providerEndpoint, rpSite, Util.BuildIdentityUrl(), Util.BuildIdentityUrl()).Respond();
			} catch (ProtocolException ex) {
				Label errorLabel = (Label)this.loginView.FindControl("errorLabel");
				errorLabel.Visible = true;
				errorLabel.Text = ex.Message;
			}
		}
コード例 #24
0
        /// <summary>
        /// Gets a value indicating whether verification of the return URL claimed by the Relying Party
        /// succeeded.
        /// </summary>
        /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
        /// <returns>Result of realm discovery.</returns>
        private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(OpenIdProvider provider)
        {
            Contract.Requires <ArgumentNullException>(provider != null);

            ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now.");

            try {
                if (this.SecuritySettings.RequireSsl && this.Realm.Scheme != Uri.UriSchemeHttps)
                {
                    Logger.OpenId.WarnFormat("RP discovery failed because RequireSsl is true and RP discovery would begin at insecure URL {0}.", this.Realm);
                    return(RelyingPartyDiscoveryResult.NoServiceDocument);
                }

                var returnToEndpoints = this.Realm.DiscoverReturnToEndpoints(provider.Channel.WebRequestHandler, false);
                if (returnToEndpoints == null)
                {
                    return(RelyingPartyDiscoveryResult.NoServiceDocument);
                }

                foreach (var returnUrl in returnToEndpoints)
                {
                    Realm discoveredReturnToUrl = returnUrl.ReturnToEndpoint;

                    // The spec requires that the return_to URLs given in an RPs XRDS doc
                    // do not contain wildcards.
                    if (discoveredReturnToUrl.DomainWildcard)
                    {
                        Logger.Yadis.WarnFormat("Realm {0} contained return_to URL {1} which contains a wildcard, which is not allowed.", Realm, discoveredReturnToUrl);
                        continue;
                    }

                    // Use the same rules as return_to/realm matching to check whether this
                    // URL fits the return_to URL we were given.
                    if (discoveredReturnToUrl.Contains(this.RequestMessage.ReturnTo))
                    {
                        // no need to keep looking after we find a match
                        return(RelyingPartyDiscoveryResult.Success);
                    }
                }
            } catch (ProtocolException ex) {
                // Don't do anything else.  We quietly fail at return_to verification and return false.
                Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed.  {1}", Realm, ex);
                return(RelyingPartyDiscoveryResult.NoServiceDocument);
            } catch (WebException ex) {
                // Don't do anything else.  We quietly fail at return_to verification and return false.
                Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed.  {1}", Realm, ex);
                return(RelyingPartyDiscoveryResult.NoServiceDocument);
            }

            return(RelyingPartyDiscoveryResult.NoMatchingReturnTo);
        }
コード例 #25
0
		private async Task<HttpResponseMessage> HandleAsync() {
			var provider = new OpenIdProvider(store);
			IRequest request = await provider.GetRequestAsync(this.Request);
			if (request == null) {
				App.Logger.Error("A request came in that did not carry an OpenID message.");
				return new HttpResponseMessage(HttpStatusCode.BadRequest) {
					Content = new StringContent("<html><body>This is an OpenID Provider endpoint.</body></html>", Encoding.UTF8, "text/html"),
				};
			}

			return await await this.MainWindow.Dispatcher.InvokeAsync(async delegate {
				if (!request.IsResponseReady) {
					var authRequest = request as IAuthenticationRequest;
					if (authRequest != null) {
						string userIdentityPageBase = this.Url.Link("default", new { controller = "user" }) + "/";
						var userIdentityPageBaseUri = new Uri(userIdentityPageBase);
						switch (this.MainWindow.checkidRequestList.SelectedIndex) {
							case 0:
								if (authRequest.IsDirectedIdentity) {
									if (this.MainWindow.capitalizedHostName.IsChecked.Value) {
										userIdentityPageBase = (userIdentityPageBaseUri.Scheme + Uri.SchemeDelimiter + userIdentityPageBaseUri.Authority).ToUpperInvariant() + userIdentityPageBaseUri.PathAndQuery;
									}
									string leafPath = "directedidentity";
									if (this.MainWindow.directedIdentityTrailingPeriodsCheckbox.IsChecked.Value) {
										leafPath += ".";
									}
									authRequest.ClaimedIdentifier = Identifier.Parse(userIdentityPageBase + leafPath, true);
									authRequest.LocalIdentifier = authRequest.ClaimedIdentifier;
								}
								authRequest.IsAuthenticated = true;
								break;
							case 1:
								authRequest.IsAuthenticated = false;
								break;
							case 2:
								IntPtr oldForegroundWindow = NativeMethods.GetForegroundWindow();
								bool stoleFocus = NativeMethods.SetForegroundWindow(this.MainWindow);
								await CheckIdWindow.ProcessAuthenticationAsync(userIdentityPageBaseUri, authRequest, CancellationToken.None);
								if (stoleFocus) {
									NativeMethods.SetForegroundWindow(oldForegroundWindow);
								}
								break;
						}
					}
				}

				var responseMessage = await provider.PrepareResponseAsync(request);
				return responseMessage;
			});
		}
コード例 #26
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CheckAuthenticationResponse"/> class
		/// for use by the Provider.
		/// </summary>
		/// <param name="request">The request that this message is responding to.</param>
		/// <param name="provider">The OpenID Provider that is preparing to send this response.</param>
		internal CheckAuthenticationResponse(CheckAuthenticationRequest request, OpenIdProvider provider)
			: base(request.Version, request) {
			Contract.Requires<ArgumentNullException>(provider != null);

			// The channel's binding elements have already set the request's IsValid property
			// appropriately.  We just copy it into the response message.
			this.IsValid = request.IsValid;

			// Confirm the RP should invalidate the association handle only if the association
			// really doesn't exist.  OpenID 2.0 section 11.4.2.2.
			IndirectSignedResponse signedResponse = new IndirectSignedResponse(request, provider.Channel);
			string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;
			if (!string.IsNullOrEmpty(invalidateHandle) && provider.AssociationStore.GetAssociation(AssociationRelyingPartyType.Smart, invalidateHandle) == null) {
				this.InvalidateHandle = invalidateHandle;
			}
		}
コード例 #27
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CheckAuthenticationResponseProvider"/> class.
		/// </summary>
		/// <param name="request">The request that this message is responding to.</param>
		/// <param name="provider">The OpenID Provider that is preparing to send this response.</param>
		internal CheckAuthenticationResponseProvider(CheckAuthenticationRequest request, OpenIdProvider provider)
			: base(request.Version, request) {
			Requires.NotNull(provider, "provider");

			// The channel's binding elements have already set the request's IsValid property
			// appropriately.  We just copy it into the response message.
			this.IsValid = request.IsValid;

			// Confirm the RP should invalidate the association handle only if the association
			// is not valid (any longer).  OpenID 2.0 section 11.4.2.2.
			IndirectSignedResponse signedResponse = new IndirectSignedResponse(request, provider.Channel);
			string invalidateHandle = ((ITamperResistantOpenIdMessage)signedResponse).InvalidateHandle;
			if (!string.IsNullOrEmpty(invalidateHandle) && !provider.AssociationStore.IsValid(signedResponse, false, invalidateHandle)) {
				this.InvalidateHandle = invalidateHandle;
			}
		}
コード例 #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
        /// </summary>
        /// <param name="provider">The provider that received the request.</param>
        /// <param name="request">The incoming authentication request message.</param>
        internal AuthenticationRequest(OpenIdProvider provider, CheckIdRequest request)
            : base(provider, request)
        {
            this.positiveResponse = new PositiveAssertionResponse(request);
            this.negativeResponse = new NegativeAssertionResponse(request, provider.Channel);

            if (this.ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier &&
                Protocol.ClaimedIdentifierForOPIdentifier != null)
            {
                // Force the hosting OP to deal with identifier_select by nulling out the two identifiers.
                this.IsDirectedIdentity = true;
                this.positiveResponse.ClaimedIdentifier = null;
                this.positiveResponse.LocalIdentifier   = null;
            }

            // URL delegation is only detectable from 2.0 RPs, since openid.claimed_id isn't included from 1.0 RPs.
            // If the openid.claimed_id is present, and if it's different than the openid.identity argument, then
            // the RP has discovered a claimed identifier that has delegated authentication to this Provider.
            this.IsDelegatedIdentifier = this.ClaimedIdentifier != null && this.ClaimedIdentifier != this.LocalIdentifier;
        }
コード例 #29
0
		/// <summary>
		/// Initializes a new instance of the <see cref="AuthenticationRequest"/> class.
		/// </summary>
		/// <param name="provider">The provider that received the request.</param>
		/// <param name="request">The incoming authentication request message.</param>
		internal AuthenticationRequest(OpenIdProvider provider, CheckIdRequest request)
			: base(provider, request) {
			Requires.NotNull(provider, "provider");

			this.positiveResponse = new PositiveAssertionResponse(request);

			if (this.ClaimedIdentifier == Protocol.ClaimedIdentifierForOPIdentifier &&
				Protocol.ClaimedIdentifierForOPIdentifier != null) {
				// Force the hosting OP to deal with identifier_select by nulling out the two identifiers.
				this.IsDirectedIdentity = true;
				this.positiveResponse.ClaimedIdentifier = null;
				this.positiveResponse.LocalIdentifier = null;
			}

			// URL delegation is only detectable from 2.0 RPs, since openid.claimed_id isn't included from 1.0 RPs.
			// If the openid.claimed_id is present, and if it's different than the openid.identity argument, then
			// the RP has discovered a claimed identifier that has delegated authentication to this Provider.
			this.IsDelegatedIdentifier = this.ClaimedIdentifier != null && this.ClaimedIdentifier != this.LocalIdentifier;

			Reporting.RecordEventOccurrence("AuthenticationRequest.IsDelegatedIdentifier", this.IsDelegatedIdentifier.ToString());
		}
コード例 #30
0
		/// <summary>
		/// Gets a default implementation of a simple provider that responds to authentication requests
		/// per the scenario that is being simulated.
		/// </summary>
		/// <remarks>
		/// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
		/// </remarks>
		internal async Task<HttpResponseMessage> AutoProviderActionAsync(OpenIdProvider provider, HttpRequestMessage req, CancellationToken ct) {
			IRequest request = await provider.GetRequestAsync(req, ct);
			Assert.That(request, Is.Not.Null);

			if (!request.IsResponseReady) {
				var authRequest = (IAuthenticationRequest)request;
				switch (this.AutoProviderScenario) {
					case Scenarios.AutoApproval:
						authRequest.IsAuthenticated = true;
						break;
					case Scenarios.AutoApprovalAddFragment:
						authRequest.SetClaimedIdentifierFragment("frag");
						authRequest.IsAuthenticated = true;
						break;
					case Scenarios.ApproveOnSetup:
						authRequest.IsAuthenticated = !authRequest.Immediate;
						break;
					case Scenarios.AlwaysDeny:
						authRequest.IsAuthenticated = false;
						break;
					default:
						// All other scenarios are done programmatically only.
						throw new InvalidOperationException("Unrecognized scenario");
				}
			}

			return await provider.PrepareResponseAsync(request, ct);
		}
コード例 #31
0
 /// <summary>
 /// Performs initialization common to construction and deserialization.
 /// </summary>
 /// <param name="provider">The provider.</param>
 private void SharedInitialization(OpenIdProvider provider)
 {
     this.negativeResponse = new Lazy <Task <NegativeAssertionResponse> >(() => NegativeAssertionResponse.CreateAsync(this.RequestMessage, CancellationToken.None, provider.Channel));
 }
コード例 #32
0
		/// <summary>
		/// Gets a default implementation of a simple provider that responds to authentication requests
		/// per the scenario that is being simulated.
		/// </summary>
		/// <remarks>
		/// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
		/// </remarks>
		internal void RegisterAutoProvider() {
			this.Handle(OPUri).By(
				async (req, ct) => {
					var provider = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories);
					return await this.AutoProviderActionAsync(provider, req, ct);
				});
		}
コード例 #33
0
ファイル: OpenIdTestBase.cs プロジェクト: enslam/dotnetopenid
		/// <summary>
		/// Creates a standard <see cref="OpenIdProvider"/> instance for general testing.
		/// </summary>
		/// <returns>The new instance.</returns>
		protected OpenIdProvider CreateProvider() {
			var op = new OpenIdProvider(new StandardProviderApplicationStore());
			op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler;
			op.DiscoveryServices.Add(new MockIdentifierDiscoveryService());
			return op;
		}
コード例 #34
0
		/// <summary>
		/// Performs initialization common to construction and deserialization.
		/// </summary>
		/// <param name="provider">The provider.</param>
		private void SharedInitialization(OpenIdProvider provider) {
			this.negativeResponse = new Lazy<Task<NegativeAssertionResponse>>(() => NegativeAssertionResponse.CreateAsync(this.RequestMessage, CancellationToken.None, provider.Channel));
		}
コード例 #35
0
		public async Task UnsolicitedDelegatingIdentifierRejection() {
			var opStore = new MemoryCryptoKeyAndNonceStore();
			Handle(RPUri).By(
				async req => {
					var rp = this.CreateRelyingParty();
					rp.SecuritySettings.RejectDelegatingIdentifiers = true;
					IAuthenticationResponse response = await rp.GetResponseAsync(req);
					Assert.That(response, Is.Not.Null);
					Assert.AreEqual(AuthenticationStatus.Failed, response.Status);
					return new HttpResponseMessage();
				});
			Handle(OPUri).By(
				async req => {
					var op = new OpenIdProvider(opStore, this.HostFactories);
					return await this.AutoProviderActionAsync(op, req, CancellationToken.None);
				});
			this.RegisterMockRPDiscovery(ssl: false);

			{
				var op = new OpenIdProvider(opStore, this.HostFactories);
				Identifier id = GetMockIdentifier(ProtocolVersion.V20, false, true);
				var assertion = await op.PrepareUnsolicitedAssertionAsync(OPUri, RPRealmUri, id, OPLocalIdentifiers[0]);
				using (var httpClient = this.HostFactories.CreateHttpClient()) {
					using (var response = await httpClient.GetAsync(assertion.Headers.Location)) {
						response.EnsureSuccessStatusCode();
					}
				}
			}
		}
コード例 #36
0
ファイル: OpenIdTestBase.cs プロジェクト: enslam/dotnetopenid
		/// <summary>
		/// A default implementation of a simple provider that responds to authentication requests
		/// per the scenario that is being simulated.
		/// </summary>
		/// <param name="provider">The OpenIdProvider on which the process messages.</param>
		/// <remarks>
		/// This is a very useful method to pass to the OpenIdCoordinator constructor for the Provider argument.
		/// </remarks>
		internal void AutoProvider(OpenIdProvider provider) {
			while (!((CoordinatingChannel)provider.Channel).RemoteChannel.IsDisposed) {
				IRequest request = provider.GetRequest();
				if (request == null) {
					continue;
				}

				if (!request.IsResponseReady) {
					var authRequest = (DotNetOpenAuth.OpenId.Provider.IAuthenticationRequest)request;
					switch (this.AutoProviderScenario) {
						case Scenarios.AutoApproval:
							authRequest.IsAuthenticated = true;
							break;
						case Scenarios.AutoApprovalAddFragment:
							authRequest.SetClaimedIdentifierFragment("frag");
							authRequest.IsAuthenticated = true;
							break;
						case Scenarios.ApproveOnSetup:
							authRequest.IsAuthenticated = !authRequest.Immediate;
							break;
						case Scenarios.AlwaysDeny:
							authRequest.IsAuthenticated = false;
							break;
						default:
							// All other scenarios are done programmatically only.
							throw new InvalidOperationException("Unrecognized scenario");
					}
				}

				provider.Respond(request);
			}
		}
コード例 #37
0
		/// <summary>
		/// Runs a parameterized association flow test.
		/// </summary>
		/// <param name="opDescription">
		/// The description of the Provider that the relying party uses to formulate the request.  
		/// The specific host is not used, but the scheme is significant.
		/// </param>
		/// <param name="expectedAssociationType">
		/// The value of the openid.assoc_type parameter expected,
		/// or null if a failure is anticipated.
		/// </param>
		private async Task ParameterizedAssociationTestAsync(
			ProviderEndpointDescription opDescription,
			string expectedAssociationType) {
			Protocol protocol = Protocol.Lookup(Protocol.Lookup(opDescription.Version).ProtocolVersion);
			bool expectSuccess = expectedAssociationType != null;
			bool expectDiffieHellman = !opDescription.Uri.IsTransportSecure();
			Association rpAssociation = null, opAssociation;
			AssociateSuccessfulResponse associateSuccessfulResponse = null;
			AssociateUnsuccessfulResponse associateUnsuccessfulResponse = null;
			var relyingParty = new OpenIdRelyingParty(new MemoryCryptoKeyAndNonceStore(), this.HostFactories);
			var provider = new OpenIdProvider(new MemoryCryptoKeyAndNonceStore(), this.HostFactories) {
				SecuritySettings = this.ProviderSecuritySettings
			};
			Handle(opDescription.Uri).By(
				async (request, ct) => {
					IRequest req = await provider.GetRequestAsync(request, ct);
					Assert.IsNotNull(req, "Expected incoming request but did not receive it.");
					Assert.IsTrue(req.IsResponseReady);
					return await provider.PrepareResponseAsync(req, ct);
				});
			relyingParty.Channel.IncomingMessageFilter = message => {
				Assert.AreSame(opDescription.Version, message.Version, "The message was recognized as version {0} but was expected to be {1}.", message.Version, Protocol.Lookup(opDescription.Version).ProtocolVersion);
				var associateSuccess = message as AssociateSuccessfulResponse;
				var associateFailed = message as AssociateUnsuccessfulResponse;
				if (associateSuccess != null) {
					associateSuccessfulResponse = associateSuccess;
				}
				if (associateFailed != null) {
					associateUnsuccessfulResponse = associateFailed;
				}
			};
			relyingParty.Channel.OutgoingMessageFilter = message => {
				Assert.AreEqual(opDescription.Version, message.Version, "The message was for version {0} but was expected to be for {1}.", message.Version, opDescription.Version);
			};

			relyingParty.SecuritySettings = this.RelyingPartySecuritySettings;
			rpAssociation = await relyingParty.AssociationManager.GetOrCreateAssociationAsync(opDescription, CancellationToken.None);

			if (expectSuccess) {
				Assert.IsNotNull(rpAssociation);
				Association actual = relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, rpAssociation.Handle);
				Assert.AreEqual(rpAssociation, actual);
				opAssociation = provider.AssociationStore.Deserialize(new TestSignedDirectedMessage(), false, rpAssociation.Handle);
				Assert.IsNotNull(opAssociation, "The Provider could not decode the association handle.");

				Assert.AreEqual(opAssociation.Handle, rpAssociation.Handle);
				Assert.AreEqual(expectedAssociationType, rpAssociation.GetAssociationType(protocol));
				Assert.AreEqual(expectedAssociationType, opAssociation.GetAssociationType(protocol));
				Assert.IsTrue(Math.Abs(opAssociation.SecondsTillExpiration - rpAssociation.SecondsTillExpiration) < 60);
				Assert.IsTrue(MessagingUtilities.AreEquivalent(opAssociation.SecretKey, rpAssociation.SecretKey));

				if (expectDiffieHellman) {
					Assert.IsInstanceOf<AssociateDiffieHellmanResponse>(associateSuccessfulResponse);
					var diffieHellmanResponse = (AssociateDiffieHellmanResponse)associateSuccessfulResponse;
					Assert.IsFalse(MessagingUtilities.AreEquivalent(diffieHellmanResponse.EncodedMacKey, rpAssociation.SecretKey), "Key should have been encrypted.");
				} else {
					Assert.IsInstanceOf<AssociateUnencryptedResponse>(associateSuccessfulResponse);
					var unencryptedResponse = (AssociateUnencryptedResponse)associateSuccessfulResponse;
				}
			} else {
				Assert.IsNull(relyingParty.AssociationManager.AssociationStoreTestHook.GetAssociation(opDescription.Uri, new RelyingPartySecuritySettings()));
			}
		}
コード例 #38
0
 /// <summary>
 /// Attempts to perform relying party discovery of the return URL claimed by the Relying Party.
 /// </summary>
 /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
 /// <returns>
 /// The details of how successful the relying party discovery was.
 /// </returns>
 /// <remarks>
 ///     <para>Return URL verification is only attempted if this method is called.</para>
 ///     <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
 /// </remarks>
 RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(OpenIdProvider provider)
 {
     Contract.Requires <ArgumentNullException>(provider != null);
     throw new System.NotImplementedException();
 }
コード例 #39
0
ファイル: ProviderEndpoint.cs プロジェクト: terry2012/DSV
 /// <summary>
 /// Creates the default OpenIdProvider to use.
 /// </summary>
 /// <returns>The new instance of OpenIdProvider.</returns>
 private OpenIdProvider CreateProvider()
 {
     return(new OpenIdProvider(OpenIdElement.Configuration.Provider.ApplicationStore.CreateInstance(OpenIdProvider.GetHttpApplicationStore(new HttpContextWrapper(this.Context)), null)));
 }
コード例 #40
0
		/// <summary>
		/// Gets a value indicating whether verification of the return URL claimed by the Relying Party
		/// succeeded.
		/// </summary>
		/// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
		/// <returns>Result of realm discovery.</returns>
		private RelyingPartyDiscoveryResult IsReturnUrlDiscoverableCore(OpenIdProvider provider) {
			Contract.Requires<ArgumentNullException>(provider != null);

			ErrorUtilities.VerifyInternal(this.Realm != null, "Realm should have been read or derived by now.");

			try {
				if (this.SecuritySettings.RequireSsl && this.Realm.Scheme != Uri.UriSchemeHttps) {
					Logger.OpenId.WarnFormat("RP discovery failed because RequireSsl is true and RP discovery would begin at insecure URL {0}.", this.Realm);
					return RelyingPartyDiscoveryResult.NoServiceDocument;
				}

				var returnToEndpoints = this.Realm.DiscoverReturnToEndpoints(provider.Channel.WebRequestHandler, false);
				if (returnToEndpoints == null) {
					return RelyingPartyDiscoveryResult.NoServiceDocument;
				}

				foreach (var returnUrl in returnToEndpoints) {
					Realm discoveredReturnToUrl = returnUrl.ReturnToEndpoint;

					// The spec requires that the return_to URLs given in an RPs XRDS doc
					// do not contain wildcards.
					if (discoveredReturnToUrl.DomainWildcard) {
						Logger.Yadis.WarnFormat("Realm {0} contained return_to URL {1} which contains a wildcard, which is not allowed.", Realm, discoveredReturnToUrl);
						continue;
					}

					// Use the same rules as return_to/realm matching to check whether this
					// URL fits the return_to URL we were given.
					if (discoveredReturnToUrl.Contains(this.RequestMessage.ReturnTo)) {
						// no need to keep looking after we find a match
						return RelyingPartyDiscoveryResult.Success;
					}
				}
			} catch (ProtocolException ex) {
				// Don't do anything else.  We quietly fail at return_to verification and return false.
				Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed.  {1}", Realm, ex);
				return RelyingPartyDiscoveryResult.NoServiceDocument;
			} catch (WebException ex) {
				// Don't do anything else.  We quietly fail at return_to verification and return false.
				Logger.Yadis.InfoFormat("Relying party discovery at URL {0} failed.  {1}", Realm, ex);
				return RelyingPartyDiscoveryResult.NoServiceDocument;
			}

			return RelyingPartyDiscoveryResult.NoMatchingReturnTo;
		}
コード例 #41
0
		public override void SetUp() {
			base.SetUp();

			this.provider = this.CreateProvider();
		}
コード例 #42
0
 /// <summary>
 /// Attempts to perform relying party discovery of the return URL claimed by the Relying Party.
 /// </summary>
 /// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
 /// <returns>
 /// The details of how successful the relying party discovery was.
 /// </returns>
 /// <remarks>
 ///     <para>Return URL verification is only attempted if this method is called.</para>
 ///     <para>See OpenID Authentication 2.0 spec section 9.2.1.</para>
 /// </remarks>
 RelyingPartyDiscoveryResult IHostProcessedRequest.IsReturnUrlDiscoverable(OpenIdProvider provider)
 {
     throw new NotImplementedException();
 }
コード例 #43
0
ファイル: UIRequest.cs プロジェクト: jsmale/dotnetopenid
		/// <summary>
		/// Gets the URL of the RP icon for the OP to display.
		/// </summary>
		/// <param name="realm">The realm of the RP where the authentication request originated.</param>
		/// <param name="provider">The Provider instance used to obtain the authentication request.</param>
		/// <returns>
		/// A sequence of the RP's icons it has available for the Provider to display, in decreasing preferred order.
		/// </returns>
		/// <value>The icon URL.</value>
		/// <remarks>
		/// This property is automatically set for the OP with the result of RP discovery.
		/// RPs should set this value by including an entry such as this in their XRDS document.
		/// <example>
		/// &lt;Service xmlns="xri://$xrd*($v*2.0)"&gt;
		/// &lt;Type&gt;http://specs.openid.net/extensions/ui/icon&lt;/Type&gt;
		/// &lt;URI&gt;http://consumer.example.com/images/image.jpg&lt;/URI&gt;
		/// &lt;/Service&gt;
		/// </example>
		/// </remarks>
		public static IEnumerable<Uri> GetRelyingPartyIconUrls(Realm realm, OpenIdProvider provider) {
			Contract.Requires(realm != null);
			Contract.Requires(provider != null);
			ErrorUtilities.VerifyArgumentNotNull(realm, "realm");
			ErrorUtilities.VerifyArgumentNotNull(provider, "provider");

			return GetRelyingPartyIconUrls(realm, provider.Channel.WebRequestHandler);
		}
コード例 #44
0
		/// <summary>
		/// Creates a standard <see cref="OpenIdProvider"/> instance for general testing.
		/// </summary>
		/// <returns>The new instance.</returns>
		protected OpenIdProvider CreateProvider() {
			var op = new OpenIdProvider(new StandardProviderApplicationStore(), this.HostFactories);
			return op;
		}
コード例 #45
0
ファイル: OpenIdTestBase.cs プロジェクト: jcp-xx/dotnetopenid
 /// <summary>
 /// Creates a standard <see cref="OpenIdProvider"/> instance for general testing.
 /// </summary>
 /// <returns>The new instance.</returns>
 protected OpenIdProvider CreateProvider()
 {
     var op = new OpenIdProvider(new StandardProviderApplicationStore());
     op.Channel.WebRequestHandler = this.MockResponder.MockWebRequestHandler;
     return op;
 }
コード例 #46
0
		/// <summary>
		/// Gets a value indicating whether verification of the return URL claimed by the Relying Party
		/// succeeded.
		/// </summary>
		/// <param name="provider">The OpenIdProvider that is performing the RP discovery.</param>
		/// <returns>Result of realm discovery.</returns>
		/// <remarks>
		/// Return URL verification is only attempted if this property is queried.
		/// The result of the verification is cached per request so calling this
		/// property getter multiple times in one request is not a performance hit.
		/// See OpenID Authentication 2.0 spec section 9.2.1.
		/// </remarks>
		public RelyingPartyDiscoveryResult IsReturnUrlDiscoverable(OpenIdProvider provider) {
			if (!this.realmDiscoveryResult.HasValue) {
				this.realmDiscoveryResult = this.IsReturnUrlDiscoverableCore(provider);
			}

			return this.realmDiscoveryResult.Value;
		}
コード例 #47
0
 public override void SetUp()
 {
     base.SetUp();
     SuspendLogging();
     this.provider = CreateProvider();
 }