public async Task CreateRequestMessage() {
			this.RegisterAutoProvider();
			var rp = this.CreateRelyingParty();
			Identifier id = this.GetMockIdentifier(ProtocolVersion.V20);
			IAuthenticationRequest authRequest = await rp.CreateRequestAsync(id, this.realm, this.returnTo);

			// Add some callback arguments
			authRequest.AddCallbackArguments("a", "b");
			authRequest.AddCallbackArguments(new Dictionary<string, string> { { "c", "d" }, { "e", "f" } });

			// Assembly an extension request.
			var sregRequest = new ClaimsRequest();
			sregRequest.Nickname = DemandLevel.Request;
			authRequest.AddExtension(sregRequest);

			// Construct the actual authentication request message.
			var authRequestAccessor = (AuthenticationRequest)authRequest;
			var req = await authRequestAccessor.CreateRequestMessageTestHookAsync(CancellationToken.None);
			Assert.IsNotNull(req);

			// Verify that callback arguments were included.
			NameValueCollection callbackArguments = HttpUtility.ParseQueryString(req.ReturnTo.Query);
			Assert.AreEqual("b", callbackArguments["a"]);
			Assert.AreEqual("d", callbackArguments["c"]);
			Assert.AreEqual("f", callbackArguments["e"]);

			// Verify that extensions were included.
			Assert.AreEqual(1, req.Extensions.Count);
			Assert.IsTrue(req.Extensions.Contains(sregRequest));
		}
Example #2
0
        public ActionResult BeginAuth()
        {
            var provider = "http://steamcommunity.com/openid";
            var realm = new DotNetOpenAuth.OpenId.Realm(string.Format("{0}{1}{2}", this.Request.Url.Scheme, Uri.SchemeDelimiter, this.Request.Url.Authority));
            var returnTo = new Uri(this.Request.Url, this.Url.Action("EndAuth"));

            using (var rp = new OpenIdRelyingParty())
            {
                var request = rp.CreateRequest(provider, realm, returnTo);

                var claimsRequest = new ClaimsRequest
                {
                    Email = DemandLevel.Require,
                    BirthDate = DemandLevel.Request,
                    Country = DemandLevel.Request,
                    FullName = DemandLevel.Request,
                    Gender = DemandLevel.Request,
                    Language = DemandLevel.Request,
                    Nickname = DemandLevel.Request,
                    PostalCode = DemandLevel.Request,
                    TimeZone = DemandLevel.Request,
                };

                request.AddExtension(claimsRequest);

                return request.RedirectingResponse.AsActionResult();
            }
        }
Example #3
0
        public static IOpenIdMessageExtension CreateClaimsRequest(
            IOpenAuthenticationProviderPermissionService openAuthenticationProviderPermissionService)
        {
            var claimsRequest = new ClaimsRequest();

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Birthdate", Provider.SystemName))
                claimsRequest.BirthDate = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Country", Provider.SystemName))
                claimsRequest.Country = DemandLevel.Require;

            //            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Email", Provider.OpenId))
            claimsRequest.Email = DemandLevel.Require;

            //            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("FullName", Provider.OpenId))
            claimsRequest.FullName = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Gender", Provider.SystemName))
                claimsRequest.Gender = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Language", Provider.SystemName))
                claimsRequest.Language = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("Nickname", Provider.SystemName))
                claimsRequest.Nickname = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("PostalCode", Provider.SystemName))
                claimsRequest.PostalCode = DemandLevel.Require;

            if (openAuthenticationProviderPermissionService.IsPermissionEnabled("TimeZone", Provider.SystemName))
                claimsRequest.TimeZone = DemandLevel.Require;

            return claimsRequest;
        }
		/// <summary>
		/// Looks for Simple Registration and Attribute Exchange (all known formats)
		/// request extensions and returns them as a Simple Registration extension,
		/// and adds the new extension to the original request message if it was absent.
		/// </summary>
		/// <param name="request">The authentication request.</param>
		/// <returns>
		/// The Simple Registration request if found, 
		/// or a fabricated one based on the Attribute Exchange extension if found,
		/// or <c>null</c> if no attribute extension request is found.</returns>
		internal static ClaimsRequest UnifyExtensionsAsSreg(this Provider.IHostProcessedRequest request) {
			Requires.NotNull(request, "request");

			var req = (Provider.HostProcessedRequest)request;
			var sreg = req.GetExtension<ClaimsRequest>();
			if (sreg != null) {
				return sreg;
			}

			var ax = req.GetExtension<FetchRequest>();
			if (ax != null) {
				sreg = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.sreg_ns);
				sreg.Synthesized = true;
				((IProtocolMessageWithExtensions)req.RequestMessage).Extensions.Add(sreg);
				sreg.BirthDate = GetDemandLevelFor(ax, WellKnownAttributes.BirthDate.WholeBirthDate);
				sreg.Country = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.Country);
				sreg.Email = GetDemandLevelFor(ax, WellKnownAttributes.Contact.Email);
				sreg.FullName = GetDemandLevelFor(ax, WellKnownAttributes.Name.FullName);
				sreg.Gender = GetDemandLevelFor(ax, WellKnownAttributes.Person.Gender);
				sreg.Language = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.Language);
				sreg.Nickname = GetDemandLevelFor(ax, WellKnownAttributes.Name.Alias);
				sreg.PostalCode = GetDemandLevelFor(ax, WellKnownAttributes.Contact.HomeAddress.PostalCode);
				sreg.TimeZone = GetDemandLevelFor(ax, WellKnownAttributes.Preferences.TimeZone);
			}

			return sreg;
		}
		public void CreateRequestMessage() {
			OpenIdCoordinator coordinator = new OpenIdCoordinator(
				rp => {
					Identifier id = this.GetMockIdentifier(ProtocolVersion.V20);
					IAuthenticationRequest authRequest = rp.CreateRequest(id, this.realm, this.returnTo);

					// Add some callback arguments
					authRequest.AddCallbackArguments("a", "b");
					authRequest.AddCallbackArguments(new Dictionary<string, string> { { "c", "d" }, { "e", "f" } });

					// Assembly an extension request.
					ClaimsRequest sregRequest = new ClaimsRequest();
					sregRequest.Nickname = DemandLevel.Request;
					authRequest.AddExtension(sregRequest);

					// Construct the actual authentication request message.
					var authRequestAccessor = (AuthenticationRequest)authRequest;
					var req = authRequestAccessor.CreateRequestMessageTestHook();
					Assert.IsNotNull(req);

					// Verify that callback arguments were included.
					NameValueCollection callbackArguments = HttpUtility.ParseQueryString(req.ReturnTo.Query);
					Assert.AreEqual("b", callbackArguments["a"]);
					Assert.AreEqual("d", callbackArguments["c"]);
					Assert.AreEqual("f", callbackArguments["e"]);

					// Verify that extensions were included.
					Assert.AreEqual(1, req.Extensions.Count);
					Assert.IsTrue(req.Extensions.Contains(sregRequest));
				},
				AutoProvider);
			coordinator.Run();
		}
		public void SetRequiredFieldsFromRequest(ClaimsRequest requestFields) {
			if (requestFields.PolicyUrl != null) {
				this.privacyLink.NavigateUrl = requestFields.PolicyUrl.AbsoluteUri;
			} else {
				this.privacyLink.Visible = false;
			}

			this.dobRequiredLabel.Visible = requestFields.BirthDate == DemandLevel.Require;
			this.countryRequiredLabel.Visible = requestFields.Country == DemandLevel.Require;
			this.emailRequiredLabel.Visible = requestFields.Email == DemandLevel.Require;
			this.fullnameRequiredLabel.Visible = requestFields.FullName == DemandLevel.Require;
			this.genderRequiredLabel.Visible = requestFields.Gender == DemandLevel.Require;
			this.languageRequiredLabel.Visible = requestFields.Language == DemandLevel.Require;
			this.nicknameRequiredLabel.Visible = requestFields.Nickname == DemandLevel.Require;
			this.postcodeRequiredLabel.Visible = requestFields.PostalCode == DemandLevel.Require;
			this.timezoneRequiredLabel.Visible = requestFields.TimeZone == DemandLevel.Require;

			this.dateOfBirthRow.Visible = !(requestFields.BirthDate == DemandLevel.NoRequest);
			this.countryRow.Visible = !(requestFields.Country == DemandLevel.NoRequest);
			this.emailRow.Visible = !(requestFields.Email == DemandLevel.NoRequest);
			this.fullnameRow.Visible = !(requestFields.FullName == DemandLevel.NoRequest);
			this.genderRow.Visible = !(requestFields.Gender == DemandLevel.NoRequest);
			this.languageRow.Visible = !(requestFields.Language == DemandLevel.NoRequest);
			this.nicknameRow.Visible = !(requestFields.Nickname == DemandLevel.NoRequest);
			this.postcodeRow.Visible = !(requestFields.PostalCode == DemandLevel.NoRequest);
			this.timezoneRow.Visible = !(requestFields.TimeZone == DemandLevel.NoRequest);
		}
Example #7
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;
        }
		public void EqualityTests() {
			ClaimsRequest req1 = new ClaimsRequest();
			ClaimsRequest req2 = new ClaimsRequest();
			Assert.AreEqual(req1, req2);

			req1.BirthDate = DemandLevel.Request;
			Assert.AreNotEqual(req1, req2);

			req2.BirthDate = DemandLevel.Request;
			req1.Country = DemandLevel.Request;
			Assert.AreNotEqual(req1, req2);
		}
Example #9
0
        protected override void AddNeededExtensions(ref DotNetOpenAuth.OpenId.RelyingParty.IAuthenticationRequest request)
        {
            var sreg = new ClaimsRequest();
            sreg.Nickname = DemandLevel.Require;
            sreg.Email = DemandLevel.Require;
            request.AddExtension(sreg);

            var ax = new FetchRequest();
            ax.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
            ax.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.Alias, true));
            request.AddExtension(ax);
        }
        public IAuthenticationRequest ValidateAtOpenIdProvider(string openIdIdentifier)
        {
            IAuthenticationRequest openIdRequest = openId.CreateRequest(Identifier.Parse(openIdIdentifier));

            var fields = new ClaimsRequest()
            {
                Email = DemandLevel.Require,
                FullName = DemandLevel.Require,
                Nickname = DemandLevel.Require
            };
            openIdRequest.AddExtension(fields);

            return openIdRequest;
        }
		public void UnifyExtensionsAsSregWithSreg() {
			var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) {
				Nickname = DemandLevel.Request,
			};
			this.extensions.Add(sregInjected);
			var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request);
			Assert.AreSame(sregInjected, sreg);
			Assert.AreEqual(DemandLevel.Request, sreg.Nickname);
			Assert.AreEqual(DemandLevel.NoRequest, sreg.FullName);

			var sregResponse = sreg.CreateResponse();
			this.request.AddResponseExtension(sregResponse);
			ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request);
			var extensions = this.GetResponseExtensions();
			Assert.AreSame(sregResponse, extensions.Single());
		}
		public void RequiredOptionalLists() {
			ClaimsRequest req = new ClaimsRequest();
			MessageDictionary dictionary = this.MessageDescriptions.GetAccessor(req);
			Assert.AreEqual(string.Empty, dictionary["required"]);
			Assert.AreEqual(string.Empty, dictionary["optional"]);

			req.BirthDate = DemandLevel.Request;
			req.Nickname = DemandLevel.Require;
			Assert.AreEqual("dob", dictionary["optional"]);
			Assert.AreEqual("nickname", dictionary["required"]);

			req.PostalCode = DemandLevel.Require;
			req.Gender = DemandLevel.Request;
			Assert.AreEqual("dob,gender", dictionary["optional"]);
			Assert.AreEqual("nickname,postcode", dictionary["required"]);
		}
Example #13
0
        public static IOpenIdMessageExtension CreateClaimsRequest()
        {
            var claimsRequest = new ClaimsRequest();

            //claimsRequest.BirthDate = DemandLevel.Require;
            //claimsRequest.Country = DemandLevel.Require;
            claimsRequest.Email = DemandLevel.Require;
            claimsRequest.FullName = DemandLevel.Require;
            //claimsRequest.Gender = DemandLevel.Require;
            //claimsRequest.Language = DemandLevel.Require;
            //claimsRequest.Nickname = DemandLevel.Require;
            //claimsRequest.PostalCode = DemandLevel.Require;
            //claimsRequest.TimeZone = DemandLevel.Require;

            return claimsRequest;
        }
		public override void SetUp() {
			base.SetUp();

			var rp = CreateRelyingParty(true);
			Identifier identifier = this.GetMockIdentifier(ProtocolVersion.V20);
			this.authReq = (AuthenticationRequest)rp.CreateRequest(identifier, RPRealmUri, RPUri);
			this.sreg = new ClaimsRequest {
				Nickname = DemandLevel.Request,
				FullName = DemandLevel.Request,
				BirthDate = DemandLevel.Request,
				Email = DemandLevel.Require,
				Country = DemandLevel.Request,
				PostalCode = DemandLevel.Request,
				Gender = DemandLevel.Request,
				Language = DemandLevel.Request,
				TimeZone = DemandLevel.Request,
			};
		}
        public ClaimsResponse GetOpenIdProfileFields(ClaimsRequest request)
        {
            if (request == null) {
                throw new ArgumentNullException("request");
            }

            ClaimsResponse fields = request.CreateResponse();
            fields.BirthDate = this.DateOfBirth;
            fields.Country = this.countryDropdownList.SelectedValue;
            fields.Email = this.emailTextBox.Text;
            fields.FullName = this.fullnameTextBox.Text;
            fields.Gender = this.Gender;
            fields.Language = this.languageDropdownList.SelectedValue;
            fields.Nickname = this.nicknameTextBox.Text;
            fields.PostalCode = this.postcodeTextBox.Text;
            fields.TimeZone = this.timezoneDropdownList.SelectedValue;
            return fields;
        }
        /// <summary>
        /// Tests equality between two <see cref="ClaimsRequest"/> structs.
        /// </summary>
        /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param>
        /// <returns>
        /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false.
        /// </returns>
        /// <exception cref="T:System.NullReferenceException">
        /// The <paramref name="obj"/> parameter is null.
        /// </exception>
        public override bool Equals(object obj)
        {
            ClaimsRequest other = obj as ClaimsRequest;

            if (other == null)
            {
                return(false);
            }

            return
                (this.BirthDate.Equals(other.BirthDate) &&
                 this.Country.Equals(other.Country) &&
                 this.Language.Equals(other.Language) &&
                 this.Email.Equals(other.Email) &&
                 this.FullName.Equals(other.FullName) &&
                 this.Gender.Equals(other.Gender) &&
                 this.Nickname.Equals(other.Nickname) &&
                 this.PostalCode.Equals(other.PostalCode) &&
                 this.TimeZone.Equals(other.TimeZone) &&
                 this.PolicyUrl.EqualsNullSafe(other.PolicyUrl));
        }
Example #17
0
        public virtual IAuthenticationRequest CreateRequest(AuthRequest authRequest)
        {
            var response = HttpContext.Current.Response;
            var returnTo = new Uri(authRequest.RequestUri, response.ApplyAppPathModifier("~/openid/returnto"));
            var returnToBuilder = new UriBuilder(returnTo) { Path = "/" };

            var realm = returnToBuilder.Uri;
            var request = RelyParty.CreateRequest(authRequest.ProviderUrl, realm, returnTo);

            // Get the common information for user
            var claimsRequest = new ClaimsRequest {
                Email = DemandLevel.Require,
                Nickname = DemandLevel.Require,
                FullName = DemandLevel.Require
            };

            request.AddExtension(claimsRequest);

            var returnUrl = CleanUpRedirectUrl(authRequest.RedirectUrl) ?? "/";
            request.SetCallbackArgument(RedirectUrlKey, returnUrl);

            return request;
        }
 public static IAuthenticationRequest CreateOpenIdRequest(string providerUrl)
 {
     var relyingParty = new OpenIdRelyingParty();
     var request = relyingParty.CreateRequest(Identifier.Parse(providerUrl));
     if (request.Provider.Uri.Host == Google)
     {
         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);
     }
     else
     {
         var claimsRequest = new ClaimsRequest
                                 {
                                     Email = DemandLevel.Require,
                                     FullName = DemandLevel.Require
                                 };
         request.AddExtension(claimsRequest);
     }
     return request;
 }
Example #19
0
        public ActionResult Authenticate(string returnUrl)
        {
            var response = Openid.GetResponse();
            if (response == null)
            {
                Identifier id;
                //make sure users openid_identifier is valid.
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        var uri = new UriBuilder(Url.RouteUrl("default", null, "http"))
                        {
                            Query = string.Format("returnUrl={0}", Uri.EscapeUriString(returnUrl))
                        };
                        IAuthenticationRequest request = Openid.CreateRequest(Request.Form["openid_identifier"], Realm.AutoDetect, uri.Uri);

                        // google openid
                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Web.Blog);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Web.Homepage);
                        request.AddExtension(fetch);

                        // other openid
                        var claims = new ClaimsRequest();
                        claims.FullName = DemandLevel.Require;
                        claims.Email = DemandLevel.Require;
                        request.AddExtension(claims);

                        //request openid_identifier
                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        // TODO handle error message in view
                        TempData["statusMessage"] = ex.Message;
                        return Redirect(returnUrl);
                    }
                }
                else
                {
                    // TODO handle error message in view
                    TempData["statusMessage"] = "Invalid identifier";
                    return Redirect(returnUrl);
                }
            }
            else
            {
                //check the response status
                switch (response.Status)
                {
                    //success status
                    case AuthenticationStatus.Authenticated:

                        string name=null, email=null, url=null;

                        var claims = response.GetExtension<ClaimsResponse>();
                        if (claims != null)
                        {
                            name = claims.FullName;
                            email = claims.Email;
                        }

                        var fetch = response.GetExtension<FetchResponse>();
                        if (fetch != null)
                        {
                            name = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName) ??
                                string.Format("{0} {1}", fetch.GetAttributeValue(WellKnownAttributes.Name.First), fetch.GetAttributeValue(WellKnownAttributes.Name.Last));
                            email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                            url = fetch.GetAttributeValue(WellKnownAttributes.Contact.Web.Homepage) ?? fetch.GetAttributeValue(WellKnownAttributes.Contact.Web.Blog);
                        }

                        CommenterCookieManager.SetCommenterCookieValue(Response, email);
                        var commenter = DbContext.Commenters.SingleOrDefault(c => c.Email == email);
                        if (commenter == null)
                        {
                            DbContext.Commenters.Add(new Commenter
                            {
                                OpenId = response.ClaimedIdentifier.ToString(),
                                Email = email,
                                Name = name,
                                Url = url
                            });
                        }
                        else
                        {
                            commenter.OpenId = commenter.OpenId ?? response.ClaimedIdentifier.ToString();
                        }
                        DbContext.SaveChanges();

                        return Redirect(returnUrl);

                    case AuthenticationStatus.Canceled:
                        // TODO handle error message in view
                        TempData["statusMessage"] = "Canceled at provider";
                        return Redirect(returnUrl);

                    case AuthenticationStatus.Failed:
                        // TODO handle error message in view
                        TempData["statusMessage"] = response.Exception.Message;
                        return Redirect(returnUrl);
                }
            }
            return new EmptyResult();
        }
 private void ParameterizedTypeUriPreservedTest(string typeUri)
 {
     ClaimsRequest request = new ClaimsRequest(typeUri);
     ClaimsResponse response = request.CreateResponse();
     Assert.AreEqual(typeUri, ((IOpenIdMessageExtension)response).TypeUri);
 }
Example #21
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 #22
0
        //[ValidateInput(false)]
        //public ActionResult Authenticate(string returnUrl)
        //{
        //    var response = openid.GetResponse();
        //    if (response == null)
        //    {
        //        // Stage 2: user submitting Identifier
        //        Identifier id;
        //        if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
        //        {
        //            try
        //            {
        //                var request = openid.CreateRequest(Request.Form["openid_identifier"]);
        //                //Ask user for their email address
        //                ClaimsRequest fields = new ClaimsRequest();
        //                fields.Email = DemandLevel.Require;
        //                fields.FullName = DemandLevel.Require;
        //                request.AddExtension(fields);
        //                return request.RedirectingResponse.AsActionResult();
        //            }
        //            catch (ProtocolException ex)
        //            {
        //                ViewData["Message"] = ex.Message;
        //                return View("LogOn");
        //            }
        //        }
        //        ViewData["Message"] = "Invalid identifier";
        //        return View("LogOn");
        //    }
        //    // Stage 3: OpenID Provider sending assertion response
        //    switch (response.Status)
        //    {
        //        case AuthenticationStatus.Authenticated:
        //            MembershipUser user = Membership.GetUser(response.ClaimedIdentifier);
        //            if (user == null)
        //            {
        //                MembershipCreateStatus membershipCreateStatus;
        //                //Get custom fields for user
        //                var sreg = response.GetExtension<ClaimsResponse>();
        //                if (sreg != null)
        //                    Membership.CreateUser(response.ClaimedIdentifier, "12345", sreg.Email, "", "", true, out membershipCreateStatus);
        //                else
        //                    Membership.CreateUser(response.ClaimedIdentifier, "12345", "*****@*****.**", "", "", true, out membershipCreateStatus);
        //                if (membershipCreateStatus == MembershipCreateStatus.Success)
        //                {
        //                    FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
        //                    //FormsService.SignIn(response.ClaimedIdentifier, false /* createPersistentCookie */);
        //                    return RedirectToAction("Index", "home");
        //                }
        //                ViewData["Message"] = "Error creating new user";
        //                return View("LogOn");
        //            }
        //            FormsAuthentication.SetAuthCookie(user.UserName, false);
        //            if (!string.IsNullOrEmpty(returnUrl))
        //            {
        //                return Redirect(returnUrl);
        //            }
        //            return RedirectToAction("Index", "Home");
        //        case AuthenticationStatus.Canceled:
        //            ViewData["Message"] = "Canceled at provider";
        //            return View("LogOn");
        //        case AuthenticationStatus.Failed:
        //            ViewData["Message"] = response.Exception.Message;
        //            return View("LogOn");
        //    }
        //    return new EmptyResult();
        //}
        //public ActionResult LogOn()
        //{
        //    var openid = new OpenIdRelyingParty();
        //    IAuthenticationResponse response = openid.GetResponse();
        //    if (response != null)
        //    {
        //        switch (response.Status)
        //        {
        //            case AuthenticationStatus.Authenticated:
        //                FormsAuthentication.RedirectFromLoginPage(
        //                    response.ClaimedIdentifier, false);
        //                break;
        //            case AuthenticationStatus.Canceled:
        //                ModelState.AddModelError("loginIdentifier",
        //                    "Login was cancelled at the provider");
        //                break;
        //            case AuthenticationStatus.Failed:
        //                ModelState.AddModelError("loginIdentifier",
        //                    "Login failed using the provided OpenID identifier");
        //                break;
        //        }
        //    }
        //    return View();
        //}
        public ActionResult LogOn(string openid_identifier, string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    try
                    {
                        var request = openid.CreateRequest(openid_identifier);

                        //Ask user for their email address
                        ClaimsRequest fields = new ClaimsRequest();
                        fields.Email = DemandLevel.Require;
                        request.AddExtension(fields);

                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData["Message"] = ex.Message;
                        return View();
                    }
                }

                ViewData["Message"] = "Invalid identifier";
                return View();
            }

            // Stage 3: OpenID Provider sending assertion response
            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    UserViewModel user = UserService.UserGet(response.ClaimedIdentifier);
                    if (user == null)
                    {
                        MembershipCreateStatus membershipCreateStatus;

                        //Get custom fields for user
                        var sreg = response.GetExtension<ClaimsResponse>();
                        if (sreg != null)
                            membershipCreateStatus = UserService.UserCreate(response.ClaimedIdentifier, sreg.Email);
                            //Membership.CreateUser(response.ClaimedIdentifier, "12345", sreg.Email, "", "", true, out membershipCreateStatus);
                        else
                            membershipCreateStatus = UserService.UserCreate(response.ClaimedIdentifier, "*****@*****.**");
                            //Membership.CreateUser(response.ClaimedIdentifier, "12345", "*****@*****.**", "", "", true, out membershipCreateStatus);

                        if (membershipCreateStatus == MembershipCreateStatus.Success)
                        {
                           // FormsAuthentication.RedirectFromLoginPage()

                            FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, true);
                            //FormsService.SignIn(response.ClaimedIdentifier, false /* createPersistentCookie */);
                            return RedirectToAction("Details", "home");
                        }
                        ViewData["Message"] = "Error creating new user";
                        return View();
                    }

                   // Membership.DeleteUser(user.UserName, true);

                    FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, true);
                    if (!string.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }

                    return RedirectToAction("Details", "Home");
                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return View();
                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return View();
            }

            return new EmptyResult();
        }
Example #23
0
        public ActionResult OpenIdLogOn(string returnUrl)
        {
            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            if (response == null)  // Initial operation
            {
                try
                {
                    var req = openid.CreateRequest("https://www.google.com/accounts/o8/id");
                    var fields = new ClaimsRequest();
                    var fetch = new FetchRequest();
                    fetch.Attributes.AddRequired(WellKnownAttributes.Contact.Email);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                    fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                    fields.Email = DemandLevel.Require;
                    req.AddExtension(fetch);
                    return req.RedirectingResponse.AsActionResult();
                }
                catch (ProtocolException ex)
                {
                    // display error by showing original LogOn view
                    ModelState.AddModelError("", "Unable to authenticate: " + ex.Message);
                    return View("Login");
                }
            }
            else  // OpenId redirection callback
            {
                // Step 2: OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        string identifier = response.ClaimedIdentifier;
                        //                        var fetch = response.GetExtension<ClaimsResponse>();
                        //                        var email = fetch.Email;
                        var fetch = response.GetExtension<FetchResponse>();
                        var email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);

                        //                        var users = Membership.FindUsersByEmail(email);
                        var user = Membership.GetUser(email);

                        // OpenId lookup fails - Id doesn't exist for login - login first)
                        if (user != null)
                        {
                            FormsAuthentication.SetAuthCookie(user.UserName, false);
                            var profile = UserProfile.GetUserProfile(user.UserName);
                            if (profile.FirstName == null || profile.FirstName == string.Empty)
                            {
                                profile.FirstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                                profile.LastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                                profile.Save();
                            }
                        }
                        else
                        {
                            // User not found create a new user
                            const string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@£$%&";
                            var passwordChars = new char[8];
                            var rand = new Random();
                            var newUser = new RegisterModel
                            {
                                Email = email,
                                UserName = email
                            };
                            newUser.FirstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                            newUser.LastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                            for (var i = 0; i < 8; i++)
                            {
                                passwordChars[i] = allowedChars[rand.Next(0, allowedChars.Length)];
                            }
                            newUser.Password = new string(passwordChars);
                            newUser.ConfirmPassword = newUser.Password;

                            //Create the user and sign in
                            MembershipCreateStatus createStatus;
                            Membership.CreateUser(newUser.UserName, newUser.Password, newUser.Email, null, null, true, null, out createStatus);

                            if (createStatus == MembershipCreateStatus.Success)
                            {
                                FormsAuthentication.SetAuthCookie(newUser.UserName, false /* createPersistentCookie */);

                                var profile = UserProfile.GetUserProfile(newUser.UserName);
                                profile.FirstName = newUser.FirstName;
                                profile.LastName = newUser.LastName;
                                profile.Save();
                            }
                            else
                            {
                                ModelState.AddModelError("", ErrorCodeToString(createStatus));
                                return View("Register");
                            }

                        }

                        if (!string.IsNullOrEmpty(returnUrl))
                            return Redirect(returnUrl);

                        return RedirectToAction("Index", "Home");

                    case AuthenticationStatus.Canceled:
                        ModelState.AddModelError("", "Authentication cancelled at google");
                        return View("Login");
                    case AuthenticationStatus.Failed:
                        ModelState.AddModelError("", "Authentication FAILED");
                        return View("Login");
                }
            }
            return new EmptyResult();
        }
        public ActionResult Authenticate(string returnUrl)
        {
            var response = openid.GetResponse();
            if (response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(Request.Form["openid_identifier"], out id))
                {
                    try
                    {
                        var claimRequest = new ClaimsRequest();
                        claimRequest.Email = DemandLevel.Require;
                        claimRequest.FullName = DemandLevel.Require;
                        claimRequest.BirthDate = DemandLevel.Request;
                        claimRequest.TimeZone = DemandLevel.Request;

                        var theRequest = openid.CreateRequest(Request.Form["openid_identifier"]);
                        theRequest.AddExtension(claimRequest);

                        return theRequest.RedirectingResponse.AsActionResult(); ;
                    }
                    catch (ProtocolException ex)
                    {
                        ViewData["Message"] = ex.Message;
                        return View("Login");
                    }
                }
                else
                {
                    ViewData["Message"] = "Invalid identifier";
                    return View("Login");
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        var claimsResponse = response.GetExtension<ClaimsResponse>();

            //                        Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                        Session["FriendlyIdentifier"] = claimsResponse.Email;
                        FormsAuthentication.SetAuthCookie(response.ClaimedIdentifier, false);
                        if (!string.IsNullOrEmpty(returnUrl))
                        {
                            return Redirect(returnUrl);
                        }
                        else
                        {
                            return RedirectToAction("Index", "Home");
                        }
                    case AuthenticationStatus.Canceled:
                        ViewData["Message"] = "Canceled at provider";
                        return View("Login");
                    case AuthenticationStatus.Failed:
                        ViewData["Message"] = response.Exception.Message;
                        return View("Login");
                }
            }
            return new EmptyResult();
        }
Example #25
0
        public ActionResult LogOn(string openid_identifier)
        {
            var openid = new OpenIdRelyingParty();

            IAuthenticationRequest request = openid.CreateRequest(Identifier.Parse(openid_identifier));

            //FetchRequest fr = null;
            //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);

            var fields = new ClaimsRequest();
            fields.Email = DemandLevel.Require;
            fields.FullName = DemandLevel.Require;
            request.AddExtension(fields);

            return request.RedirectingResponse.AsActionResult();
        }
        /// <summary>
        /// Starts the OpenId flow
        /// </summary>
        public ActionResult OpenIdStartLogin(string openidIdentifier, string returnUrl)
        {
            if (!this.Config.AuthenticationProviders.SSOOpenId.IsDefined)
            {
                return ResultHelper.ForbiddenResult(this);
            }

            if (!String.IsNullOrEmpty(this.Config.AuthenticationProviders.SSOOpenId.Identifier))
            {
                openidIdentifier = this.Config.AuthenticationProviders.SSOOpenId.Identifier;
            }

            Identifier id;
            if (Identifier.TryParse(openidIdentifier, out id))
            {
                //Build openid return urls
                var returnAbsoluteUrl = new Uri(Request.Url, Url.Action("OpenIdFinishLogin", new
                {
                    returnUrl = returnUrl
                }));

                var realmUrl = new Uri(Request.Url, "/");

                OpenIdRelyingParty openid = new OpenIdRelyingParty();
                var authenticationRequest = openid.CreateRequest(id, realmUrl, returnAbsoluteUrl);

                if (this.Config.AuthenticationProviders.SSOOpenId.EnableClaimsRequest)
                {
                    var claimsRequest = new ClaimsRequest {Nickname = DemandLevel.Require, Email = DemandLevel.Request, BirthDate = DemandLevel.Request};

                    authenticationRequest.AddExtension(claimsRequest);
                }

                return authenticationRequest.RedirectingResponse.AsActionResult();
            }
            throw new FormatException("openid identifier not valid");
        }
		public string CreateRequestWithSimpleRegistration(string userSuppliedIdentifier, string realm, string returnToUrl, string optionalSreg, string requiredSreg) {
			var request = relyingParty.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl));

			ClaimsRequest sreg = new ClaimsRequest();
			if (!string.IsNullOrEmpty(optionalSreg)) {
				sreg.SetProfileRequestFromList(optionalSreg.Split(','), DemandLevel.Request);
			}
			if (!string.IsNullOrEmpty(requiredSreg)) {
				sreg.SetProfileRequestFromList(requiredSreg.Split(','), DemandLevel.Require);
			}
			request.AddExtension(sreg);
			return request.RedirectingResponse.GetDirectUriRequest(relyingParty.Channel).AbsoluteUri;
		}
		public void UnifyExtensionsAsSregWithBothSregAndAX() {
			var sregInjected = new ClaimsRequest(DotNetOpenAuth.OpenId.Extensions.SimpleRegistration.Constants.TypeUris.Standard) {
				Nickname = DemandLevel.Request,
			};
			this.extensions.Add(sregInjected);
			var axInjected = new FetchRequest();
			axInjected.Attributes.AddOptional(WellKnownAttributes.Contact.Email);
			this.extensions.Add(axInjected);
			var sreg = ExtensionsInteropHelper.UnifyExtensionsAsSreg(this.request);
			Assert.AreSame(sregInjected, sreg);
			Assert.AreEqual(DemandLevel.Request, sreg.Nickname);
			Assert.AreEqual(DemandLevel.NoRequest, sreg.Email);

			var sregResponseInjected = sreg.CreateResponse();
			sregResponseInjected.Nickname = "andy";
			this.request.AddResponseExtension(sregResponseInjected);
			var axResponseInjected = new FetchResponse();
			axResponseInjected.Attributes.Add(WellKnownAttributes.Contact.Email, "*****@*****.**");
			this.request.AddResponseExtension(axResponseInjected);
			ExtensionsInteropHelper.ConvertSregToMatchRequest(this.request);
			var extensions = this.GetResponseExtensions();
			var sregResponse = extensions.OfType<ClaimsResponse>().Single();
			Assert.AreEqual("andy", sregResponse.Nickname);
			var axResponse = extensions.OfType<FetchResponse>().Single();
			Assert.AreEqual("*****@*****.**", axResponse.GetAttributeValue(WellKnownAttributes.Contact.Email));
		}
Example #29
0
        public ActionResult Authenticate()
        {
            string provider = Request.Form["openid_identifier"];

            var response = openid.GetResponse();
            if (response == null)
            {
                Identifier id = null;
                if (Identifier.TryParse(provider, out id))
                {
                    // Redirect user to provider for authentication
                    try
                    {
                        var request = openid.CreateRequest(id);
                        var fields = new ClaimsRequest()
                        {
                            Email = DemandLevel.Require,
                            FullName = DemandLevel.Require,
                            Nickname = DemandLevel.Require
                        };
                        request.AddExtension(fields);

                        var fetch = new FetchRequest();
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.Alias);
                        fetch.Attributes.AddRequired(WellKnownAttributes.Name.FullName);
                        request.AddExtension(fetch);

                        return request.RedirectingResponse.AsActionResult();
                    }
                    catch (ProtocolException e)
                    {
                        ViewData["Message"] = e.Message;
                    }
                }
            }
            else
            {
                // Handle response from provider
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        var claimedIdentifier = response.ClaimedIdentifier.ToString();
                        var user = TodoContext.Current.Users.Where(u => u.OpenId == claimedIdentifier).FirstOrDefault();

                        if (user == null)
                        {
                            var claim = response.GetExtension<ClaimsResponse>();
                            var fetch = response.GetExtension<FetchResponse>();

                            // Create the new user
                            user = ModelContext.Create<User>();
                            user.Name = fetch.Attributes[WellKnownAttributes.Name.First].Values[0];
                            user.OpenId = claimedIdentifier;

                            // Add a default list to the new user
                            var defaultList = ModelContext.Create<List>();
                            defaultList.Name = "My First List";
                            user.Lists.Add(defaultList);

                            // Add a default item to the default list
                            var defaultItem = ModelContext.Create<ListItem>();
                            defaultItem.DateCreated = DateTime.Now;
                            defaultItem.DueDate = DateTime.Now;
                            defaultItem.Description = "Be Productive!";
                            defaultList.Items.Add(defaultItem);

                            // Save the new user
                            TodoContext.Current.SaveChanges();
                        }

                        FormsAuthenticationTicket authTicket = new
                            FormsAuthenticationTicket(1, //version
                            response.ClaimedIdentifier, // user name
                            DateTime.Now,             //creation
                            DateTime.Now.AddMinutes(30), //Expiration
                            false, //Persistent
                            user.OpenId);

                        string encTicket = FormsAuthentication.Encrypt(authTicket);

                        this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

                        return RedirectToAction("Index", "Home");
                    case AuthenticationStatus.Canceled:
                        break;
                    case AuthenticationStatus.Failed:
                        break;
                }
            }

            return RedirectToAction("Index", "Home");
        }
Example #30
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);
			}
		}
Example #31
0
        public virtual ActionResult Authenticate(string openid_provider)
        {
            var openid = new OpenIdRelyingParty();
            var response = openid.GetResponse();

            Logger.InfoFormat("Trying to log-on user using OpenId Identifier: {0} .", openid_provider);

            if (response == null)
            {
                var request = openid.CreateRequest(openid_provider);

                var claim = new ClaimsRequest
                                {
                                    Email = DemandLevel.Require,
                                    Nickname = DemandLevel.Require,
                                    FullName = DemandLevel.Request,
                                };

                var fetch = new FetchRequest();
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.First);
                fetch.Attributes.AddRequired(WellKnownAttributes.Name.Last);

                request.AddExtension(claim);
                request.AddExtension(fetch);

                return request.RedirectingResponse.AsActionResult();
            }

            if (response.Status == AuthenticationStatus.Authenticated)
            {
                var claim = response.GetExtension<ClaimsResponse>();
                var fetch = response.GetExtension<FetchResponse>();
                var nick = response.FriendlyIdentifierForDisplay;
                var email = string.Empty;

                if (claim != null)
                {
                    nick = string.IsNullOrEmpty(claim.Nickname) ? claim.FullName : claim.Nickname;
                    email = claim.Email;
                }

                if (string.IsNullOrEmpty(nick) && fetch != null &&
                    fetch.Attributes.Contains(WellKnownAttributes.Name.First) &&
                    fetch.Attributes.Contains(WellKnownAttributes.Name.Last))
                {
                    nick = fetch.GetAttributeValue(WellKnownAttributes.Name.First) + " " +
                           fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                }

                var user = string.Format("{0} <{1}>", nick, email);

                FormsService.SignIn(user);

                Logger.InfoFormat("User {0} authenticated successfully.", user);

                return RedirectToAction("Index", "Home");
            }

            Logger.Warn("User attempted login but password validation failed.");
            ModelState.AddModelError("", "Authentication failed.");

            return View("LogOn");
        }