protected void add_Click(object sender, System.EventArgs e)
        {
            SharedBasePage requestPage = Page as SharedBasePage;

            // validate base entries Captcha and Comment
            Page.Validate("Base");
            bool baseValid = Page.IsValid;

            // check the openid controls
            Page.Validate("OpenId");
            bool openIdValid = Page.IsValid;

            // check the classic controls Name and Email
            Page.Validate("Classic");
            bool classicValid = Page.IsValid;

            if (baseValid && openIdValid)
            {
                if (String.IsNullOrEmpty(openid_identifier.Text) == false && openid_identifier.Text != "Click to Sign In")
                {
                    Session["pendingComment"] = comment.Text;
                    Session["pendingEntryId"] = ViewState["entryId"].ToString().ToUpper();
                    OpenIdRelyingParty openid = new OpenIdRelyingParty();
                    try
                    {
                        IAuthenticationRequest req         = openid.CreateRequest(openid_identifier.Text);
                        ClaimsRequest          sregRequest = new ClaimsRequest();
                        sregRequest.Email    = DemandLevel.Require;
                        sregRequest.Nickname = DemandLevel.Require;
                        sregRequest.FullName = DemandLevel.Request;
                        req.AddExtension(sregRequest);

                        // Also add AX request explicitly so we can request first and last name individually.
                        FetchRequest axRequest = new FetchRequest();
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        axRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        req.AddExtension(axRequest);

                        SaveCookies();
                        req.RedirectToProvider();
                        return;
                    }
                    catch (UriFormatException ue) //They've entered something that's not a URI!
                    {
                        requestPage.LoggingService.AddEvent(new EventDataItem(EventCodes.Error, "ERROR: " + openid_identifier.Text + " is not a valid URL. " + ue.Message, ""));
                    }
                }
            }

            if (baseValid && classicValid)
            {
                //Why isn't Page.Validate("Normal") working? It returns false. Hm.
                if (!String.IsNullOrEmpty(name.Text.Trim()))
                {
                    SaveCookies();
                    AddNewComment(name.Text, email.Text, homepage.Text, comment.Text, ViewState["entryId"].ToString().ToUpper(), /* openid */ false);
                }
            }
        }
Example #2
0
        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);

                    // 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 #3
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 #4
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);
        }
    }
Example #5
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 #6
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 #7
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);
            }
        }
Example #8
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());
        }
        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 #10
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 #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.
            if (policies.Count > 0)
            {
                var pape = new PolicyRequest();
                foreach (string policy in policies)
                {
                    pape.PreferredPolicies.Add(policy);
                }

                request.AddExtension(pape);
            }
        }
Example #12
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 #13
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 #14
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);
        }
Example #15
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);
 }
Example #16
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 #17
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);
			}
		}
        /// <summary>
        /// Action Results for Index, uses DotNetOpenAuth for creating OpenId Request with Intuit
        /// and handling response recieved.
        /// </summary>
        /// <returns></returns>
        public RedirectResult Index()
        {
            var openid_identifier = ConfigurationManager.AppSettings["openid_identifier"].ToString();;
            var response          = openid.GetResponse();

            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    try
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openid_identifier);
                        FetchRequest           fetch   = new FetchRequest();
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email));
                        fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName));
                        request.AddExtension(fetch);
                        request.RedirectToProvider();
                    }
                    catch (ProtocolException ex)
                    {
                        throw ex;
                    }
                }
            }
            else
            {
                if (response.FriendlyIdentifierForDisplay == null)
                {
                    Response.Redirect("/OpenId");
                }

                // Stage 3: OpenID Provider sending assertion response, storing the response in Session object is only for demonstration purpose
                Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                FetchResponse fetch = response.GetExtension <FetchResponse>();
                if (fetch != null)
                {
                    Session["OpenIdResponse"] = "True";
                    Session["FriendlyEmail"]  = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email); // emailAddresses.Count > 0 ? emailAddresses[0] : null;
                    Session["FriendlyName"]   = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName); //fullNames.Count > 0 ? fullNames[0] : null;

                    //get the Oauth Access token for the user from OauthAccessTokenStorage.xml
                    OauthAccessTokenStorageHelper.GetOauthAccessTokenForUser(Session["FriendlyEmail"].ToString(), this);
                }
            }

            string query = Request.Url.Query;

            if (!string.IsNullOrWhiteSpace(query) && query.ToLower().Contains("disconnect=true"))
            {
                Session["accessToken"]       = "dummyAccessToken";
                Session["accessTokenSecret"] = "dummyAccessTokenSecret";
                Session["Flag"] = true;
                return(Redirect("/CleanupOnDisconnect/Index"));
            }

            return(Redirect("/Home/index"));
        }
Example #19
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);
		}
Example #20
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.AddRequired(WellKnownAttributes.Contact.Email);
			fetchRequest.Attributes.AddOptional(WellKnownAttributes.Name.FullName);

			request.AddExtension(fetchRequest);
		}
        protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
        {
            var fetchRequest = new FetchRequest();

            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
            fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
            request.AddExtension(fetchRequest);
        }
Example #22
0
 protected override void OnBeforeSendingAuthenticationRequest(IAuthenticationRequest request)
 {
     var fetchRequest = new FetchRequest();
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.First);
     fetchRequest.Attributes.AddRequired(WellKnownAttributes.Name.Last);
     request.AddExtension(fetchRequest);
 }
Example #23
0
        internal static string SignIn(Guid userDetailsPageId)
        {
            string errorMessage = string.Empty;

            using (var openid = new OpenIdRelyingParty())
            {
                //fix wrong URI, add PathInfo
                HttpContext.Current.RewritePath(HttpContext.Current.Request.RawUrl);
                IAuthenticationResponse response = openid.GetResponse();
                if (response == null)
                {
                    //request
                    string openIDIdentifier = HttpContext.Current.Request.Form["openid_identifier"];

                    if (!string.IsNullOrEmpty(openIDIdentifier))
                    {
                        IAuthenticationRequest request = openid.CreateRequest(openIDIdentifier);
                        var claims = new ClaimsRequest();
                        claims.Email    = DemandLevel.Require;
                        claims.Nickname = DemandLevel.Require;
                        claims.FullName = DemandLevel.Require;
                        claims.Country  = DemandLevel.Require;
                        request.AddExtension(claims);

                        //small fix for request.RedirectToProvider();
                        string location = request.RedirectingResponse.Headers["Location"];
                        HttpContext.Current.Response.Redirect(location, false);
                    }
                }
                else
                {
                    //response
                    switch (response.Status)
                    {
                    case AuthenticationStatus.Authenticated:
                        HandleSuccessfulSignIn(response, userDetailsPageId);
                        break;

                    case AuthenticationStatus.Canceled:
                        errorMessage = "Login was cancelled at the provider.";
                        break;

                    case AuthenticationStatus.Failed:
                        errorMessage = "Login failed at the provider.";
                        break;

                    case AuthenticationStatus.SetupRequired:
                        errorMessage = "The provider requires setup.";
                        break;

                    default:
                        errorMessage = "Login failed.";
                        break;
                    }
                }
            }
            return(errorMessage);
        }
Example #24
0
 public static void AddClaimsRequest(IAuthenticationRequest r)
 {
     r.AddExtension(new ClaimsRequest
     {
         Email    = DemandLevel.Require,
         Nickname = DemandLevel.Require,
         FullName = DemandLevel.Require
     });
 }
Example #25
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.AddRequired(WellKnownAttributes.Contact.Email);
            fetchRequest.Attributes.AddOptional(WellKnownAttributes.Name.FullName);

            request.AddExtension(fetchRequest);
        }
		/// <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);
		}
Example #27
0
        public ActionResult RedirectToProvider(string providerUrl, string returnUrl, FetchRequest fetch)
        {
            IAuthenticationRequest authenticationRequest = this.relyingParty.CreateRequest(providerUrl,
                                                                                           Realm.AutoDetect,
                                                                                           new Uri(returnUrl));

            authenticationRequest.AddExtension(fetch);

            return(new OutgoingRequestActionResult(authenticationRequest.RedirectingResponse));
        }
Example #28
0
        public void ProviverRedirect(string discoveryUri)
        {
            IAuthenticationRequest request = null;

            try
            {
                OpenIdRelyingParty openid = new OpenIdRelyingParty();
                var builder = new UriBuilder(Request.Url)
                {
                    Query = ""
                };
                request = openid.CreateRequest(discoveryUri, builder.Uri, builder.Uri);
                switch (discoveryUri)
                {
                case "https://www.google.com/accounts/o8/id":
                    var fetch = new FetchRequest();
                    fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.Middle);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Person.Gender);
                    request.AddExtension(fetch);
                    break;

                case "https://me.yahoo.com":
                    request.AddExtension(new ClaimsRequest
                    {
                        Email    = DemandLevel.Request,
                        FullName = DemandLevel.Request
                    });
                    break;
                }
            }
            catch (Exception ex)
            {
                ProcessException(ex);
            }
            if (request != null)
            {
                request.RedirectToProvider();
            }
        }
        /// <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);
        }
Example #30
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 <ArgumentNullException>(openIdAuthenticationRequest != null);

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

            openIdAuthenticationRequest.AddExtension(authorizationRequest);
        }
Example #31
0
        //
        // GET: /RSVP/RsvpBegin

        public ActionResult RsvpBegin(string identifier, int id)
        {
            Uri returnTo = new Uri(new Uri(Realm.AutoDetect), Url.Action("RsvpFinish"));
            IAuthenticationRequest request = relyingParty.CreateRequest(identifier, Realm.AutoDetect, returnTo);

            request.SetUntrustedCallbackArgument("DinnerId", id.ToString(CultureInfo.InvariantCulture));
            request.AddExtension(new ClaimsRequest {
                Email = DemandLevel.Require, FullName = DemandLevel.Request
            });
            return(request.RedirectingResponse.AsActionResult());
        }
Example #32
0
        /// <summary>
        /// Create a mvc request to log user in the relying party account system.
        /// </summary>
        /// <param name="identifier">Identifier</param>
        /// <returns>Request</returns>
        public ActionResult CreateRequest(string identifier)
        {
            IAuthenticationRequest request = _openid.CreateRequest(
                Identifier.Parse(identifier));

            // Require email. We can latter use it for Gravatar
            // or for retriving forgotten open id.
            request.AddExtension(new ClaimsRequest {
                Email = DemandLevel.Require
            });
            return(request.RedirectingResponse.AsActionResult());
        }
Example #33
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);
        }
        /// <summary>
        /// Redirects the browser to the sign in page of the OpenID authority.
        /// </summary>
        public override void RedirectToLoginPage()
        {
            using (var openid = new OpenIdRelyingParty())
            {
                // TODO: do this only once when OpenID is initialized
                System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Ssl3;

                IAuthenticationRequest request = openid.CreateRequest(discoveryUrl);
                request.AddExtension(CreateFetchRequest());
                request.RedirectToProvider();
            }
        }
Example #35
0
        public IAuthenticationRequest ValidateAtOpenIdProvider(string openIdIdentifier)
        {
            IAuthenticationRequest openIdRequest = openId.CreateRequest(Identifier.Parse(openIdIdentifier));

            var fetch = new FetchRequest();

            fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
            fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
            fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
            openIdRequest.AddExtension(fetch);

            return(openIdRequest);
        }
Example #36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            this.RegisterAsyncTask(
                new PageAsyncTask(
                    async ct => {
                using (var openid = new OpenIdRelyingParty()) {
                    // In order to receive the UIRequest as a response, we must register a custom extension factory.
                    openid.ExtensionFactories.Add(new UIRequestAtRelyingPartyFactory());

                    var response = await openid.GetResponseAsync(new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                    if (response == null)
                    {
                        // Submit an OpenID request which Google must reply to immediately.
                        // If the user hasn't established a trust relationship with this site yet,
                        // Google will not give us the user identity, but they will tell us whether the user
                        // at least has an active login session with them so we know whether to promote the
                        // "Log in with Google" button.
                        IAuthenticationRequest request =
                            await
                            openid.CreateRequestAsync(
                                "https://www.google.com/accounts/o8/id", new HttpRequestWrapper(Request), Response.ClientDisconnectedToken);
                        request.AddExtension(new UIRequest {
                            Mode = UIModeDetectSession
                        });
                        request.Mode = AuthenticationRequestMode.Immediate;
                        await request.RedirectToProviderAsync(new HttpContextWrapper(this.Context), Response.ClientDisconnectedToken);
                    }
                    else
                    {
                        if (response.Status == AuthenticationStatus.Authenticated)
                        {
                            this.YouTrustUsLabel.Visible = true;
                        }
                        else if (response.Status == AuthenticationStatus.SetupRequired)
                        {
                            // Google refused to authenticate the user without user interaction.
                            // This is either because Google doesn't know who the user is yet,
                            // or because the user hasn't indicated to Google to trust this site.
                            // Google uniquely offers the RP a tip as to which of the above situations is true.
                            // Figure out which it is.  In a real app, you might use this value to promote a
                            // Google login button on your site if you detect that a Google session exists.
                            var ext = response.GetUntrustedExtension <UIRequest>();
                            this.YouAreLoggedInLabel.Visible    = ext != null && ext.Mode == UIModeDetectSession;
                            this.YouAreNotLoggedInLabel.Visible = !this.YouAreLoggedInLabel.Visible;
                        }
                    }
                }
            }));
        }
Example #37
0
        private IAuthenticationRequest BuildOpenIdRequest(string openIdProviderIdentifier)
        {
            IAuthenticationRequest req = openid.CreateRequest(openIdProviderIdentifier);



            FetchRequest fetch = new FetchRequest();

            fetch.Attributes.Add(new AttributeRequest("http://schema.wave.com/endpoint/descriptor/trustScore", true /* required */));
            fetch.Attributes.Add(new AttributeRequest("http://schema.wave.com/endpoint/descriptor/needsSetup", false /* optional */));
            fetch.Attributes.Add(new AttributeRequest("http://schema.wave.com/endpoint/descriptor/setupURL", false /* optional */));
            req.AddExtension(fetch);

            return(req);
        }
        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 #39
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);
		}
	}
        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);
        }
Example #41
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");

			request.AddExtension(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().UrlBeforeRewriting, this.Page.ResolveUrl(this.PolicyUrl)),
			});
		}
Example #42
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) {
			ErrorUtilities.VerifyArgumentNotNull(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().UrlBeforeRewriting, this.Page.ResolveUrl(this.PolicyUrl)),
			};

			// Only actually add the extension request if fields are actually being requested.
			if (!sreg.Equals(EmptyClaimsRequest)) {
				request.AddExtension(sreg);
			}
		}
Example #43
0
 void addProfileArgs(IAuthenticationRequest request)
 {
     request.AddExtension(new ClaimsRequest() {
         Nickname = RequestNickname,
         Email = RequestEmail,
         FullName = RequestFullName,
         BirthDate = RequestBirthDate,
         Gender = RequestGender,
         PostalCode = RequestPostalCode,
         Country = RequestCountry,
         Language = RequestLanguage,
         TimeZone = RequestTimeZone,
         PolicyUrl = string.IsNullOrEmpty(PolicyUrl) ?
             null : new Uri(Util.GetRequestUrlFromContext(), Page.ResolveUrl(PolicyUrl)),
     });
 }
Example #44
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(new HttpRequestWrapper(this.Context.Request).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);
			}
		}