Пример #1
0
 public void Provider()
 {
     OpenIdRelyingParty rp = new OpenIdRelyingParty(null, null, null);
     Identifier id = TestSupport.GetMockIdentifier(TestSupport.Scenarios.AutoApproval, ProtocolVersion.V20);
     IAuthenticationRequest request = rp.CreateRequest(id, realm, returnTo);
     Assert.IsNotNull(request.Provider);
 }
Пример #2
0
		public ActionResult Authenticate() {
			var openid = new OpenIdRelyingParty();
			if (openid.Response == null) {
				// Stage 2: user submitting Identifier
				Identifier id;
				if (Identifier.TryParse(Request.Form["openid_identifier"], out id)) {
					openid.CreateRequest(Request.Form["openid_identifier"]).RedirectToProvider();
				} else {
					ViewData["Message"] = "Invalid identifier";
					return View("Login");
				}
			} else {
				// Stage 3: OpenID Provider sending assertion response
				switch (openid.Response.Status) {
					case AuthenticationStatus.Authenticated:
						FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, false);
						break;
					case AuthenticationStatus.Canceled:
						ViewData["Message"] = "Canceled at provider";
						return View("Login");
					case AuthenticationStatus.Failed:
						ViewData["Message"] = openid.Response.Exception.Message;
						return View("Login");
				}
			}
			return new EmptyResult();
		}
Пример #3
0
 protected void yahooLoginButton_Click(object sender, ImageClickEventArgs e)
 {
     OpenIdRelyingParty openid = new OpenIdRelyingParty();
     var req = openid.CreateRequest("yahoo.com");
     req.RedirectToProvider();
     // We don't listen for the response from the provider explicitly
     // because the OpenIdLogin control is already doing that for us.
 }
 public void Login(string id)
 {
     var openid = new OpenIdRelyingParty();
     Identifier identifier;
     if (!string.IsNullOrEmpty(id) && Identifier.TryParse(id, out identifier))
     {
         openid.CreateRequest(
             identifier,
             new Realm(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath),
             new Uri(Url.RouteUrl("Config", new { action = "Login" }, "http"))
         ).RedirectToProvider();
     }
     else
     {
         throw new ArgumentException("Invalid OpenID.");
     }
 }
Пример #5
0
        public ActionResult Authenticate()
        {
            var openid = new OpenIdRelyingParty();
            if (openid.Response == null)
            {
                try
                {
                    var req = openid.CreateRequest(Request.Form["openid_identifier"]);
                    var fields = new ClaimsRequest { Email = DemandLevel.Require, Nickname = DemandLevel.Require };

                    req.AddExtension(fields);
                    req.RedirectToProvider();
                }
                catch (ThreadAbortException) { }
                catch (Exception e) { ViewData["Message"] = e.Message; }

                return View("Login");
            }

            switch (openid.Response.Status)
            {
                case AuthenticationStatus.Authenticated:

                    var fields = openid.Response.GetExtension(typeof(ClaimsResponse)) as ClaimsResponse;

                    if (fields != null)
                    {
                        TempData["Email"] = fields.Email;
                        TempData["Nickname"] = fields.Nickname;
                    }

                    FormsAuthentication.RedirectFromLoginPage(openid.Response.ClaimedIdentifier, true);

                    break;
                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return View("Login");
                case AuthenticationStatus.Failed:
                    ViewData["Message"] = openid.Response.Exception.Message;
                    return View("Login");
            }

            // need this rather than returning an ActionResult.
            return null;
        }
        public Address GetOpenIDAddress(Uri claimUri)
        {
            var openid = new OpenIdRelyingParty();
            Address result=new Address();
            if (openid.Response != null)
            {
                // Stage 2: user submitting Identifier
                var fetch = openid.Response.GetExtension<FetchResponse>();
                if (fetch != null)
                {
                    
                    
                    result.Email = GetFetchValue(fetch, "contact/email");
                    result.FirstName = GetFetchValue(fetch, "namePerson/first");
                    result.LastName = GetFetchValue(fetch, "namePerson/last");
                    result.Street1 = GetFetchValue(fetch, "contact/streetaddressLine1/home");
                    result.Street2 = GetFetchValue(fetch, "contact/streetaddressLine2/home");
                    result.City = GetFetchValue(fetch, "contact/city/home");
                    result.StateOrProvince = GetFetchValue(fetch, "contact/city/stateorprovince");
                    result.Country = GetFetchValue(fetch, "contact/country/home");
                    result.Zip = GetFetchValue(fetch, "contact/postalCode/home");

                    result.UserName = openid.Response.ClaimedIdentifier;

                }
            }
            else
            {
                var request=openid.CreateRequest(claimUri.AbsoluteUri);
                var fetch = new FetchRequest();
                fetch.AddAttribute(new AttributeRequest("contact/email"));
                fetch.AddAttribute(new AttributeRequest("namePerson/first"));
                fetch.AddAttribute(new AttributeRequest("namePerson/last"));
                fetch.AddAttribute(new AttributeRequest("contact/streetaddressLine1/home"));
                fetch.AddAttribute(new AttributeRequest("contact/streetaddressLine2/home"));
                fetch.AddAttribute(new AttributeRequest("contact/city/home"));
                fetch.AddAttribute(new AttributeRequest("contact/city/stateorprovince"));
                fetch.AddAttribute(new AttributeRequest("contact/country/home"));
                fetch.AddAttribute(new AttributeRequest("contact/postalCode/home"));
                request.AddExtension(fetch);
                request.RedirectToProvider();
            }
            return result;
        }
        public bool IsValidLogin(Uri serviceUri)
        {
            bool result = false;
            var openid = new OpenIdRelyingParty();
            if (openid.Response == null)
            {
                // Stage 2: user submitting Identifier
                openid.CreateRequest(serviceUri.AbsoluteUri).RedirectToProvider();
            }
            else
            {
                result = openid.Response.Status == AuthenticationStatus.Authenticated;

                if (result)
                {
                    //synch the users

                }

            }
            return result;
        }
Пример #8
0
        protected void PrepareAuthenticationRequest()
        {
            if (string.IsNullOrEmpty(Text))
                throw new InvalidOperationException(DotNetOpenId.Strings.OpenIdTextBoxEmpty);

            try {
                var consumer = new OpenIdRelyingParty();

                // Resolve the trust root, and swap out the scheme and port if necessary to match the
                // return_to URL, since this match is required by OpenId, and the consumer app
                // may be using HTTP at some times and HTTPS at others.
                UriBuilder realm = getResolvedRealm(RealmUrl);
                realm.Scheme = Page.Request.Url.Scheme;
                realm.Port = Page.Request.Url.Port;

                // Initiate openid request
                Request = consumer.CreateRequest(Text, new Realm(realm));
                Request.Mode = ImmediateMode ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup;
                if (EnableRequestProfile) addProfileArgs(Request);
            } catch (WebException ex) {
                OnFailed(new FailedAuthenticationResponse(ex));
            } catch (OpenIdException ex) {
                OnFailed(new FailedAuthenticationResponse(ex));
            }
        }
Пример #9
0
        public Yield UserLogin(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
            
            string userSuppliedIdentifier = context.GetParam("url", null);
            if (String.IsNullOrEmpty(userSuppliedIdentifier)) {
                _log.Info("No identifier was specified");
                throw new DreamBadRequestException("No identifier was specified.");
            }

            XUri returnUri = new XUri(context.GetParam("returnurl", null));
            String realm = context.GetParam("realm", null);
            if (String.IsNullOrEmpty(realm)) {
                realm = returnUri.WithoutPathQueryFragment().ToString();
            }

            IAuthenticationRequest openIdRequest;

            // dummy parameters required by DotNetOpenId 2.x; in 3.x, you can
            // just pass null to the OpenIdRelyingParty constructor.
            Uri identifierUri = new Uri(userSuppliedIdentifier);
            NameValueCollection queryCol = System.Web.HttpUtility.ParseQueryString(identifierUri.Query);
            OpenIdRelyingParty openid = new OpenIdRelyingParty(null, identifierUri, queryCol);
           
            // creating an OpenID request will authenticate that 
            // the endpoint exists and is an OpenID provider.
            _log.DebugFormat("Creating OpenID request: identifier {0}, return URL {1}, realm {2}", userSuppliedIdentifier, returnUri.ToString(), realm); 

            try {
                openIdRequest = openid.CreateRequest(
                    userSuppliedIdentifier,
                    realm,
                    returnUri.ToUri());
            } catch (OpenIdException ex) {
                _log.WarnFormat("'{0}' rejected as OpenID identifier: {1}", userSuppliedIdentifier, ex.Message);
                throw new DreamBadRequestException(string.Format("'{0}' is not a valid OpenID identifier. {1}", userSuppliedIdentifier, ex.Message));
            }

            // Ask for the e-mail address on this request.
            // Use both SREG and AX, to increase the odds of getting it.
            openIdRequest.AddExtension(new ClaimsRequest{
                Email = DemandLevel.Require,
            });

            var fetch = new FetchRequest();
            fetch.AddAttribute(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
            openIdRequest.AddExtension(fetch);

            // The RedirectingResponse either contains a "Location" header for 
            // a HTTP GET, which will return in the response as 'endpoint', or
            // a HTML FORM which needs to be displayed to the user, which will
            // return in the response as 'form'.
            IResponse wr = openIdRequest.RedirectingResponse;

            XDoc result = new XDoc("openid");
            if (String.IsNullOrEmpty(wr.Headers["Location"])) {
                System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
                string formBody = enc.GetString(wr.Body);
                _log.DebugFormat("OpenID redirect by HTML FORM: {0}", formBody);  
                result.Attr("form", formBody);  
            } else {
                string redirectUrl = wr.Headers["Location"];
                _log.DebugFormat("OpenID redirect URL: {0}", redirectUrl);
                result.Attr("endpoint", redirectUrl);
            }

            response.Return(DreamMessage.Ok(result));
            yield break;
        }
Пример #10
0
        public AuthenticationResult Authenticate(string userIdentifier)
        {
            var openid = new OpenIdRelyingParty();
            if (openid.Response == null)
            {
                // Redirect the user to the provider party. They will login, and be redirected
                // back here.
                try
                {
                    var claims = new ClaimsRequest();
                    claims.Nickname = DemandLevel.Require;
                    claims.FullName = DemandLevel.Require;
                    claims.Email = DemandLevel.Require;
                    claims.PostalCode = DemandLevel.Request;

                    var id = Identifier.Parse(userIdentifier);
                    var request = openid.CreateRequest(userIdentifier);
                    request.AddExtension(claims);
                    request.RedirectToProvider();
                }
                catch (OpenIdException ex)
                {
                    // The user may have entered an incorrectly formatted URI, the server is offline, etc.
                    return new AuthenticationResult() { Cancelled = false, Error = ex, Success = false, Username = userIdentifier };
                }
            }
            else
            {
                // The OpenID provider has processed the user's request and redirected them back here.
                switch (openid.Response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        // Update the member information
                        return new AuthenticationResult() {Cancelled = false, Error = null, Success = true, Username = userIdentifier};
                    case AuthenticationStatus.Canceled:
                        return new AuthenticationResult() {Cancelled = true, Error = null, Success = false, Username = userIdentifier};
                    case AuthenticationStatus.Failed:
                        return new AuthenticationResult() {Cancelled = false, Error = null, Success = false, Username = userIdentifier};
                }
            }
            return null;
        }
Пример #11
0
 public void CreateRequestWithoutContext2()
 {
     var consumer = new OpenIdRelyingParty(new ApplicationMemoryStore(), simpleNonOpenIdRequest, new NameValueCollection());
     consumer.CreateRequest(simpleOpenId, realm);
 }
Пример #12
0
        public void MultipleServiceEndpoints()
        {
            string xrds = @"<?xml version='1.0' encoding='UTF-8'?>
            <XRD xmlns='xri://$xrd*($v*2.0)'>
             <Query>=MultipleEndpoint</Query>
             <Status cid='verified' code='100' />
             <ProviderID>=!91F2.8153.F600.AE24</ProviderID>
             <CanonicalID>=!91F2.8153.F600.AE24</CanonicalID>
             <Service>
              <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID>
              <Type select='true'>xri://+i-service*(+contact)*($v*1.0)</Type>
              <Type match='null'/>
              <Path select='true'>(+contact)</Path>
              <Path match='null'/>
              <MediaType match='default'/>
              <URI append='qxri'>http://contact.freexri.com/contact/</URI>
             </Service>
             <Service priority='20'>
              <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID>
              <Type select='true'>http://openid.net/signon/1.0</Type>
              <Path select='true'>(+login)</Path>
              <Path match='default'/>
              <MediaType match='default'/>
              <URI append='none' priority='2'>http://authn.freexri.com/auth10/</URI>
              <URI append='none' priority='1'>https://authn.freexri.com/auth10/</URI>
             </Service>
             <Service priority='10'>
              <ProviderID>@!7F6F.F50.A4E4.1133</ProviderID>
              <Type select='true'>http://specs.openid.net/auth/2.0/signon</Type>
              <Path select='true'>(+login)</Path>
              <Path match='default'/>
              <MediaType match='default'/>
              <URI append='none' priority='2'>http://authn.freexri.com/auth20/</URI>
              <URI append='none' priority='1'>https://authn.freexri.com/auth20/</URI>
             </Service>
             <ServedBy>OpenXRI</ServedBy>
            </XRD>";
            MockHttpRequest.RegisterMockXrdsResponses(new Dictionary<string, string> {
                {"https://xri.net/=MultipleEndpoint?_xrd_r=application/xrd%2Bxml;sep=false", xrds},
            });
            OpenIdRelyingParty rp = new OpenIdRelyingParty(null, null, null);
            Realm realm = new Realm("http://somerealm");
            Uri return_to = new Uri("http://somerealm/return_to");
            IAuthenticationRequest request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
            Assert.AreEqual("https://authn.freexri.com/auth20/", request.Provider.Uri.AbsoluteUri);
            rp.EndpointOrder = (se1, se2) => -se1.ServicePriority.Value.CompareTo(se2.ServicePriority.Value);
            request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
            Assert.AreEqual("https://authn.freexri.com/auth10/", request.Provider.Uri.AbsoluteUri);

            // Now test the filter.  Auth20 would come out on top, if we didn't select it out with the filter.
            rp.EndpointOrder = OpenIdRelyingParty.DefaultEndpointOrder;
            rp.EndpointFilter = (se) => se.Uri.AbsoluteUri == "https://authn.freexri.com/auth10/";
            request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
            Assert.AreEqual("https://authn.freexri.com/auth10/", request.Provider.Uri.AbsoluteUri);
        }
        public virtual ActionResult OpenIdLogin(string openid_identifier)
        {
            bool rememberMe = false;
            OpenIdRelyingParty openid = new OpenIdRelyingParty();

            // Stage 1: display login form to user
            if (openid.Response == null && Request.HttpMethod != "POST")
            {
                return View("Login");
            } else
            if (openid.Response == null)
            {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse(openid_identifier, out id))
                {
                    openid.CreateRequest(openid_identifier).RedirectToProvider();
                }
                else
                {
                    ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.InvalidIdentifierSpecified);
                    ViewData["openid_identifier"] = openid_identifier;
                    return View("Login");
                }
            }
            else
            {
                // Stage 3: OpenID Provider sending assertion response
                switch (openid.Response.Status)
                {
                    case AuthenticationStatus.Authenticated:

                        // Associate openid identity to user account and login
                        var userName = AssociateOpenIdIdentityToUserName(openid.Response.ClaimedIdentifier);
                        if (string.IsNullOrEmpty(userName))
                        {
                            ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.AssociationFailure);
                            ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                            return View("Login");
                        }
                        FormsAuthentication.RedirectFromLoginPage(userName, rememberMe);
                        break;

                    case AuthenticationStatus.Canceled:
                        ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.CanceledAtProvider);
                        ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                        return View("Login");

                    case AuthenticationStatus.Failed:
                        ViewData.ModelState.AddModelError("openid_identifier", ErrorMessages.UnknownFailure + openid.Response.Exception.Message);
                        ViewData["openid_identifier"] = openid.Response.ClaimedIdentifier;
                        return View("Login");
                }
            }

            return View("Login");
        }
Пример #14
0
		public string CreateRequest(string userSuppliedIdentifier, string realm, string returnToUrl) {
			OpenIdRelyingParty rp = new OpenIdRelyingParty(null, null, null);
			Response response = (Response)rp.CreateRequest(userSuppliedIdentifier, realm, new Uri(returnToUrl)).RedirectingResponse;
			return response.IndirectMessageAsRequestUri.AbsoluteUri;
		}
Пример #15
0
		public void MultipleServiceEndpoints() {
			MockHttpRequest.RegisterMockXrdsResponses(new Dictionary<string, string> {
				{"https://xri.net/=MultipleEndpoint?_xrd_r=application/xrd%2Bxml;sep=false", multipleEndpointXrds},
			});
			OpenIdRelyingParty rp = new OpenIdRelyingParty(null, null, null);
			Realm realm = new Realm("http://somerealm");
			Uri return_to = new Uri("http://somerealm/return_to");
			IAuthenticationRequest request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
			Assert.AreEqual("https://authn.freexri.com/auth20/", request.Provider.Uri.AbsoluteUri);
			rp.EndpointOrder = (se1, se2) => -se1.ServicePriority.Value.CompareTo(se2.ServicePriority.Value);
			request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
			Assert.AreEqual("https://authn.freexri.com/auth10/", request.Provider.Uri.AbsoluteUri);

			// Now test the filter.  Auth20 would come out on top, if we didn't select it out with the filter.
			rp.EndpointOrder = OpenIdRelyingParty.DefaultEndpointOrder;
			rp.EndpointFilter = (se) => se.Uri.AbsoluteUri == "https://authn.freexri.com/auth10/";
			request = rp.CreateRequest("=MultipleEndpoint", realm, return_to);
			Assert.AreEqual("https://authn.freexri.com/auth10/", request.Provider.Uri.AbsoluteUri);
		}
Пример #16
0
      public ActionResult Login(string openid_url)
      {
         if (Identifier.IsValid(openid_url))
         {
            try
            {
               Identifier openId = Identifier.Parse(openid_url);

               OpenIdRelyingParty rp = new OpenIdRelyingParty();
               IAuthenticationRequest request = rp.CreateRequest(openId, new Realm(OpenId.Realm), new Uri(OpenId.LoginUrl));
               request.RedirectToProvider();
            }
            catch (DotNetOpenId.OpenIdException exception)
            {
               ViewData["LoginErrorMessage"] = exception.Message;
               ModelState.AddModelError("LoginError", exception);
            }
         }
         else
         {
            ViewData["LoginErrorMessage"] = "The OpenID you provided is not in the correct format.";
            ModelState.AddModelError("LoginError", "The OpenID you provided is not in the correct format.");
         }

         // if we got here then something went wrong so we go back to the login view.
         return View();
      }
Пример #17
0
   protected void btnLogin_Click(object sender, EventArgs e)
   {
      string openIdUrl = Request["openid_url"];

      if (Identifier.IsValid(openIdUrl))
      {
         try
         {
            Identifier openId = Identifier.Parse(openIdUrl);

            OpenIdRelyingParty rp = new OpenIdRelyingParty();
            IAuthenticationRequest request = rp.CreateRequest(openId, new Realm(OpenId.Realm), new Uri(OpenId.LoginUrl));
            request.RedirectToProvider();
         }
         catch (DotNetOpenId.OpenIdException exception)
         {
            lblError.Text = exception.Message;
         }
         catch (Exception exception)
         {
            lblError.Text = "An unexpected error occured during authentication. (" + exception.Message + ")";
         }
      }
      else
      {
         lblError.Text = "The OpenID you provided is not in the correct format.";
      }
   }
Пример #18
0
      public ActionResult Login(string openid_url)
      {
         //FormsAuth.SetAuthCookie(openid_url, false /* createPersistentCookie */);
         //return RedirectToAction("Index", "Home");

         if (Identifier.IsValid(openid_url))
         {
            try
            {
               Identifier openId = Identifier.Parse(openid_url);

               OpenIdRelyingParty rp = new OpenIdRelyingParty();
               IAuthenticationRequest request = rp.CreateRequest(openId, new Realm(OpenId.Realm), new Uri(OpenId.LoginUrl));
               request.RedirectToProvider();
            }
            catch (DotNetOpenId.OpenIdException exception)
            {
               ModelState.AddModelError("OpenIdException", exception);
            }
            catch (Exception exception)
            {
               ModelState.AddModelError("Authentication", exception);
            }
         }
         else
         {
            ModelState.AddModelError("openid_url", "The OpenID you provided is not in the correct format.");
         }

         // if we got here then something went wrong so wego back to the login view.
         return View();
      }