public void MinimumOPVersion20WithDeceptiveEndpointRealizedAtAuthentication()
        {
            // Create an identifier that claims to have a 2.0 OP endpoint.
            MockIdentifier id = TestSupport.GetMockIdentifier(TestSupport.Scenarios.AutoApproval, ProtocolVersion.V20);

            var rp = TestSupport.CreateRelyingParty(null, null);

            IAuthenticationRequest req = rp.CreateRequest(id, TestSupport.Realm, TestSupport.ReturnTo);
            IResponse providerResponse = TestSupport.CreateProviderResponseToRequest(req, opReq => {
                opReq.IsAuthenticated = true;
            });

            var opAuthWebResponse = (Response)providerResponse;
            var opAuthResponse    = (DotNetOpenId.Provider.EncodableResponse)opAuthWebResponse.EncodableMessage;
            var rp2 = TestSupport.CreateRelyingParty(null, opAuthResponse.RedirectUrl,
                                                     opAuthResponse.EncodedFields.ToNameValueCollection());

            rp2.Settings.MinimumRequiredOpenIdVersion = ProtocolVersion.V20;
            // Rig an intercept between the provider and RP to make our own Provider LOOK like a 1.x provider.
            var sniffer = new DirectMessageSniffWrapper(rp2.DirectMessageChannel);

            rp2.DirectMessageChannel = sniffer;
            sniffer.Receiving       += (endpoint, fields) => {
                fields.Remove(Protocol.v20.openidnp.ns);
            };
            var resp = rp2.Response;

            Assert.AreEqual(AuthenticationStatus.Failed, resp.Status, "Authentication should have failed since OP is really a 1.x OP masquerading as a 2.0 OP.");
        }
        protected void loginButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
            {
                return; // don't login if custom validation failed.
            }
            try
            {
                using (OpenIdRelyingParty openid = this.createRelyingParty())
                {
                    IAuthenticationRequest request = openid.CreateRequest(this.openIdBox.Text);
                    // Here is where we add the OpenID+OAuth Extension
                    request.AddExtension(new OAuthRequest(Constants.ConsumerKey));

                    // Send your visitor to their Provider for authentication.
                    request.RedirectToProvider();
                }
            }
            catch (ProtocolException ex)
            {
                // The user probably entered an Identifier that
                // was not a valid OpenID endpoint.
                this.openidValidator.Text    = ex.Message;
                this.openidValidator.IsValid = false;
            }
            catch (WebException ex)
            {
                // The user probably entered an Identifier that
                // was not a valid OpenID endpoint.
                this.openidValidator.Text    = ex.Message;
                this.openidValidator.IsValid = false;
            }
        }
Example #3
0
    protected void cmdLoginOpenId_Click(object sender, EventArgs e)
    {
        try {
            using (OpenIdRelyingParty openid = new OpenIdRelyingParty()) {
                var realm     = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped) + "/";
                var return_to = Request.Url.StripQueryArgumentsWithPrefix("auto-redirect-openid");

                if (!string.IsNullOrEmpty(txtReferrer.Value) && !return_to.Query.Contains("referrer"))
                {
                    return_to = new Uri(return_to.ToString() + (string.IsNullOrEmpty(return_to.Query) ? "?" : "&") + "referrer=" + HttpUtility.UrlEncode(txtReferrer.Value));
                }

                IAuthenticationRequest request = openid.CreateRequest(Configuration.OpenIdProvider, realm, return_to);

                var fetch = new FetchRequest();
                fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                request.AddExtension(fetch);

                // Send your visitor to their Provider for authentication.
                request.RedirectToProvider();
            }
        } catch (ProtocolException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            lblMessage.Text = Utils.FormatException(ex);
        }
    }
Example #4
0
 protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
 {
     FetchRequest extension = new FetchRequest();
     extension.Attributes.AddRequired("http://axschema.org/contact/email");
     extension.Attributes.AddRequired("http://axschema.org/namePerson");
     request.AddExtension(extension);
 }
		/// <summary>
		/// Initializes a new instance of the <see cref="OpenIdEventArgs"/> class
		/// with minimal information of an incomplete or failed authentication attempt.
		/// </summary>
		/// <param name="request">The outgoing authentication request.</param>
		internal OpenIdEventArgs(IAuthenticationRequest request) {
			Requires.NotNull(request, "request");

			this.Request = request;
			this.ClaimedIdentifier = request.ClaimedIdentifier;
			this.IsDirectedIdentity = request.IsDirectedIdentity;
		}
		/// <summary>
		/// Processes an authentication request by a popup window.
		/// </summary>
		/// <param name="userIdentityPageBase">The base URI upon which user identity pages are created.</param>
		/// <param name="request">The incoming authentication request.</param>
		/// <param name="cancellationToken">The cancellation token.</param>
		/// <returns>
		/// A task that completes with the asynchronous operation.
		/// </returns>
		internal static async Task ProcessAuthenticationAsync(Uri userIdentityPageBase, IAuthenticationRequest request, CancellationToken cancellationToken) {
			Requires.NotNull(userIdentityPageBase, "userIdentityPageBase");
			Requires.NotNull(request, "request");

			var window = new CheckIdWindow(userIdentityPageBase, request);

			IHostFactories hostFactories = new DefaultOpenIdHostFactories();
			bool isRPDiscoverable = await request.IsReturnUrlDiscoverableAsync(hostFactories, cancellationToken) == RelyingPartyDiscoveryResult.Success;
			window.discoverableYesLabel.Visibility = isRPDiscoverable ? Visibility.Visible : Visibility.Collapsed;
			window.discoverableNoLabel.Visibility = isRPDiscoverable ? Visibility.Collapsed : Visibility.Visible;

			bool? result = window.ShowDialog();

			// If the user pressed Esc or cancel, just send a negative assertion.
			if (!result.HasValue || !result.Value) {
				request.IsAuthenticated = false;
				return;
			}

			request.IsAuthenticated = window.tabControl1.SelectedItem == window.positiveTab;
			if (request.IsAuthenticated.Value) {
				request.ClaimedIdentifier = window.claimedIdentifierBox.Text;
				request.LocalIdentifier = window.localIdentifierBox.Text;
			}
		}
        public ActionResult OpenID(string openid_identifier)
        {
            var openid = new OpenIdRelyingParty();
            IAuthenticationRequest request = openid.CreateRequest(Identifier.Parse(openid_identifier));

            return(request.RedirectingResponse.AsActionResult());
        }
Example #8
0
        private IBasicLoginAttempt BuildRequest(string parentHref, IAuthenticationRequest request)
        {
            var username = request.Principals.Nullable() ?? string.Empty;
            var password = request.Credentials.Nullable() ?? string.Empty;
            var value    = $"{username}:{password}";

            value = Base64.Encode(value, Encoding.UTF8);

            var attempt = this.dataStore.Instantiate <IBasicLoginAttempt>();

            attempt.SetType("basic");
            attempt.SetValue(value);

            if (request.AccountStore != null)
            {
                attempt.SetAccountStore(request.AccountStore);
            }

            var supportsNameKey = request as IHasOrganizationNameKey;

            if (supportsNameKey != null && !string.IsNullOrEmpty(supportsNameKey.OrganizationNameKey))
            {
                attempt.SetAccountStore(supportsNameKey.OrganizationNameKey);
            }

            return(attempt);
        }
Example #9
0
        public ActionResult OpenIdLogin(string openidIdentifier)
        {
            if (!Identifier.IsValid(openidIdentifier))
            {
                ModelState.AddModelError("loginIdentifier",
                                         "The specified login identifier is invalid");

                return(View("LogOn"));
            }
            else
            {
                var openid = new OpenIdRelyingParty();
                IAuthenticationRequest request = openid.CreateRequest(
                    Identifier.Parse(openidIdentifier));

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

                return(request.RedirectingResponse.AsActionResult());
            }
        }
Example #10
0
        /// <summary>
        /// Handles the Click event of the loginButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void LoginButton_Click(object sender, EventArgs e)
        {
            this.Page.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                if (!this.Page.IsValid)
                {
                    return;
                }

                var authenticationRequests     = await this.CreateRequestsAsync(CancellationToken.None);
                IAuthenticationRequest request = authenticationRequests.FirstOrDefault();
                if (request != null)
                {
                    await this.LogOnAsync(request, CancellationToken.None);
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.FailedMessageText))
                    {
                        this.errorLabel.Text = string.Format(
                            CultureInfo.CurrentCulture, this.FailedMessageText, OpenIdStrings.OpenIdEndpointNotFound);
                        this.errorLabel.Visible = true;
                    }
                }
            }));
        }
Example #11
0
		private void prepareRequest(IAuthenticationRequest request) {
			// Collect the PAPE policies requested by the user.
			List<string> policies = new List<string>();
			foreach (ListItem item in this.papePolicies.Items) {
				if (item.Selected) {
					policies.Add(item.Value);
				}
			}

			// Add the PAPE extension if any policy was requested.
			var pape = new PolicyRequest();
			if (policies.Count > 0) {
				foreach (string policy in policies) {
					pape.PreferredPolicies.Add(policy);
				}
			}

			if (this.maxAuthTimeBox.Text.Length > 0) {
				pape.MaximumAuthenticationAge = TimeSpan.FromSeconds(double.Parse(this.maxAuthTimeBox.Text));
			}

			if (pape.PreferredPolicies.Count > 0 || pape.MaximumAuthenticationAge.HasValue) {
				request.AddExtension(pape);
			}
		}
Example #12
0
        private void AddAttributeExchangeExtensions(IAuthenticationRequest auth)
        {
            // Try to use OpenId 2.0's attribute exchange
            var fetch = new FetchRequest();

            //Technically, http://axschema.org/... are "standard", but we'll still find these in the wild
            fetch.Attributes.Add(new AttributeRequest("http://schema.openid.net/namePerson", false));
            fetch.Attributes.Add(new AttributeRequest("http://schema.openid.net/contact/email", false));

            fetch.Attributes.AddRequired("http://axschema.org/contact/country/home");
            fetch.Attributes.AddRequired("http://axschema.org/namePerson/first");
            fetch.Attributes.AddRequired("http://axschema.org/namePerson/last");
            fetch.Attributes.AddRequired("http://axschema.org/pref/language");
            fetch.Attributes.AddRequired("http://schemas.openid.net/ax/api/user_id");

            //Standard compliant AX schema
            fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName, false));

            //For... no good reason, really, google OpenId requires you "require" an e-mail address to get it
            bool requireEmail = auth.Provider.Uri.AbsoluteUri.Contains(".google.com");

            fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, requireEmail));

            auth.AddExtension(fetch);
        }
        public ActionResult SteamLogin()
        {
            //Steam authentication code gotten from: https://stackoverflow.com/questions/20845146/steam-login-authentication-c-sharp
            var openid   = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response != null)
            {
                switch (response.Status)
                {
                case AuthenticationStatus.Authenticated:
                    // do success
                    var responseURI = response.ClaimedIdentifier.ToString();
                    Session["SteamID"] = responseURI.Split('/').Last();
                    //"http://steamcommunity.com/openid/id/76561197969877387"
                    // last part is steam user id
                    return(RedirectToAction("Friends"));

                case AuthenticationStatus.Canceled:
                case AuthenticationStatus.Failed:
                    // do fail
                    break;
                }
            }
            else
            {
                using (OpenIdRelyingParty openidd = new OpenIdRelyingParty())
                {
                    IAuthenticationRequest request = openidd.CreateRequest("http://steamcommunity.com/openid");
                    request.RedirectToProvider();
                }
            }

            return(View());
        }
Example #14
0
        private void prepareRequest(IAuthenticationRequest request)
        {
            // Collect the PAPE policies requested by the user.
            List <string> policies = new List <string>();

            foreach (ListItem item in this.papePolicies.Items)
            {
                if (item.Selected)
                {
                    policies.Add(item.Value);
                }
            }

            // Add the PAPE extension if any policy was requested.
            if (policies.Count > 0)
            {
                var pape = new PolicyRequest();
                foreach (string policy in policies)
                {
                    pape.PreferredPolicies.Add(policy);
                }

                request.AddExtension(pape);
            }
        }
Example #15
0
        protected void PerformGoogleAuthentication()
        {
            using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
            {
                //Set up the callback URL
                Uri callbackUrl = new Uri(
                    String.Format("{0}{1}{2}{3}?{4}=true",
                                  (Request.IsSecureConnection) ? "https://" : "http://",
                                  Request.Url.Host,
                                  (Request.Url.IsDefaultPort) ?
                                  String.Empty : String.Concat(":", Request.Url.Port),
                                  Page.ResolveUrl(AUTHENTICATION_ENDPOINT),
                                  CALLBACK_PARAMETER
                                  ));

                //Set up request object for Google Authentication
                IAuthenticationRequest request =
                    openid.CreateRequest(GOOGLE_OAUTH_ENDPOINT,
                                         DotNetOpenAuth.OpenId.Realm.AutoDetect, callbackUrl);


                //Let's tell Google, what we want to have from the user:
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                request.AddExtension(fetch);

                //Redirect to Google Authentication
                request.RedirectToProvider();
            }
        }
Example #16
0
        private IAuthenticationRequest GetGoogleRequest()
        {
            // Google requires that the realm and consumer key be equal,
            // so we constrain the realm to match the realm in the web.config file.
            // This does mean that the return_to URL must also fall under the key,
            // which means this sample will only work on a public web site
            // that is properly registered with Google.
            // We will customize the realm to use http or https based on what the
            // return_to URL will be (which will be this page).
            Realm realm = Request.Url.Scheme + Uri.SchemeDelimiter + Global.GoogleTokenManager.ConsumerKey + "/";
            IAuthenticationRequest authReq = relyingParty.CreateRequest(GoogleOPIdentifier, realm);

            // Prepare the OAuth extension
            string scope = GoogleConsumer.GetScopeUri(GoogleConsumer.Applications.Contacts);

            Global.GoogleWebConsumer.AttachAuthorizationRequest(authReq, scope);

            // We also want the user's email address
            var fetch = new FetchRequest();

            fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            authReq.AddExtension(fetch);

            return(authReq);
        }
Example #17
0
        /// <summary>
        /// Make the request to the OpenID provider.
        /// </summary>
        /// <param name="openid_identifier">Identifier to send the request to.</param>
        /// <returns></returns>
        private ActionResult SendRequestToOpenIdProvider(string identifier)
        {
            Identifier id;

            if (Identifier.TryParse(identifier, out id))
            {
                try
                {
                    IAuthenticationRequest request = openId.CreateRequest(Identifier.Parse(identifier));

                    // Next we have to specify which data we want
                    request.AddExtension(new ClaimsRequest
                    {
                        Email    = DemandLevel.Require,
                        Nickname = DemandLevel.Require,
                        FullName = DemandLevel.Request
                    });

                    // Finally we'll make a request to the OpenID provider
                    return(request.RedirectingResponse.AsActionResult());
                }
                catch (ProtocolException e)
                {
                    ModelState.AddModelError("openid_identifier", e);
                }
            }
            else
            {
                ModelState.AddModelError("openid_identifier", "Invalid identifier");
            }

            return(View());
        }
Example #18
0
 private void CreateOpenIDRequestAndRedirect(string openIdUrl)
 {
     try
     {
         using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
         {
             IAuthenticationRequest request = openid.CreateRequest(openIdUrl);
             // This is where you would add any OpenID extensions you wanted
             // to include in the authentication request.
             request.AddExtension(new ClaimsRequest
             {
                 //Country = DemandLevel.Request,
                 //Email = DemandLevel.Request,
                 //Gender = DemandLevel.Require,
                 //PostalCode = DemandLevel.Require,
                 //TimeZone = DemandLevel.Require,
             });                          // Send your visitor to their Provider for authentication.
             request.RedirectToProvider();
         }
     }
     catch (ProtocolException ex)
     {
         // The user probably entered an Identifier that
         // was not a valid OpenID endpoint.
         this.openidValidator.Text    = ex.Message;
         this.openidValidator.IsValid = false;
     }
 }
Example #19
0
    private void prepareRequest(IAuthenticationRequest request)
    {
        // Setup is the default for the login control.  But the user may have checked the box to override that.
        request.Mode = immediateCheckBox.Checked ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;

        // Collect the PAPE policies requested by the user.
        List <string> policies = new List <string>();

        foreach (ListItem item in papePolicies.Items)
        {
            if (item.Selected)
            {
                policies.Add(item.Value);
            }
        }

        // Add the PAPE extension if any policy was requested.
        if (policies.Count > 0)
        {
            var pape = new PolicyRequest();
            foreach (string policy in policies)
            {
                pape.PreferredPolicies.Add(policy);
            }

            request.AddExtension(pape);
        }
    }
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckIdWindow"/> class.
        /// </summary>
        /// <param name="provider">The OpenID Provider host.</param>
        /// <param name="request">The incoming authentication request.</param>
        private CheckIdWindow(HostedProvider provider, IAuthenticationRequest request)
        {
            Contract.Requires(request != null);

            InitializeComponent();

            // Initialize the window with appropriate values.
            this.realmLabel.Content            = request.Realm;
            this.immediateModeLabel.Visibility = request.Immediate ? Visibility.Visible : Visibility.Collapsed;
            this.setupModeLabel.Visibility     = request.Immediate ? Visibility.Collapsed : Visibility.Visible;

            bool isRPDiscoverable = request.IsReturnUrlDiscoverable(provider.Provider) == RelyingPartyDiscoveryResult.Success;

            this.discoverableYesLabel.Visibility = isRPDiscoverable ? Visibility.Visible : Visibility.Collapsed;
            this.discoverableNoLabel.Visibility  = isRPDiscoverable ? Visibility.Collapsed : Visibility.Visible;

            if (request.IsDirectedIdentity)
            {
                this.claimedIdentifierBox.Text = provider.UserIdentityPageBase.AbsoluteUri;
                this.localIdentifierBox.Text   = provider.UserIdentityPageBase.AbsoluteUri;
            }
            else
            {
                this.claimedIdentifierBox.Text = request.ClaimedIdentifier;
                this.localIdentifierBox.Text   = request.LocalIdentifier;
            }
        }
        public ActionResult Provider()
        {
            IRequest request = OpenIdProvider.GetRequest();
            if (request != null) {
                var authRequest = request as IAuthenticationRequest;
                if (authRequest != null) {
                    PendingAuthenticationRequest = authRequest;
                    if (authRequest.IsReturnUrlDiscoverable(OpenIdProvider) == RelyingPartyDiscoveryResult.Success &&
                        User.Identity.IsAuthenticated &&
                        (authRequest.IsDirectedIdentity || this.UserControlsIdentifier(authRequest))) {
                        return this.SendAssertion();
                    } else {
                        return RedirectToAction("LogOn", "Account", new { returnUrl = Url.Action("SendAssertion") });
                    }
                }

                if (request.IsResponseReady) {
                    return OpenIdProvider.PrepareResponse(request).AsActionResult();
                } else {
                    return RedirectToAction("LogOn", "Account");
                }
            } else {
                return View();
            }
        }
 protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
 {
     var fetchRequest = new FetchRequest();
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
     request.AddExtension(fetchRequest);
 }
        /// <summary>
        /// Gets the full URL that carries an OpenID message, even if it exceeds the normal maximum size of a URL,
        /// for purposes of sending to an AJAX component running in the browser.
        /// </summary>
        /// <param name="request">The authentication request.</param>
        /// <param name="immediate"><c>true</c>to create a checkid_immediate request;
        /// <c>false</c> to create a checkid_setup request.</param>
        /// <returns>The absolute URL that carries the entire OpenID message.</returns>
        private Uri GetRedirectUrl(IAuthenticationRequest request, bool immediate)
        {
            Contract.Requires <ArgumentNullException>(request != null);

            request.Mode = immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
            return(request.RedirectingResponse.GetDirectUriRequest(this.Channel));
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="OpenIdEventArgs"/> class
		/// with minimal information of an incomplete or failed authentication attempt.
		/// </summary>
		/// <param name="request">The outgoing authentication request.</param>
		internal OpenIdEventArgs(IAuthenticationRequest request) {
			Contract.Requires<ArgumentNullException>(request != null);

			this.Request = request;
			this.ClaimedIdentifier = request.ClaimedIdentifier;
			this.IsDirectedIdentity = request.IsDirectedIdentity;
		}
        public IAuthenticationReply Authenticate(IAuthenticationRequest authenticationRequest)
        {
            var authenticationReply = new AuthenticationReply();

            this._traceManager.Trace("CA: Authentication Request Received", authenticationRequest);

            IEnumerable<User> users =
                this.UnitOfWork.Repository<User, int>()
                    .Query()
                    .Filter(p => p.Email.Equals(authenticationRequest.UserId, StringComparison.OrdinalIgnoreCase))
                    .Get();

            User user = users.FirstOrDefault();
            if (user != null)
            {
                var sessionKey = new byte[SessionKeyLength];
                this.GetRandomBytes(sessionKey);

                ITgsToken tgsToken = this.CreateTgsToken(sessionKey);
                ITgtToken tgtToken = this.CreateTgtToken(user, sessionKey);
                this._traceManager.Trace("CA: TGS Generate tokens", tgsToken, tgtToken);
                authenticationReply.TgsBytes = this.EncryptTgsToken(user, tgsToken);
                authenticationReply.TgtBytes = this.EncryptTgtToken(tgtToken);
                this._traceManager.Trace("CA: TGS Encrypt tokens", Tuple.Create(authenticationReply.TgsBytes, authenticationReply.TgtBytes));
            }
            else
            {
                authenticationReply.Message = "User not found.";
            }

            return authenticationReply;
        }
Example #26
0
 /// <summary>
 /// Constructs an object with minimal information of an incomplete or failed
 /// authentication attempt.
 /// </summary>
 internal OpenIdEventArgs(IAuthenticationRequest request)
 {
     if (request == null) throw new ArgumentNullException("request");
     Request = request;
     ClaimedIdentifier = request.ClaimedIdentifier;
     IsDirectedIdentity = request.IsDirectedIdentity;
 }
Example #27
0
        internal static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest)
        {
            if (idrequest.Immediate) {
                if (idrequest.IsDirectedIdentity) {
                    if (HttpContext.Current.User.Identity.IsAuthenticated) {
                        idrequest.LocalIdentifier = Util.BuildIdentityUrl();
                        idrequest.IsAuthenticated = true;
                    } else {
                        idrequest.IsAuthenticated = false;
                    }
                } else {
                    string userOwningOpenIdUrl = Util.ExtractUserName(idrequest.LocalIdentifier);

                    // NOTE: in a production provider site, you may want to only
                    // respond affirmatively if the user has already authorized this consumer
                    // to know the answer.
                    idrequest.IsAuthenticated = userOwningOpenIdUrl == HttpContext.Current.User.Identity.Name;
                }

                if (idrequest.IsAuthenticated.Value) {
                    // add extension responses here.
                }
            } else {
                HttpContext.Current.Response.Redirect("~/decide.aspx", true);
            }
        }
Example #28
0
        /// <summary>
        /// Gets the full URL that carries an OpenID message, even if it exceeds the normal maximum size of a URL,
        /// for purposes of sending to an AJAX component running in the browser.
        /// </summary>
        /// <param name="request">The authentication request.</param>
        /// <param name="immediate"><c>true</c>to create a checkid_immediate request;
        /// <c>false</c> to create a checkid_setup request.</param>
        /// <returns>The absolute URL that carries the entire OpenID message.</returns>
        private Uri GetRedirectUrl(IAuthenticationRequest request, bool immediate)
        {
            Requires.NotNull(request, "request");

            request.Mode = immediate ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
            return(request.RedirectingResponse.GetDirectUriRequest(this.Channel));
        }
Example #29
0
        public IEnumerable <IOAuthQueryParameter> GenerateApplicationParameters(
            IReadOnlyConsumerCredentials temporaryCredentials,
            IAuthenticationRequest authRequest = null,
            IEnumerable <IOAuthQueryParameter> additionalParameters = null)
        {
            var headers = GenerateConsumerParameters(temporaryCredentials).ToList();

            // Add Header for authenticated connection to a Twitter Application
            if (authRequest != null &&
                !string.IsNullOrEmpty(authRequest.AuthorizationKey) &&
                !string.IsNullOrEmpty(authRequest.AuthorizationSecret))
            {
                headers.Add(new OAuthQueryParameter("oauth_token", StringFormater.UrlEncode(authRequest.AuthorizationKey), true, true, false));
                headers.Add(new OAuthQueryParameter("oauth_token_secret", StringFormater.UrlEncode(authRequest.AuthorizationSecret), false, false, true));
            }
            else
            {
                headers.Add(new OAuthQueryParameter("oauth_token", "", false, false, true));
            }

            if (additionalParameters != null)
            {
                headers.AddRange(additionalParameters);
            }

            return(headers);
        }
Example #30
0
        private RetrieveCrmTicketResponse GetCrmTicketResponse(IAuthenticationRequest tokenRequest)
        {
            // Retrieve a CrmTicket from the CrmDiscoveryService Web service.
            RetrieveCrmTicketRequest crmTicketRequest = new RetrieveCrmTicketRequest();

            crmTicketRequest.OrganizationName = tokenRequest.OrganizationName;
            crmTicketRequest.UserId           = tokenRequest.DomainName + @"\" + tokenRequest.Username;
            crmTicketRequest.Password         = Globals.UnwrapSecureString(tokenRequest.Password);

            RetrieveCrmTicketResponse crmTicketResponse = null;

            try
            {
                crmTicketResponse = (RetrieveCrmTicketResponse)_disco.Execute(crmTicketRequest);
            }
            catch (SoapException se)
            {
                // examine SoapException for authentication failure
            }
            catch (Exception ex)
            {
                AddExceptionData(ex, tokenRequest);
                throw;
            }
            return(crmTicketResponse);
        }
Example #31
0
        private void prepareRequest(IAuthenticationRequest request)
        {
            // Collect the PAPE policies requested by the user.
            List <string> policies = new List <string>();

            foreach (ListItem item in this.papePolicies.Items)
            {
                if (item.Selected)
                {
                    policies.Add(item.Value);
                }
            }

            // Add the PAPE extension if any policy was requested.
            var pape = new PolicyRequest();

            if (policies.Count > 0)
            {
                foreach (string policy in policies)
                {
                    pape.PreferredPolicies.Add(policy);
                }
            }

            if (this.maxAuthTimeBox.Text.Length > 0)
            {
                pape.MaximumAuthenticationAge = TimeSpan.FromSeconds(double.Parse(this.maxAuthTimeBox.Text));
            }

            if (pape.PreferredPolicies.Count > 0 || pape.MaximumAuthenticationAge.HasValue)
            {
                request.AddExtension(pape);
            }
        }
Example #32
0
        public Token RequestToken(IAuthenticationRequest tokenRequest)
        {
            // Check that we're accessing a valid organization from the CrmDiscoveryService Web service.
            if (String.IsNullOrEmpty(tokenRequest.OrganizationName))
            {
                OrganizationDetail orgInfo = GetOrganizationDetail();
                tokenRequest.OrganizationName = orgInfo.OrganizationName;
            }

            // Retrieve a CrmTicket from the CrmDiscoveryService Web service.
            RetrieveCrmTicketResponse crmTicketResponse = GetCrmTicketResponse(tokenRequest);

            if (crmTicketResponse == null)
            {
                // user not found, try default credentials
                IAuthenticationRequest defaultTicketRequest = GetDefaultTicketRequest();
                crmTicketResponse = GetCrmTicketResponse(defaultTicketRequest);
            }

            // user not found at all, throw exception
            if (crmTicketResponse == null)
            {
                InvalidCredentialsException ex = new InvalidCredentialsException();
                ex.Data.Add("Username", tokenRequest.DomainName + @"\" + tokenRequest.Username);
                throw ex;
            }

            CrmAuthenticationToken crmToken = GetCrmAuthenticationToken(tokenRequest, crmTicketResponse);

            return(new Token(crmToken, crmTicketResponse.OrganizationDetail.CrmServiceUrl));
        }
Example #33
0
 internal static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest)
 {
     if (idrequest.Immediate)
     {
         if (idrequest.IsDirectedIdentity)
         {
             if (HttpContext.Current.User.Identity.IsAuthenticated)
             {
                 idrequest.LocalIdentifier = Util.BuildIdentityUrl();
                 idrequest.IsAuthenticated = true;
             }
             else
             {
                 idrequest.IsAuthenticated = false;
             }
         }
         else
         {
             string userOwningOpenIdUrl = Util.ExtractUserName(idrequest.LocalIdentifier);
             // NOTE: in a production provider site, you may want to only
             // respond affirmatively if the user has already authorized this consumer
             // to know the answer.
             idrequest.IsAuthenticated = userOwningOpenIdUrl == HttpContext.Current.User.Identity.Name;
         }
     }
     else
     {
         HttpContext.Current.Response.Redirect("~/decide.aspx", true);
     }
 }
Example #34
0
        private void AddExceptionData(Exception ex, IAuthenticationRequest tokenRequest)
        {
            if (ex == null)
            {
                return;
            }

            if (!ex.Data.Contains("Organization"))
            {
                ex.Data.Add("Organization", Globals.CrmServiceSettings.OrganizationName);
            }

            if (!ex.Data.Contains("ServiceUrl"))
            {
                ex.Data.Add("ServiceUrl", Globals.CrmServiceSettings.ServiceUrl);
            }

            if (tokenRequest != null)
            {
                if (!ex.Data.Contains("DomainName"))
                {
                    ex.Data.Add("DomainName", Globals.CrmServiceSettings.DomainName);
                }

                if (!ex.Data.Contains("Username"))
                {
                    ex.Data.Add("Username", tokenRequest.Username);
                }
            }
        }
Example #35
0
        public ActionResult LogOn(string loginIdentifier)
        {
            if (!Identifier.IsValid(loginIdentifier))
            {
                ModelState.AddModelError("loginIdentifier",
                                         "The specified login identifier is invalid");
                return(View());
            }
            else
            {
                var openid = new OpenIdRelyingParty();
                IAuthenticationRequest request = openid.CreateRequest(
                    Identifier.Parse(loginIdentifier));

                // Require some additional data
                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                fetch.Attributes.AddOptional(WellKnownAttributes.Name.Alias);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                request.AddExtension(fetch);

                var returnUrl = Request.QueryString["returnUrl"] != null
                                    ? Request.QueryString["returnUrl"]
                                    : Url.Action("Index", "Home");
                request.AddCallbackArguments("returnUrl", returnUrl);

                return(request.RedirectingResponse.AsActionResult());
            }
        }
Example #36
0
        private CrmAuthenticationToken GetCrmAuthenticationToken(IAuthenticationRequest tokenRequest, RetrieveCrmTicketResponse ticket)
        {
            Int32 authenticationType;

#if DEBUG_AuthOverride
            authenticationType = Globals.CrmServiceSettings.DeploymentType;
#else
            if (String.IsNullOrEmpty(tokenRequest.DomainName))
            {
                // this is a CRM user, don't authenticate with their credentials
                authenticationType = Globals.CrmServiceSettings.DeploymentType;
            }
            else
            {
                // this is a domain user, authenticate via AD
                authenticationType = AuthenticationType.AD;
            }
#endif

            CrmAuthenticationToken sdkToken = new CrmAuthenticationToken()
            {
                AuthenticationType = authenticationType,
                OrganizationName   = ticket.OrganizationDetail.OrganizationName,
                CrmTicket          = ticket.CrmTicket
            };
            return(sdkToken);
        }
Example #37
0
    protected void loginButton_Click(object sender, EventArgs e)
    {
        if (!Page.IsValid)
        {
            return;                        // don't login if custom validation failed.
        }
        OpenIdRelyingParty openid = createRelyingParty();

        try {
            IAuthenticationRequest request = openid.CreateRequest(openIdBox.Text);
            // This is where you would add any OpenID extensions you wanted
            // to include in the authentication request.
            // request.AddExtension(someExtensionRequestInstance);

            // Send your visitor to their Provider for authentication.
            request.RedirectToProvider();
        } catch (OpenIdException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            openidValidator.Text    = ex.Message;
            openidValidator.IsValid = false;
        } catch (WebException ex) {
            // The user probably entered an Identifier that
            // was not a valid OpenID endpoint.
            openidValidator.Text    = ex.Message;
            openidValidator.IsValid = false;
        }
    }
Example #38
0
        /// <summary>
        /// Adds extensions to a given authentication request to ask the Provider
        /// for user profile data.
        /// </summary>
        /// <param name="request">The authentication request to add the extensions to.</param>
        private void AddProfileArgs(IAuthenticationRequest request)
        {
            Requires.NotNull(request, "request");

            var sreg = new ClaimsRequest()
            {
                Nickname   = this.RequestNickname,
                Email      = this.RequestEmail,
                FullName   = this.RequestFullName,
                BirthDate  = this.RequestBirthDate,
                Gender     = this.RequestGender,
                PostalCode = this.RequestPostalCode,
                Country    = this.RequestCountry,
                Language   = this.RequestLanguage,
                TimeZone   = this.RequestTimeZone,
                PolicyUrl  = string.IsNullOrEmpty(this.PolicyUrl) ?
                             null : new Uri(this.RelyingParty.Channel.GetRequestFromContext().GetPublicFacingUrl(), this.Page.ResolveUrl(this.PolicyUrl)),
            };

            // Only actually add the extension request if fields are actually being requested.
            if (!sreg.Equals(EmptyClaimsRequest))
            {
                request.AddExtension(sreg);
            }
        }
        private ActionResult RedirectToSteamOpenID(string login, string referer, OpenIdRelyingParty openid)
        {
            IAuthenticationRequest request = null;
            int tries = 3;

            while (request == null && tries > 0)
            {
                try
                {
                    tries--;
                    request = openid.CreateRequest(Identifier.Parse("https://steamcommunity.com/openid/"));
                }
                catch (Exception ex)
                {
                    Trace.TraceWarning("Steam openid CreateRequest has failed: {0}", ex);
                }
            }
            if (request == null)
            {
                return(Content("Steam OpenID service is offline, cannot authorize, please try again later."));
            }
            if (!string.IsNullOrEmpty(referer))
            {
                request.SetCallbackArgument("referer", referer);
            }
            return(request.RedirectingResponse.AsActionResultMvc5());
        }
Example #40
0
        public ActionResult SendAssertion()
        {
            IAuthenticationRequest authReq = PendingAuthenticationRequest;

            PendingAuthenticationRequest = null;             // clear session static so we don't do this again
            if (authReq == null)
            {
                throw new InvalidOperationException("There's no pending authentication request!");
            }

            if (authReq.IsDirectedIdentity)
            {
                authReq.LocalIdentifier = Models.User.GetClaimedIdentifierForUser(User.Identity.Name);
            }
            if (!authReq.IsDelegatedIdentifier)
            {
                authReq.ClaimedIdentifier = authReq.LocalIdentifier;
            }

            // Respond to AX/sreg extension requests.
            //// Real web sites would have code here

            authReq.IsAuthenticated = this.UserControlsIdentifier(authReq);
            return(OpenIdProvider.PrepareResponse(authReq).AsActionResult());
        }
Example #41
0
		/// <summary>
		/// Called just before the authentication request is sent to service provider.
		/// </summary>
		/// <param name="request">
		/// The request. 
		/// </param>
		protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request) {
			// Attribute Exchange extensions
			var fetchRequest = new FetchRequest();
			fetchRequest.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, isRequired: true));
			fetchRequest.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName, isRequired: false));

			request.AddExtension(fetchRequest);
		}
        public Task<IAuthenticationResult> AuthenticateAsync(string parentHref, IAuthenticationRequest request, IRetrievalOptions<IAuthenticationResult> options, CancellationToken cancellationToken)
        {
            Validate(parentHref, request);

            var attempt = this.BuildRequest(parentHref, request);
            var href = $"{parentHref}/loginAttempts";

            return this.dataStoreAsync.CreateAsync<IBasicLoginAttempt, IAuthenticationResult>(href, attempt, options, null, cancellationToken);
        }
        IAuthenticationResult IApplicationSync.AuthenticateAccount(IAuthenticationRequest request, Action<IRetrievalOptions<IAuthenticationResult>> responseOptions)
        {
            var options = new DefaultRetrievalOptions<IAuthenticationResult>();
            responseOptions(options);

            var dispatcher = new AuthenticationRequestDispatcher();

            return dispatcher.Authenticate(this.GetInternalSyncDataStore(), this, request, options);
        }
        Task<IAuthenticationResult> IApplication.AuthenticateAccountAsync(IAuthenticationRequest request, Action<IRetrievalOptions<IAuthenticationResult>> responseOptions, CancellationToken cancellationToken)
        {
            var options = new DefaultRetrievalOptions<IAuthenticationResult>();
            responseOptions(options);

            var dispatcher = new AuthenticationRequestDispatcher();

            return dispatcher.AuthenticateAsync(this.GetInternalAsyncDataStore(), this, request, options, cancellationToken);
        }
		/// <summary>
		/// Attaches an OAuth authorization request to an outgoing OpenID authentication request.
		/// </summary>
		/// <param name="openIdAuthenticationRequest">The OpenID authentication request.</param>
		/// <param name="scope">The scope of access that is requested of the service provider.</param>
		public void AttachAuthorizationRequest(IAuthenticationRequest openIdAuthenticationRequest, string scope) {
			Requires.NotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest");

			var authorizationRequest = new AuthorizationRequest {
				Consumer = this.ConsumerKey,
				Scope = scope,
			};

			openIdAuthenticationRequest.AddExtension(authorizationRequest);
		}
		/// <summary>
		/// Called just before the authentication request is sent to service provider.
		/// </summary>
		/// <param name="request">
		/// The request. 
		/// </param>
		protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request) {
			// Attribute Exchange extensions
			var fetchRequest = new FetchRequest();
			fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
			fetchRequest.Attributes.AddOptional(WellKnownAttributes.Contact.HomeAddress.Country);
			fetchRequest.Attributes.AddOptional(WellKnownAttributes.Name.First);
			fetchRequest.Attributes.AddOptional(WellKnownAttributes.Name.Last);

			request.AddExtension(fetchRequest);
		}
        public IAuthenticationResult Authenticate(IInternalDataStore dataStore, IApplication application, IAuthenticationRequest request, IRetrievalOptions<IAuthenticationResult> options)
        {
            Validate(dataStore, application, request);

            if (request is UsernamePasswordRequest)
            {
                return new BasicAuthenticator(dataStore).Authenticate(application.Href, request, options);
            }

            throw new InvalidOperationException($"The AuthenticationRequest {request.GetType().Name} is not supported by this implementation.");
        }
        private static void Validate(string parentHref, IAuthenticationRequest request)
        {
            if (string.IsNullOrEmpty(parentHref))
            {
                throw new ArgumentNullException(nameof(parentHref));
            }

            if (!(request is UsernamePasswordRequest))
            {
                throw new ArgumentException("Only UsernamePasswordRequest instances are supported by this by this authenticator.");
            }
        }
Example #49
0
        /// <summary>
        /// Attaches an OAuth authorization request to an outgoing OpenID authentication request.
        /// </summary>
        /// <param name="openIdAuthenticationRequest">The OpenID authentication request.</param>
        /// <param name="scope">The scope of access that is requested of the service provider.</param>
        public void AttachAuthorizationRequest(IAuthenticationRequest openIdAuthenticationRequest, string scope)
        {
            Contract.Requires(openIdAuthenticationRequest != null);
            ErrorUtilities.VerifyArgumentNotNull(openIdAuthenticationRequest, "openIdAuthenticationRequest");

            var authorizationRequest = new AuthorizationRequest {
                Consumer = this.ConsumerKey,
                Scope = scope,
            };

            openIdAuthenticationRequest.AddExtension(authorizationRequest);
        }
Example #50
0
    public void ProcessRequest(HttpContext context) {
       var sregRequest = ProviderEndpoint.PendingAuthenticationRequest.GetExtension<ClaimsRequest>();
       ClaimsResponse sregResponse = null;
       if (sregRequest != null)
       {
          //sregResponse = profileFields.GetOpenIdProfileFields(sregRequest);
       }
       ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
       if (sregResponse != null)
       {
          ProviderEndpoint.PendingAuthenticationRequest.AddResponseExtension(sregResponse);
       }
       //Debug.Assert(ProviderEndpoint.PendingAuthenticationRequest.IsResponseReady);
       ProviderEndpoint.PendingAuthenticationRequest.Response.Send();
       ProviderEndpoint.PendingAuthenticationRequest = null;


      OpenIdProvider provider = new OpenIdProvider();
      if (provider.Request != null) {
        // Some OpenID requests are automatable and can be responded to immediately.
        if (!provider.Request.IsResponseReady) {
          // But authentication requests cannot be responded to until something on
          // this site decides whether to approve or disapprove the authentication.
          var idrequest = (IAuthenticationRequest)provider.Request;
          // We store the authentication request in the user's session so that
          // redirects and user prompts can appear and eventually some page can decide
          // to respond to the OpenID authentication request either affirmatively or
          // negatively.
          PendingAuthenticationRequest = idrequest;
          // We delegate that approval process to our utility method that we share
          // with our other Provider sample page server.aspx.
          Util.ProcessAuthenticationChallenge(idrequest);
          // As part of authentication approval, the user may need to authenticate
          // to this Provider and/or decide whether to allow the requesting RP site
          // to log this user in.  If any UI needs to be presented to the user, 
          // the previous call to ProcessAuthenticationChallenge MAY not return
          // due to a redirect to some ASPX page.
        } else {
          // Some other automatable OpenID request is coming down, so clear
          // any previously session stored authentication request that might be
          // stored for this user.
          PendingAuthenticationRequest = null;
        }
        // Whether this was an automated message or an authentication message,
        // if there is a response ready to send back immediately, do so.
        if (provider.Request.IsResponseReady) {
          provider.Request.Response.Send();
          PendingAuthenticationRequest = null;
        }
      }
    }
Example #51
0
		/// <summary>
		/// Gets the <c>window.open</c> javascript snippet to use to open a popup window
		/// compliant with the UI extension.
		/// </summary>
		/// <param name="relyingParty">The relying party.</param>
		/// <param name="request">The authentication request to place in the window.</param>
		/// <param name="windowName">The name to assign to the popup window.</param>
		/// <returns>A string starting with 'window.open' and forming just that one method call.</returns>
		internal static string GetWindowPopupScript(OpenIdRelyingParty relyingParty, IAuthenticationRequest request, string windowName) {
			Requires.NotNull(relyingParty, "relyingParty");
			Requires.NotNull(request, "request");
			Requires.NotNullOrEmpty(windowName, "windowName");

			Uri popupUrl = request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel);

			return string.Format(
				CultureInfo.InvariantCulture,
				"(window.showModalDialog ? window.showModalDialog({0}, {1}, 'status:0;resizable:1;scroll:1;center:1;dialogWidth:{2}px; dialogHeight:{3}') : window.open({0}, {1}, 'status=0,toolbar=0,location=1,resizable=1,scrollbars=1,left=' + ((screen.width - {2}) / 2) + ',top=' + ((screen.height - {3}) / 2) + ',width={2},height={3}'));",
				MessagingUtilities.GetSafeJavascriptValue(popupUrl.AbsoluteUri),
				MessagingUtilities.GetSafeJavascriptValue(windowName),
				OpenId.Extensions.UI.UIUtilities.PopupWidth,
				OpenId.Extensions.UI.UIUtilities.PopupHeight);
		}
Example #52
0
      public static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest)
      {
         var sregRequest = ProviderEndpoint.PendingAuthenticationRequest.GetExtension<ClaimsRequest>();
         ClaimsResponse sregResponse = null;
         if (sregRequest != null)
         {
            //sregResponse = profileFields.GetOpenIdProfileFields(sregRequest);
         }
         ProviderEndpoint.PendingAuthenticationRequest.IsAuthenticated = true;
         if (sregResponse != null)
         {
            ProviderEndpoint.PendingAuthenticationRequest.AddResponseExtension(sregResponse);
         }
         //Debug.Assert(ProviderEndpoint.PendingAuthenticationRequest.IsResponseReady);
         ProviderEndpoint.PendingAuthenticationRequest.Response.Send();
         ProviderEndpoint.PendingAuthenticationRequest = null;


         //if (idrequest.Immediate)
         //{
         //   if (idrequest.IsDirectedIdentity)
         //   {
         //      idrequest.IsAuthenticated = true;
         //      //if (HttpContext.Current.User.Identity.IsAuthenticated)
         //      //{
         //      //   idrequest.LocalIdentifier = Util.BuildIdentityUrl();
         //      //   idrequest.IsAuthenticated = true;
         //      //}
         //      //else
         //      //{
         //      //   idrequest.IsAuthenticated = false;
         //      //}
         //   }
         //   else
         //   {
         //      //string userOwningOpenIdUrl = Util.ExtractUserName(idrequest.LocalIdentifier);
         //      // NOTE: in a production provider site, you may want to only 
         //      // respond affirmatively if the user has already authorized this consumer
         //      // to know the answer.
         //      //idrequest.IsAuthenticated = userOwningOpenIdUrl == HttpContext.Current.User.Identity.Name;
         //   }
         //}
         //else
         //{
         //   //HttpContext.Current.Response.Redirect("~/decide.aspx", true);
         //}
      }
        private static void Validate(IInternalDataStore dataStore, IApplication application, IAuthenticationRequest request)
        {
            if (dataStore == null)
            {
                throw new ArgumentNullException(nameof(dataStore));
            }

            if (application == null)
            {
                throw new ArgumentNullException(nameof(application));
            }

            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
        }
Example #54
0
		/// <summary>
		/// Initializes a new instance of the <see cref="CheckIdWindow"/> class.
		/// </summary>
		/// <param name="userIdentityPageBase">The base URI upon which user identity pages are created.</param>
		/// <param name="request">The incoming authentication request.</param>
		private CheckIdWindow(Uri userIdentityPageBase, IAuthenticationRequest request) {
			Requires.NotNull(request, "request");

			this.InitializeComponent();

			// Initialize the window with appropriate values.
			this.realmLabel.Content = request.Realm;
			this.immediateModeLabel.Visibility = request.Immediate ? Visibility.Visible : Visibility.Collapsed;
			this.setupModeLabel.Visibility = request.Immediate ? Visibility.Collapsed : Visibility.Visible;

			if (request.IsDirectedIdentity) {
				this.claimedIdentifierBox.Text = userIdentityPageBase.AbsoluteUri;
				this.localIdentifierBox.Text = userIdentityPageBase.AbsoluteUri;
			} else {
				this.claimedIdentifierBox.Text = request.ClaimedIdentifier;
				this.localIdentifierBox.Text = request.LocalIdentifier;
			}
		}
Example #55
0
		internal static void ProcessAuthenticationChallenge(IAuthenticationRequest idrequest) {
			// Verify that RP discovery is successful.
			if (idrequest.IsReturnUrlDiscoverable(ProviderEndpoint.Provider) != RelyingPartyDiscoveryResult.Success) {
				idrequest.IsAuthenticated = false;
				return;
			}

			// Verify that the RP is on the whitelist.  Realms are case sensitive.
			string[] whitelist = ConfigurationManager.AppSettings["whitelistedRealms"].Split(';');
			if (Array.IndexOf(whitelist, idrequest.Realm.ToString()) < 0) {
				idrequest.IsAuthenticated = false;
				return;
			}

			if (idrequest.IsDirectedIdentity) {
				if (HttpContext.Current.User.Identity.IsAuthenticated) {
					idrequest.LocalIdentifier = Util.BuildIdentityUrl();
					idrequest.IsAuthenticated = true;
				} else {
					idrequest.IsAuthenticated = false;
				}
			} else {
				string userOwningOpenIdUrl = Util.ExtractUserName(idrequest.LocalIdentifier);

				// NOTE: in a production provider site, you may want to only 
				// respond affirmatively if the user has already authorized this consumer
				// to know the answer.
				idrequest.IsAuthenticated = userOwningOpenIdUrl == HttpContext.Current.User.Identity.Name;
			}

			if (idrequest.IsAuthenticated.Value) {
				// add extension responses here.
				var fetchRequest = idrequest.GetExtension<FetchRequest>();
				if (fetchRequest != null) {
					var fetchResponse = new FetchResponse();
					if (fetchRequest.Attributes.Contains(RolesAttribute)) {
						// Inform the RP what roles this user should fill
						// These roles would normally come out of the user database.
						fetchResponse.Attributes.Add(RolesAttribute, "Member", "Admin");
					}
					idrequest.AddResponseExtension(fetchResponse);
				}
			}
		}
Example #56
0
        /// <summary>
        /// Called when the Provider is preparing to send a response to an authentication request.
        /// </summary>
        /// <param name="request">The request that is configured to generate the outgoing response.</param>
        /// <returns>
        /// 	<c>true</c> if this behavior owns this request and wants to stop other behaviors
        /// from handling it; <c>false</c> to allow other behaviors to process this request.
        /// </returns>
        bool IProviderBehavior.OnOutgoingResponse(IAuthenticationRequest request)
        {
            ErrorUtilities.VerifyArgumentNotNull(request, "request");

            // Nothing to do for negative assertions.
            if (!request.IsAuthenticated.Value) {
                return false;
            }

            var requestInternal = (Provider.AuthenticationRequest)request;
            var responseMessage = (IProtocolMessageWithExtensions)requestInternal.Response;

            // Only apply our special policies if the RP requested it.
            var papeRequest = request.GetExtension<PolicyRequest>();
            if (papeRequest != null) {
                if (papeRequest.PreferredPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
                    ErrorUtilities.VerifyProtocol(request.ClaimedIdentifier == request.LocalIdentifier, OpenIdStrings.DelegatingIdentifiersNotAllowed);

                    if (PpidIdentifierProvider == null) {
                        Logger.OpenId.Error(BehaviorStrings.PpidProviderNotGiven);
                        return false;
                    }

                    // Mask the user's identity with a PPID.
                    if (PpidIdentifierProvider.IsUserLocalIdentifier(request.LocalIdentifier)) {
                        Identifier ppidIdentifier = PpidIdentifierProvider.GetIdentifier(request.LocalIdentifier, request.Realm);
                        requestInternal.ResetClaimedAndLocalIdentifiers(ppidIdentifier);
                    }

                    // Indicate that the RP is receiving a PPID claimed_id
                    var papeResponse = responseMessage.Extensions.OfType<PolicyResponse>().SingleOrDefault();
                    if (papeResponse == null) {
                        request.AddResponseExtension(papeResponse = new PolicyResponse());
                    }

                    if (!papeResponse.ActualPolicies.Contains(AuthenticationPolicies.PrivatePersonalIdentifier)) {
                        papeResponse.ActualPolicies.Add(AuthenticationPolicies.PrivatePersonalIdentifier);
                    }
                }
            }

            return false;
        }
		/// <summary>
		/// Processes an authentication request by a popup window.
		/// </summary>
		/// <param name="provider">The OpenID Provider host.</param>
		/// <param name="request">The incoming authentication request.</param>
		internal static void ProcessAuthentication(HostedProvider provider, IAuthenticationRequest request) {
			Contract.Requires(provider != null);
			Contract.Requires(request != null);

			var window = new CheckIdWindow(provider, request);
			bool? result = window.ShowDialog();

			// If the user pressed Esc or cancel, just send a negative assertion.
			if (!result.HasValue || !result.Value) {
				request.IsAuthenticated = false;
				return;
			}

			request.IsAuthenticated = window.tabControl1.SelectedItem == window.positiveTab;
			if (request.IsAuthenticated.Value) {
				request.ClaimedIdentifier = window.claimedIdentifierBox.Text;
				request.LocalIdentifier = window.localIdentifierBox.Text;
			}
		}
        private void prepareRequest(IAuthenticationRequest request)
        {
            // Collect the PAPE policies requested by the user.
            List<string> policies = new List<string>();
            foreach (ListItem item in this.papePolicies.Items) {
                if (item.Selected) {
                    policies.Add(item.Value);
                }
            }

            // Add the PAPE extension if any policy was requested.
            if (policies.Count > 0) {
                var pape = new PolicyRequest();
                foreach (string policy in policies) {
                    pape.PreferredPolicies.Add(policy);
                }

                request.AddExtension(pape);
            }
        }
        public ActionResult SendAssertion()
        {
            IAuthenticationRequest authReq = PendingAuthenticationRequest;
            PendingAuthenticationRequest = null; // clear session static so we don't do this again
            if (authReq == null) {
                throw new InvalidOperationException("There's no pending authentication request!");
            }

            if (authReq.IsDirectedIdentity) {
                authReq.LocalIdentifier = Models.User.GetClaimedIdentifierForUser(User.Identity.Name);
            }
            if (!authReq.IsDelegatedIdentifier) {
                authReq.ClaimedIdentifier = authReq.LocalIdentifier;
            }

            // Respond to AX/sreg extension requests.
            //// Real web sites would have code here

            authReq.IsAuthenticated = this.UserControlsIdentifier(authReq);
            return OpenIdProvider.PrepareResponse(authReq).AsActionResult();
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="CheckIdWindow"/> class.
		/// </summary>
		/// <param name="provider">The OpenID Provider host.</param>
		/// <param name="request">The incoming authentication request.</param>
		private CheckIdWindow(HostedProvider provider, IAuthenticationRequest request) {
			Contract.Requires(request != null);

			this.InitializeComponent();

			// Initialize the window with appropriate values.
			this.realmLabel.Content = request.Realm;
			this.immediateModeLabel.Visibility = request.Immediate ? Visibility.Visible : Visibility.Collapsed;
			this.setupModeLabel.Visibility = request.Immediate ? Visibility.Collapsed : Visibility.Visible;

			bool isRPDiscoverable = request.IsReturnUrlDiscoverable(provider.Provider.Channel.WebRequestHandler) == RelyingPartyDiscoveryResult.Success;
			this.discoverableYesLabel.Visibility = isRPDiscoverable ? Visibility.Visible : Visibility.Collapsed;
			this.discoverableNoLabel.Visibility = isRPDiscoverable ? Visibility.Collapsed : Visibility.Visible;

			if (request.IsDirectedIdentity) {
				this.claimedIdentifierBox.Text = provider.UserIdentityPageBase.AbsoluteUri;
				this.localIdentifierBox.Text = provider.UserIdentityPageBase.AbsoluteUri;
			} else {
				this.claimedIdentifierBox.Text = request.ClaimedIdentifier;
				this.localIdentifierBox.Text = request.LocalIdentifier;
			}
		}