public OpenIdMembershipUser(
   string providerName, 
   Identifier openId,
   string name,
   object providerUserKey,
   string email,
   string passwordQuestion,
   string comment,
   bool isApproved,
   bool isLockedOut,
   DateTime creationDate,
   DateTime lastLoginDate,
   DateTime lastActivityDate,
   DateTime lastPasswordChangedDate,
   DateTime lastLockoutDate)
     : base(providerName,
   name,
   providerUserKey,
   email,
   passwordQuestion,
   comment,
   isApproved,
   isLockedOut,
   creationDate,
   lastLoginDate,
   lastActivityDate,
   lastPasswordChangedDate,
   lastLockoutDate)
 {
     OpenId = openId;
 }
Esempio n. 2
0
        public static void CreateDatabase(Identifier claimedId, string friendlyId, string databaseName)
        {
            const string SqlFormat = @"
            {0}
            GO
            EXEC [dbo].[AddUser] 'admin', 'admin', '{1}', '{2}'
            GO
            ";
            var removeSnippets = new string[] { @"
            IF IS_SRVROLEMEMBER(N'sysadmin') = 1
            BEGIN
            IF EXISTS (SELECT 1
                   FROM   [master].[dbo].[sysdatabases]
                   WHERE  [name] = N'$(DatabaseName)')
            BEGIN
                EXECUTE sp_executesql N'ALTER DATABASE [$(DatabaseName)]
            SET HONOR_BROKER_PRIORITY OFF
            WITH ROLLBACK IMMEDIATE';
            END
            END
            ELSE
            BEGIN
            PRINT N'The database settings cannot be modified. You must be a SysAdmin to apply these settings.';
            END

            GO" };
            string databasePath = HttpContext.Current.Server.MapPath("~/App_Data/" + databaseName + ".mdf");
            StringBuilder schemaSqlBuilder = new StringBuilder();
            using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(DefaultNamespace + ".CreateDatabase.sql")))
            {
                schemaSqlBuilder.Append(sr.ReadToEnd());
            }
            foreach (string remove in removeSnippets)
            {
                schemaSqlBuilder.Replace(remove, string.Empty);
            }
            schemaSqlBuilder.Replace("$(Path1)", HttpContext.Current.Server.MapPath("~/App_Data/"));
            schemaSqlBuilder.Replace("WEBROOT", databasePath);
            schemaSqlBuilder.Replace("$(DatabaseName)", databaseName);

            string sql = string.Format(CultureInfo.InvariantCulture, SqlFormat, schemaSqlBuilder, claimedId, "Admin");

            var serverConnection = new ServerConnection(".\\sqlexpress");
            try
            {
                serverConnection.ExecuteNonQuery(sql);
            }
            finally
            {
                try
                {
                    var server = new Server(serverConnection);
                    server.DetachDatabase(databaseName, true);
                }
                catch (FailedOperationException)
                {
                }
                serverConnection.Disconnect();
            }
        }
Esempio n. 3
0
		/// <summary>
		/// Initializes a new instance of the <see cref="OpenIdClient"/> class.
		/// </summary>
		/// <param name="providerName">
		/// Name of the provider. 
		/// </param>
		/// <param name="providerIdentifier">
		/// The provider identifier, which is the usually the login url of the specified provider. 
		/// </param>
		public OpenIdClient(string providerName, Identifier providerIdentifier) {
			Requires.NotNullOrEmpty(providerName, "providerName");
			Requires.NotNull(providerIdentifier, "providerIdentifier");

			this.providerName = providerName;
			this.providerIdentifier = providerIdentifier;
		}
        private ActionResult LogOn(Identifier identifier)
        {
            //Remove the unnecessary portion of the identifier
            string steamIDString = identifier.ToString().Replace("http://steamcommunity.com/openid/id/", "");
            long steamId64 = long.Parse(steamIDString);

            using (var db = new SprayContext())
            {
                var user = db.Users.FirstOrDefault(x => x.SteamId == steamId64);

                SteamWebAPI.SteamAPISession session = new SteamWebAPI.SteamAPISession();
                session.accessToken = ""; /* CHANGEME - Steam Web API access token */
                var userInfo = session.GetUserInfo(steamId64.ToString());

                if (user == null)
                {
                    //Add the user if they're new
                    user = CreateUser(steamId64, db, userInfo);
                }
                else
                {
                    // Or update the relevant information
                    user.AvatarURI = userInfo.avatarUrl;
                    user.NickName = userInfo.nickname;
                    user.LastUpdated = DateTime.Now;
                }

                int recordsAffected = db.SaveChanges();
                FormsAuthentication.SetAuthCookie(steamId64.ToString(), true);
            }

            return RedirectToAction("Index", "Home");
        }
		public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy) {
			if (userSuppliedIdentifier == null) {
				throw new ArgumentNullException("userSuppliedIdentifier");
			}
			if (realm == null) {
				throw new ArgumentNullException("realm");
			}
			if (returnTo == null) {
				throw new ArgumentNullException("returnTo");
			}

			var requests = relyingParty.CreateRequests(userSuppliedIdentifier, realm, returnTo);

			foreach (IAuthenticationRequest request in requests) {
				// Ask for the user's email, not because we necessarily need it to do our work,
				// but so we can display something meaningful to the user as their "username"
				// when they log in with a PPID from Google, for example.
				request.AddExtension(new ClaimsRequest {
					Email = DemandLevel.Require,
					FullName = DemandLevel.Request,
					PolicyUrl = privacyPolicy,
				});

				yield return request;
			}
		}
Esempio n. 6
0
 /// <summary>
 /// Creates the open id request.
 /// </summary>
 /// <param name="identifier">The identifier.</param>
 /// <returns></returns>
 private IAuthenticationRequest CreateOpenIdRequest(Identifier identifier)
 {
     var request = openId.CreateRequest(identifier);
     var fetchRequest = CreateFetchRequest();
     request.AddExtension(fetchRequest);
     return request;
 }
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to discover services for.</param>
		/// <returns>A non-null sequence of services discovered for the identifier.</returns>
		public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) {
			Requires.NotNull(identifier, "identifier");

			IEnumerable<IdentifierDiscoveryResult> results = Enumerable.Empty<IdentifierDiscoveryResult>();
			foreach (var discoverer in this.DiscoveryServices) {
				bool abortDiscoveryChain;
				var discoveryResults = discoverer.Discover(identifier, this.host.WebRequestHandler, out abortDiscoveryChain).CacheGeneratedResults();
				results = results.Concat(discoveryResults);
				if (abortDiscoveryChain) {
					Logger.OpenId.InfoFormat("Further discovery on '{0}' was stopped by the {1} discovery service.", identifier, discoverer.GetType().Name);
					break;
				}
			}

			// If any OP Identifier service elements were found, we must not proceed
			// to use any Claimed Identifier services, per OpenID 2.0 sections 7.3.2.2 and 11.2.
			// For a discussion on this topic, see
			// http://groups.google.com/group/dotnetopenid/browse_thread/thread/4b5a8c6b2210f387/5e25910e4d2252c8
			// Sometimes the IIdentifierDiscoveryService will automatically filter this for us, but
			// just to be sure, we'll do it here as well.
			if (!this.host.SecuritySettings.AllowDualPurposeIdentifiers) {
				results = results.CacheGeneratedResults(); // avoid performing discovery repeatedly
				var opIdentifiers = results.Where(result => result.ClaimedIdentifier == result.Protocol.ClaimedIdentifierForOPIdentifier);
				var claimedIdentifiers = results.Where(result => result.ClaimedIdentifier != result.Protocol.ClaimedIdentifierForOPIdentifier);
				results = opIdentifiers.Any() ? opIdentifiers : claimedIdentifiers;
			}

			return results;
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="NoDiscoveryIdentifier"/> class.
        /// </summary>
        /// <param name="wrappedIdentifier">The ordinary Identifier whose discovery is being masked.</param>
        /// <param name="claimSsl">Whether this Identifier should claim to be SSL-secure, although no discovery will never generate service endpoints anyway.</param>
        internal NoDiscoveryIdentifier(Identifier wrappedIdentifier, bool claimSsl)
            : base(wrappedIdentifier.OriginalString, claimSsl)
        {
            Contract.Requires(wrappedIdentifier != null);
            ErrorUtilities.VerifyArgumentNotNull(wrappedIdentifier, "wrappedIdentifier");

            this.wrappedIdentifier = wrappedIdentifier;
        }
Esempio n. 9
0
		internal override bool TryRequireSsl(out Identifier secureIdentifier) {
			// We take special care to make our wrapped identifier secure, but still
			// return a mocked (secure) identifier.
			Identifier secureWrappedIdentifier;
			bool result = this.wrappedIdentifier.TryRequireSsl(out secureWrappedIdentifier);
			secureIdentifier = new MockIdentifier(secureWrappedIdentifier, this.mockHttpRequest, this.endpoints);
			return result;
		}
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to perform discovery on.</param>
		/// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
		/// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
		/// <returns>
		/// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
		/// </returns>
		public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
			abortDiscoveryChain = false;
			var xriIdentifier = identifier as XriIdentifier;
			if (xriIdentifier == null) {
				return Enumerable.Empty<IdentifierDiscoveryResult>();
			}

			return DownloadXrds(xriIdentifier, requestHandler).XrdElements.CreateServiceEndpoints(xriIdentifier);
		}
		/// <summary>
		/// Generates OpenID Providers that can authenticate using directed identity.
		/// </summary>
		/// <param name="xrds">The XrdsDocument instance to use in this process.</param>
		/// <param name="opIdentifier">The OP Identifier entered (and resolved) by the user.  Essentially the user-supplied identifier.</param>
		/// <returns>A sequence of the providers that can offer directed identity services.</returns>
		private static IEnumerable<IdentifierDiscoveryResult> GenerateOPIdentifierServiceEndpoints(this IEnumerable<XrdElement> xrds, Identifier opIdentifier) {
			Requires.NotNull(xrds, "xrds");
			Requires.NotNull(opIdentifier, "opIdentifier");
			return from service in xrds.FindOPIdentifierServices()
				   from uri in service.UriElements
				   let protocol = Protocol.FindBestVersion(p => p.OPIdentifierServiceTypeURI, service.TypeElementUris)
				   let providerDescription = new ProviderEndpointDescription(uri.Uri, service.TypeElementUris)
				   select IdentifierDiscoveryResult.CreateForProviderIdentifier(opIdentifier, providerDescription, service.Priority, uri.Priority);
		}
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to perform discovery on.</param>
		/// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
		/// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
		/// <returns>
		/// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
		/// </returns>
		public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
			var mockIdentifier = identifier as MockIdentifier;
			if (mockIdentifier == null) {
				abortDiscoveryChain = false;
				return Enumerable.Empty<IdentifierDiscoveryResult>();
			}

			abortDiscoveryChain = true;
			return mockIdentifier.DiscoveryEndpoints;
		}
Esempio n. 13
0
        public static ActionResult SendRequest(OpenIdRelyingParty openid, Identifier openIdIdentifier)
        {
            Logger.Info("Sending request to the open id provider");

            var req = openid.CreateRequest(openIdIdentifier);

            var fetch = new FetchRequest();
            fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
            fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.Alias, true));
            req.AddExtension(fetch);
            return req.RedirectingResponse.AsActionResult();
        }
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to perform discovery on.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
		/// </returns>
		public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) {
			Requires.NotNull(identifier, "identifier");
			Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired);
			cancellationToken.ThrowIfCancellationRequested();

			var uriIdentifier = identifier as UriIdentifier;
			if (uriIdentifier == null) {
				return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>());
			}

			var endpoints = new List<IdentifierDiscoveryResult>();

			// Attempt YADIS discovery
			DiscoveryResult yadisResult = await Yadis.DiscoverAsync(this.HostFactories, uriIdentifier, identifier.IsDiscoverySecureEndToEnd, cancellationToken);
			cancellationToken.ThrowIfCancellationRequested();
			if (yadisResult != null) {
				if (yadisResult.IsXrds) {
					try {
						XrdsDocument xrds = new XrdsDocument(yadisResult.ResponseText);
						var xrdsEndpoints = xrds.XrdElements.CreateServiceEndpoints(yadisResult.NormalizedUri, uriIdentifier);

						// Filter out insecure endpoints if high security is required.
						if (uriIdentifier.IsDiscoverySecureEndToEnd) {
							xrdsEndpoints = xrdsEndpoints.Where(se => se.ProviderEndpoint.IsTransportSecure());
						}
						endpoints.AddRange(xrdsEndpoints);
					} catch (XmlException ex) {
						Logger.Yadis.Error("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
					}
				}

				// Failing YADIS discovery of an XRDS document, we try HTML discovery.
				if (endpoints.Count == 0) {
					await yadisResult.TryRevertToHtmlResponseAsync();
					var htmlEndpoints = new List<IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
					if (htmlEndpoints.Any()) {
						Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
						Logger.Yadis.Debug(htmlEndpoints.ToStringDeferred(true));
						endpoints.AddRange(htmlEndpoints.Where(ep => !uriIdentifier.IsDiscoverySecureEndToEnd || ep.ProviderEndpoint.IsTransportSecure()));
						if (endpoints.Count == 0) {
							Logger.Yadis.Info("No HTML discovered endpoints met the security requirements.");
						}
					} else {
						Logger.Yadis.Debug("HTML discovery failed to find any endpoints.");
					}
				} else {
					Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
				}
			}

			return new IdentifierDiscoveryServiceResult(endpoints);
		}
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to perform discovery on.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
		/// </returns>
		public async Task<IdentifierDiscoveryServiceResult> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken) {
			Requires.NotNull(identifier, "identifier");
			Verify.Operation(this.HostFactories != null, Strings.HostFactoriesRequired);

			var xriIdentifier = identifier as XriIdentifier;
			if (xriIdentifier == null) {
				return new IdentifierDiscoveryServiceResult(Enumerable.Empty<IdentifierDiscoveryResult>());
			}

			var xrds = await DownloadXrdsAsync(xriIdentifier, this.HostFactories, cancellationToken);
			var endpoints = xrds.XrdElements.CreateServiceEndpoints(xriIdentifier);
			return new IdentifierDiscoveryServiceResult(endpoints);
		}
Esempio n. 16
0
		public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints)
			: base(wrappedIdentifier.OriginalString, false) {
			Requires.NotNull(wrappedIdentifier, "wrappedIdentifier");
			Requires.NotNull(mockHttpRequest, "mockHttpRequest");
			Requires.NotNull(endpoints, "endpoints");

			this.wrappedIdentifier = wrappedIdentifier;
			this.endpoints = endpoints;
			this.mockHttpRequest = mockHttpRequest;

			// Register a mock HTTP response to enable discovery of this identifier within the RP
			// without having to host an ASP.NET site within the test.
			mockHttpRequest.RegisterMockXrdsResponse(new Uri(wrappedIdentifier.ToString()), endpoints);
		}
		/// <summary>
		/// Gets the salt to use for generating an anonymous identifier for a given OP local identifier.
		/// </summary>
		/// <param name="localIdentifier">The OP local identifier.</param>
		/// <returns>The salt to use in the hash.</returns>
		/// <remarks>
		/// It is important that this method always return the same value for a given
		/// <paramref name="localIdentifier"/>.
		/// New salts can be generated for local identifiers without previously assigned salt
		/// values by calling <see cref="CreateSalt"/> or by a custom method.
		/// </remarks>
		protected override byte[] GetHashSaltForLocalIdentifier(Identifier localIdentifier) {
			// This is just a sample with no database... a real web app MUST return 
			// a reasonable salt here and have that salt be persistent for each user.
			var membership = (ReadOnlyXmlMembershipProvider)Membership.Provider;
			string username = User.GetUserFromClaimedIdentifier(new Uri(localIdentifier));
			string salt = membership.GetSalt(username);
			return Convert.FromBase64String(salt);

			// If users were encountered without a salt, one could be generated like this,
			// and would also need to be saved to the user's account.
			//// var newSalt = AnonymousIdentifierProviderBase.GetNewSalt(5);
			//// user.Salt = newSalt;
			//// return newSalt;
		}
Esempio n. 18
0
		public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<IdentifierDiscoveryResult> endpoints)
			: base(wrappedIdentifier.OriginalString, false) {
			Contract.Requires<ArgumentNullException>(wrappedIdentifier != null);
			Contract.Requires<ArgumentNullException>(mockHttpRequest != null);
			Contract.Requires<ArgumentNullException>(endpoints != null);

			this.wrappedIdentifier = wrappedIdentifier;
			this.endpoints = endpoints;
			this.mockHttpRequest = mockHttpRequest;

			// Register a mock HTTP response to enable discovery of this identifier within the RP
			// without having to host an ASP.NET site within the test.
			mockHttpRequest.RegisterMockXrdsResponse(new Uri(wrappedIdentifier.ToString()), endpoints);
		}
Esempio n. 19
0
        public MockIdentifier(Identifier wrappedIdentifier, MockHttpRequest mockHttpRequest, IEnumerable<ServiceEndpoint> endpoints)
            : base(false)
        {
            ErrorUtilities.VerifyArgumentNotNull(wrappedIdentifier, "wrappedIdentifier");
            ErrorUtilities.VerifyArgumentNotNull(mockHttpRequest, "mockHttpRequest");
            ErrorUtilities.VerifyArgumentNotNull(endpoints, "endpoints");

            this.wrappedIdentifier = wrappedIdentifier;
            this.endpoints = endpoints;
            this.mockHttpRequest = mockHttpRequest;

            // Register a mock HTTP response to enable discovery of this identifier within the RP
            // without having to host an ASP.NET site within the test.
            mockHttpRequest.RegisterMockXrdsResponse(new Uri(wrappedIdentifier.ToString()), endpoints);
        }
Esempio n. 20
0
		/// <summary>
		/// Performs discovery on the specified identifier.
		/// </summary>
		/// <param name="identifier">The identifier to perform discovery on.</param>
		/// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
		/// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
		/// <returns>
		/// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
		/// </returns>
		public IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain) {
			abortDiscoveryChain = false;
			var uriIdentifier = identifier as UriIdentifier;
			if (uriIdentifier == null) {
				return Enumerable.Empty<IdentifierDiscoveryResult>();
			}

			var endpoints = new List<IdentifierDiscoveryResult>();

			// Attempt YADIS discovery
			DiscoveryResult yadisResult = Yadis.Discover(requestHandler, uriIdentifier, identifier.IsDiscoverySecureEndToEnd);
			if (yadisResult != null) {
				if (yadisResult.IsXrds) {
					try {
						XrdsDocument xrds = new XrdsDocument(yadisResult.ResponseText);
						var xrdsEndpoints = xrds.XrdElements.CreateServiceEndpoints(yadisResult.NormalizedUri, uriIdentifier);

						// Filter out insecure endpoints if high security is required.
						if (uriIdentifier.IsDiscoverySecureEndToEnd) {
							xrdsEndpoints = xrdsEndpoints.Where(se => se.ProviderEndpoint.IsTransportSecure());
						}
						endpoints.AddRange(xrdsEndpoints);
					} catch (XmlException ex) {
						Logger.Yadis.Error("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
					}
				}

				// Failing YADIS discovery of an XRDS document, we try HTML discovery.
				if (endpoints.Count == 0) {
					yadisResult.TryRevertToHtmlResponse();
					var htmlEndpoints = new List<IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
					if (htmlEndpoints.Any()) {
						Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
						Logger.Yadis.Debug(htmlEndpoints.ToStringDeferred(true));
						endpoints.AddRange(htmlEndpoints.Where(ep => !uriIdentifier.IsDiscoverySecureEndToEnd || ep.ProviderEndpoint.IsTransportSecure()));
						if (endpoints.Count == 0) {
							Logger.Yadis.Info("No HTML discovered endpoints met the security requirements.");
						}
					} else {
						Logger.Yadis.Debug("HTML discovery failed to find any endpoints.");
					}
				} else {
					Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
				}
			}
			return endpoints;
		}
		public async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) {
			Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
			Requires.NotNull(realm, "realm");
			Requires.NotNull(returnTo, "returnTo");

			var requests = (await relyingParty.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, cancellationToken)).ToList();

			foreach (IAuthenticationRequest request in requests) {
				// Ask for the user's email, not because we necessarily need it to do our work,
				// but so we can display something meaningful to the user as their "username"
				// when they log in with a PPID from Google, for example.
				request.AddExtension(new ClaimsRequest {
					Email = DemandLevel.Require,
					FullName = DemandLevel.Request,
					PolicyUrl = privacyPolicy,
				});
			}

			return requests;
		}
Esempio n. 22
0
        public static IAuthenticationRequest GetRedirectActionRequest(Identifier provider)
        {
            var openid = new OpenIdRelyingParty();
            var request = openid.CreateRequest(Identifier.Parse(provider));

            var fr = new FetchRequest();
            fr.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            fr.Attributes.AddRequired(WellKnownAttributes.Name.First);
            fr.Attributes.AddRequired(WellKnownAttributes.Name.Last);
            request.AddExtension(fr);

            // Require some additional data
            request.AddExtension(new ClaimsRequest
            {
                Email = DemandLevel.Require,
                FullName = DemandLevel.Require,
                Nickname = DemandLevel.Require
            });

            return request;
        }
Esempio n. 23
0
 public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy)
 {
     return this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy).First();
 }
Esempio n. 24
0
		internal Task<IEnumerable<IdentifierDiscoveryResult>> DiscoverAsync(Identifier identifier, CancellationToken cancellationToken = default(CancellationToken)) {
			var rp = this.CreateRelyingParty(true);
			return rp.DiscoverAsync(identifier, cancellationToken);
		}
Esempio n. 25
0
		internal IEnumerable<IdentifierDiscoveryResult> Discover(Identifier identifier) {
			var rp = this.CreateRelyingParty(true);
			rp.Channel.WebRequestHandler = this.RequestHandler;
			return rp.Discover(identifier);
		}
Esempio n. 26
0
 public ActionResult AjaxDiscovery(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy)
 {
     return relyingParty.AsAjaxDiscoveryResult(
         this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy)).AsActionResult();
 }
		private void DiscoverHtml(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, bool useRedirect) {
			this.Discover("/Discovery/htmldiscovery/" + page, version, expectedLocalId, providerEndpoint, false, useRedirect);
		}
		private void DiscoverHtml(string scenario, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) {
			string page = scenario + ".html";
			this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, false);
			this.DiscoverHtml(page, version, expectedLocalId, providerEndpoint, true);
		}
		private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint, WebHeaderCollection headers) {
			if (!page.Contains(".")) {
				page += ".xml";
			}
			this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, false, headers);
			this.Discover("/Discovery/xrdsdiscovery/" + page, version, expectedLocalId, providerEndpoint, true, true, headers);
		}
		private void DiscoverXrds(string page, ProtocolVersion version, Identifier expectedLocalId, string providerEndpoint) {
			this.DiscoverXrds(page, version, expectedLocalId, providerEndpoint, null);
		}
Esempio n. 31
0
        /// <summary>
        /// Performs discovery on the specified identifier.
        /// </summary>
        /// <param name="identifier">The identifier to perform discovery on.</param>
        /// <param name="requestHandler">The means to place outgoing HTTP requests.</param>
        /// <param name="abortDiscoveryChain">if set to <c>true</c>, no further discovery services will be called for this identifier.</param>
        /// <returns>
        /// A sequence of service endpoints yielded by discovery.  Must not be null, but may be empty.
        /// </returns>
        public IEnumerable <IdentifierDiscoveryResult> Discover(Identifier identifier, IDirectWebRequestHandler requestHandler, out bool abortDiscoveryChain)
        {
            abortDiscoveryChain = false;
            var uriIdentifier = identifier as UriIdentifier;

            if (uriIdentifier == null)
            {
                return(Enumerable.Empty <IdentifierDiscoveryResult>());
            }

            var endpoints = new List <IdentifierDiscoveryResult>();

            // Attempt YADIS discovery
            DiscoveryResult yadisResult = Yadis.Discover(requestHandler, uriIdentifier, identifier.IsDiscoverySecureEndToEnd);

            if (yadisResult != null)
            {
                if (yadisResult.IsXrds)
                {
                    try {
                        XrdsDocument xrds          = new XrdsDocument(yadisResult.ResponseText);
                        var          xrdsEndpoints = xrds.XrdElements.CreateServiceEndpoints(yadisResult.NormalizedUri, uriIdentifier);

                        // Filter out insecure endpoints if high security is required.
                        if (uriIdentifier.IsDiscoverySecureEndToEnd)
                        {
                            xrdsEndpoints = xrdsEndpoints.Where(se => se.ProviderEndpoint.IsTransportSecure());
                        }
                        endpoints.AddRange(xrdsEndpoints);
                    } catch (XmlException ex) {
                        Logger.Yadis.Error("Error while parsing the XRDS document.  Falling back to HTML discovery.", ex);
                    }
                }

                // Failing YADIS discovery of an XRDS document, we try HTML discovery.
                if (endpoints.Count == 0)
                {
                    yadisResult.TryRevertToHtmlResponse();
                    var htmlEndpoints = new List <IdentifierDiscoveryResult>(DiscoverFromHtml(yadisResult.NormalizedUri, uriIdentifier, yadisResult.ResponseText));
                    if (htmlEndpoints.Any())
                    {
                        Logger.Yadis.DebugFormat("Total services discovered in HTML: {0}", htmlEndpoints.Count);
                        Logger.Yadis.Debug(htmlEndpoints.ToStringDeferred(true));
                        endpoints.AddRange(htmlEndpoints.Where(ep => !uriIdentifier.IsDiscoverySecureEndToEnd || ep.ProviderEndpoint.IsTransportSecure()));
                        if (endpoints.Count == 0)
                        {
                            Logger.Yadis.Info("No HTML discovered endpoints met the security requirements.");
                        }
                    }
                    else
                    {
                        Logger.Yadis.Debug("HTML discovery failed to find any endpoints.");
                    }
                }
                else
                {
                    Logger.Yadis.Debug("Skipping HTML discovery because XRDS contained service endpoints.");
                }
            }
            return(endpoints);
        }
Esempio n. 32
0
 /// <summary>
 /// Converts a given identifier to its secure equivalent.
 /// UriIdentifiers originally created with an implied HTTP scheme change to HTTPS.
 /// Discovery is made to require SSL for the entire resolution process.
 /// </summary>
 /// <param name="secureIdentifier">
 /// The newly created secure identifier.
 /// If the conversion fails, <paramref name="secureIdentifier"/> retains
 /// <i>this</i> identifiers identity, but will never discover any endpoints.
 /// </param>
 /// <returns>
 /// True if the secure conversion was successful.
 /// False if the Identifier was originally created with an explicit HTTP scheme.
 /// </returns>
 internal abstract bool TryRequireSsl(out Identifier secureIdentifier);
Esempio n. 33
0
 [ContractVerification(false)]         // bugs/limitations in CC static analysis
 internal override bool TryRequireSsl(out Identifier secureIdentifier)
 {
     secureIdentifier = IsDiscoverySecureEndToEnd ? this : new XriIdentifier(this, true);
     return(true);
 }