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

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

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

				yield return request;
			}
		}
Example #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MockRealm"/> class.
        /// </summary>
        /// <param name="wrappedRealm">The wrapped realm.</param>
        /// <param name="relyingPartyDescriptions">The relying party descriptions.</param>
        internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions)
            : base(wrappedRealm)
        {
            ErrorUtilities.VerifyArgumentNotNull(relyingPartyDescriptions, "relyingPartyDescriptions");

            this.relyingPartyDescriptions = relyingPartyDescriptions;
        }
Example #3
0
 public void ImplicitConversionToStringTests()
 {
     Realm realm = new Realm("http://host/");
     string realmString = realm;
     Assert.AreEqual("http://host/", realmString);
     realm = null;
     realmString = realm;
     Assert.IsNull(realmString);
 }
        public ActionResult RedirectToProvider(string providerUrl, string returnUrl, FetchRequest fetch)
        {
            var baseUrl = HttpContext.Current.Request.ToPublicUrl(new Uri("/", UriKind.Relative));
            var realm = new Realm(baseUrl);
            var authenticationRequest = _relyingParty.CreateRequest(providerUrl, realm, new Uri(returnUrl,UriKind.Absolute));
            authenticationRequest.AddExtension(fetch);

            return new OutgoingRequestActionResult(authenticationRequest.RedirectingResponse);
        }
Example #5
0
 public override void RequestAuthentication(HttpContextBase context, Uri returnUrl)
 {
     var relyingPartyField = typeof (DotNetOpenAuth.AspNet.Clients.OpenIdClient).GetField("RelyingParty",
         BindingFlags.Static | BindingFlags.NonPublic);
     var providerIdentifierField = typeof (DotNetOpenAuth.AspNet.Clients.OpenIdClient).GetField(
         "providerIdentifier", BindingFlags.NonPublic | BindingFlags.Instance);
     var relyingParty = (OpenIdRelyingParty)relyingPartyField.GetValue(this);
     Realm realm = new Realm(_realmUri ?? new Uri(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)));
     IAuthenticationRequest authenticationRequest = relyingParty.CreateRequest((Identifier) providerIdentifierField.GetValue(this), realm, returnUrl);
     this.OnBeforeSendingAuthenticationRequest(authenticationRequest);
     authenticationRequest.RedirectToProvider();
 }
Example #6
0
        public void EqualsTest()
        {
            Realm testRealm1a = new Realm("http://www.yahoo.com");
            Realm testRealm1b = new Realm("http://www.yahoo.com");
            Realm testRealm2 = new Realm("http://www.yahoo.com/b");
            Realm testRealm3 = new Realm("http://*.www.yahoo.com");

            Assert.AreEqual(testRealm1a, testRealm1b);
            Assert.AreNotEqual(testRealm1a, testRealm2);
            Assert.AreNotEqual(testRealm1a, null);
            Assert.AreNotEqual(testRealm1a, testRealm1a.ToString(), "Although the URLs are equal, different object types shouldn't be equal.");
            Assert.AreNotEqual(testRealm3, testRealm1a, "Wildcard difference ignored by Equals");
        }
Example #7
0
 public static Realm AutoResolve(this Realm input)
 {
     var stringRes = "";
     if (input.Host.ToLower() != "localhost")
     {
         stringRes = input.Scheme + "://" + input.Host + input.PathAndQuery;
         var realmRet = new Realm(
                 stringRes
             );
         return realmRet;
     }
     else
     {
         return input;
     }
 }
		public async Task<IEnumerable<IAuthenticationRequest>> CreateRequestsAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) {
			Requires.NotNull(userSuppliedIdentifier, "userSuppliedIdentifier");
			Requires.NotNull(realm, "realm");
			Requires.NotNull(returnTo, "returnTo");

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

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

			return requests;
		}
        public override void RequestAuthentication(HttpContextBase context, Uri returnUrl)
        {
            var request = Guid.NewGuid();
            var relyingPartyField = typeof(DotNetOpenAuth.AspNet.Clients.OpenIdClient).GetField("RelyingParty",
                BindingFlags.Static | BindingFlags.NonPublic);
            var providerIdentifierField = typeof(DotNetOpenAuth.AspNet.Clients.OpenIdClient).GetField(
                "providerIdentifier", BindingFlags.NonPublic | BindingFlags.Instance);
            var relyingParty = (OpenIdRelyingParty)relyingPartyField.GetValue(this);
            var realm = new Realm(_realmUri ?? new Uri(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)));
            var userSuppliedIdentifier = new Uri((Identifier)providerIdentifierField.GetValue(this));
            var localhost = new Uri(ConfigurationManager.AppSettings["CustomEndpointHost"] ?? "http://localhost/");
            var userSuppliedIdentifierForRequestMachine = new Uri(localhost,
                new Uri(userSuppliedIdentifier.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)).MakeRelativeUri(userSuppliedIdentifier));

            Logger.InfoFormat("Request {0}; userSuppliedIdentifier {1}; userSuppliedIdentifierForRequestMachine {2}", request, userSuppliedIdentifier, userSuppliedIdentifierForRequestMachine);
            IAuthenticationRequest authenticationRequest = relyingParty.CreateRequest(userSuppliedIdentifierForRequestMachine, realm, returnUrl);
            OnBeforeSendingAuthenticationRequest(authenticationRequest);

            try
            {
                var property = authenticationRequest.DiscoveryResult.GetType().GetProperty("ProviderEndpoint");
                var providerEndPointUri = (Uri)property.GetValue(authenticationRequest.DiscoveryResult, null);

                var providerEndPointUriRequestMachine = new Uri(new Uri(context.Request.Url.GetComponents(UriComponents.SchemeAndServer,UriFormat.Unescaped)),
                    new Uri(providerEndPointUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)).MakeRelativeUri(providerEndPointUri));

                Logger.InfoFormat("Request {0}; userSupplied {1}", request, userSuppliedIdentifier);
                property.SetValue(authenticationRequest.DiscoveryResult, providerEndPointUriRequestMachine, BindingFlags.SetProperty, null, null, CultureInfo.CurrentCulture);

                authenticationRequest.RedirectToProvider();
            }
            catch (Exception ex)
            {
                Logger.Error("Error in discovery modification", ex);
                throw;
            }
        }
        //TODO: Redirect to a different action, or give some sort of error message.
        public ActionResult OpenId()
        {
            var response = Openid.GetResponse();
            if (response == null)
            {
                //User submitting Identifier
                Identifier id;
                if (Identifier.TryParse(STEAM_OPENID_URI, out id))
                {
                    try
                    {
                        Realm realm = new Realm(Request.Url.Scheme + "://" + Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped));
                        Uri uri = new Uri(Request.Url.AbsoluteUri, UriKind.Absolute);
                        var request = Openid.CreateRequest(STEAM_OPENID_URI, realm, uri);
                        request.RedirectToProvider();
                        return new EmptyResult();
                    }
                    catch (ProtocolException)
                    {
                        return RedirectToAction("Index");
                    }
                }
                return RedirectToAction("Index");
            }

            switch (response.Status)
            {
                case AuthenticationStatus.Authenticated:
                    return LogOn(response.ClaimedIdentifier);
                case AuthenticationStatus.Canceled:
                    return RedirectToAction("Index");
                case AuthenticationStatus.Failed:
                    return RedirectToAction("Index");
            }
            return RedirectToAction("Index");
        }
		public async Task<ActionResult> AjaxDiscoveryAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) {
			return (await relyingParty.AsAjaxDiscoveryResultAsync(
				await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, privacyPolicy, cancellationToken),
				cancellationToken)).AsActionResult();
		}
		public async Task<IAuthenticationRequest> CreateRequestAsync(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken)) {
			return (await this.CreateRequestsAsync(userSuppliedIdentifier, realm, returnTo, privacyPolicy, cancellationToken)).First();
		}
Example #13
0
        public virtual JsonResult LoginOpenId(LoginOpenIdVM model)
        {
            PartialPostVM returnValue = null;

            if (string.IsNullOrEmpty(model.openid_identifier) || !Identifier.IsValid(model.openid_identifier))
            {
                ModelState.AddModelError("", "The specified login identifier is invalid");
                returnValue = new PartialPostVM
                {
                    Action = PartialPostVM.ActionType.refresh,
                    Message = String.Empty,
                    Content = ControllerExtension.RenderPartialViewToString(this, MVC.Child.Views.LoginOpenId)
                };
            }
            else
            {
                try
                {
                    var openid = new OpenIdRelyingParty();
                    Identifier oiProvider = Identifier.Parse(model.openid_identifier);
                    Realm currentHost = new Realm(InsideWordWebSettings.HostName);
                    Uri returnUrl = new Uri(Url.ActionAbsolute(MVC.Child.LoginOpenIdProcess()));
                    IAuthenticationRequest request = openid.CreateRequest(oiProvider,
                                                                          currentHost,
                                                                          returnUrl);
                    // Request some additional data
                    request.AddExtension(new ClaimsRequest
                    {
                        Email = DemandLevel.Require
                    });

                    returnValue = new PartialPostVM
                    {
                        Action = PartialPostVM.ActionType.redirect,
                        Message = string.Empty,
                        Content = request.RedirectingResponse.Headers["Location"]
                    };

                    string previousUrl = null;
                    if (HttpContext.Request.UrlReferrer != null)
                    {
                        previousUrl = HttpContext.Request.UrlReferrer.AbsoluteUri;
                    }
                    Session[_loginPreviousPageKey] = previousUrl;
                }
                catch (Exception caughtException)
                {
                    InsideWordWebLog.Instance.Log.Error(caughtException);
                    ModelState.AddModelError("", "The specified login identifier is invalid");
                    returnValue = new PartialPostVM
                    {
                        Action = PartialPostVM.ActionType.refresh,
                        Message = String.Empty,
                        Content = ControllerExtension.RenderPartialViewToString(this, MVC.Child.Views.LoginOpenId)
                    };
                }
            }
            return Json(returnValue);
        }
Example #14
0
        public ActionResult Authenticate(string returnUrl, string ticket)
        {
            var r = HttpContext.Request;
            bool updating = !string.IsNullOrEmpty (ticket);
            string loginView = "Login";
            var response = openid.GetResponse ();
            if (response == null) {
                // Stage 2: user submitting Identifier
                Identifier id;
                if (Identifier.TryParse (Request.Form["openid_identifier"], out id)) {
                    try
                    {
                        string host = updating ? Settings.Default.PreviousWebSiteHost : Settings.Default.WebSiteHost;
                        Realm realm;
                        if (host.All (c => char.IsDigit(c) || c=='.' || c==':'))
                            realm = new Realm ("http://" + host);
                        else
                            realm = new Realm ("http://*." + host);

                        IAuthenticationRequest req = openid.CreateRequest (Request.Form["openid_identifier"]);
            //						IAuthenticationRequest req = openid.CreateRequest (Request.Form["openid_identifier"], realm);
                        OutgoingWebResponse res = req.RedirectingResponse;
                        return new InternalOutgoingWebResponseActionResult (res);
                    }
                    catch (ProtocolException ex) {
                        ViewData["Message"] = ex.Message;
                        return View (loginView);
                    }
                }
                else {
                    ViewData["Message"] = "Invalid identifier";
                    return View (loginView);
                }
            }
            else {
                // Stage 3: OpenID Provider sending assertion response
                switch (response.Status) {
                case AuthenticationStatus.Authenticated:

                    User user = CurrentServiceModel.GetUserFromOpenId (response.ClaimedIdentifier);
                    if (updating) {
                        if (user == null) {
                            ViewData["Message"] = "User not registered";
                            return View (loginView);
                        }
                        string newId = GetTicketId (ticket);
                        CurrentServiceModel.UpdateOpenId (response.ClaimedIdentifier, newId);
                        FormsAuthentication.SignOut ();
                    }

                    // This is a new user, send them to a registration page
                    if (user == null) {
                        ViewData["openid"] = response.ClaimedIdentifier;
                        if (Settings.Default.SupportsMultiApps)
                            return Redirect (string.Format ("~/home/User/register?openid={0}", Url.Encode (response.ClaimedIdentifier)));
                        else
                            return Redirect (string.Format ("~/User/register?openid={0}", Url.Encode (response.ClaimedIdentifier)));
                    }

                    Session["FriendlyIdentifier"] = response.FriendlyIdentifierForDisplay;
                    FormsAuthentication.SetAuthCookie (user.Login, false);

                    if (!string.IsNullOrEmpty (returnUrl))
                        return Redirect (returnUrl);
                    else if (updating)
                        return Redirect (ControllerHelper.GetActionUrl ("home", "Index", "Home"));
                    else
                        return RedirectToAction ("Index", "Home");

                case AuthenticationStatus.Canceled:
                    ViewData["Message"] = "Canceled at provider";
                    return View (loginView);
                case AuthenticationStatus.Failed:
                    ViewData["Message"] = response.Exception.Message;
                    return View (loginView);
                }
            }
            return new EmptyResult ();
        }
		public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo) {
			return relyingParty.CreateRequest(userSuppliedIdentifier, realm, returnTo);
		}
Example #16
0
 public IEnumerable<IAuthenticationRequest> CreateRequests(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl)
 {
     return this.actual.CreateRequests(userSuppliedIdentifier, realm, returnToUrl);
 }
 public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy)
 {
     return this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy).First();
 }
 public string PreloadDiscoveryResults(Realm realm, Uri returnTo, Uri privacyPolicy, params Identifier[] identifiers)
 {
     return relyingParty.AsAjaxPreloadedDiscoveryResult(
         identifiers.SelectMany(id => this.CreateRequests(id, realm, returnTo, privacyPolicy)));
 }
 public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl)
 {
     return this.openIdRelyingParty.CreateRequest(userSuppliedIdentifier, realm, returnToUrl);
 }
Example #20
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MockRealm"/> class.
		/// </summary>
		/// <param name="wrappedRealm">The wrapped realm.</param>
		/// <param name="relyingPartyDescriptions">The relying party descriptions.</param>
		internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions)
			: base(wrappedRealm) {
			Requires.NotNull(relyingPartyDescriptions, "relyingPartyDescriptions");

			this.relyingPartyDescriptions = relyingPartyDescriptions;
		}
		public async Task<string> PreloadDiscoveryResultsAsync(Realm realm, Uri returnTo, Uri privacyPolicy, CancellationToken cancellationToken = default(CancellationToken), params Identifier[] identifiers) {
			var results = new List<IAuthenticationRequest>();
			foreach (var id in identifiers) {
				var discoveryResult = await this.CreateRequestsAsync(id, realm, returnTo, privacyPolicy, cancellationToken);
				results.AddRange(discoveryResult);
			}

			return await relyingParty.AsAjaxPreloadedDiscoveryResultAsync(results, cancellationToken);
		}
Example #22
0
        void OpenIDLoginFormHandler(OSHttpRequest httpRequest, OSHttpResponse httpResponse, string openidIdentifier)
        {
            Uri identity;
            Identifier identifier;

            if (String.IsNullOrEmpty(openidIdentifier))
            {
                m_log.Warn("[CABLE BEACH LOGIN]: Received an OpenID login with an empty OpenID URL field");
                CableBeachState.SendLoginTemplate(httpResponse, null, "Please fill in the OpenID URL field");
                return;
            }

            if (UriIdentifier.TryParse(openidIdentifier, out identifier) && Uri.TryCreate(openidIdentifier, UriKind.Absolute, out identity))
            {
                // Check if this identity is authorized for access
                if (CableBeachState.IsIdentityAuthorized(identity))
                {
                    string baseURL = String.Format("{0}://{1}", httpRequest.Url.Scheme, httpRequest.Url.Authority);
                    Realm realm = new Realm(baseURL);

                    try
                    {
                        m_log.Info("[CABLE BEACH LOGIN]: Starting OpenID auth request for " + identity);

                        DotNetOpenAuth.OpenId.RelyingParty.IAuthenticationRequest authRequest =
                            CableBeachState.RelyingParty.CreateRequest(identifier, realm, new Uri(httpRequest.Url, "/login/openid_callback"));

                        // Add a Simple Registration request to the OpenID request
                        ClaimsRequest sreg = new ClaimsRequest();
                        sreg.BirthDate = DemandLevel.Request;
                        sreg.Email = DemandLevel.Request;
                        sreg.FullName = DemandLevel.Request;
                        sreg.Gender = DemandLevel.Request;
                        sreg.Language = DemandLevel.Request;
                        sreg.Nickname = DemandLevel.Request;
                        sreg.TimeZone = DemandLevel.Request;
                        authRequest.AddExtension(sreg);

                        // Add an Attribute Exchange request to the OpenID request
                        FetchRequest ax = new FetchRequest();
                        ax.Attributes.AddOptional(AvatarAttributes.BIOGRAPHY.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.BIRTH_DATE.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.COMPANY.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.EMAIL.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.FIRST_NAME.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.LANGUAGE.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.LAST_NAME.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.TIMEZONE.ToString());
                        ax.Attributes.AddOptional(AvatarAttributes.WEBSITE.ToString());
                        authRequest.AddExtension(ax);

                        OpenAuthHelper.OpenAuthResponseToHttp(httpResponse, authRequest.RedirectingResponse);
                    }
                    catch (Exception ex)
                    {
                        m_log.Error("[CABLE BEACH LOGIN]: OpenID login failed: " + ex.Message, ex);
                        CableBeachState.SendLoginTemplate(httpResponse, null, "OpenID login failed: " + ex.Message);
                    }
                }
                else
                {
                    m_log.Warn("[CABLE BEACH LOGIN]: Identity " + identity + " was denied access");
                    CableBeachState.SendLoginTemplate(httpResponse, null, identity + " is not authorized to access this world");
                }
            }
        }
Example #23
0
        public virtual void RequestAuthentication(HttpContextBase context, Uri returnUrl, StateDictionary state)
        {
			Requires.NotNull(returnUrl, "returnUrl");
            Requires.NotNull(state, "state");
            returnUrl = returnUrl.AttachQueryStringParameter("state", state.ToEncodedString());
			var realm = new Realm(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));
			IAuthenticationRequest request = RelyingParty.CreateRequest(this.providerIdentifier, realm, returnUrl);

			// give subclasses a chance to modify request message, e.g. add extension attributes, etc.
			this.OnBeforeSendingAuthenticationRequest(request);

			request.RedirectToProvider();
		}
Example #24
0
		/// <summary>
		/// Initializes a new instance of the <see cref="MockRealm"/> class.
		/// </summary>
		/// <param name="wrappedRealm">The wrapped realm.</param>
		/// <param name="relyingPartyDescriptions">The relying party descriptions.</param>
		internal MockRealm(Realm wrappedRealm, params RelyingPartyEndpointDescription[] relyingPartyDescriptions)
			: base(wrappedRealm) {
			Contract.Requires<ArgumentNullException>(relyingPartyDescriptions != null);

			this.relyingPartyDescriptions = relyingPartyDescriptions;
		}
 public ActionResult AjaxDiscovery(Identifier userSuppliedIdentifier, Realm realm, Uri returnTo, Uri privacyPolicy)
 {
     return relyingParty.AsAjaxDiscoveryResult(
         this.CreateRequests(userSuppliedIdentifier, realm, returnTo, privacyPolicy)).AsActionResult();
 }
        public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
        {
            HttpRequestInfo requestInfo = OpenAuthHelper.GetRequestInfo(httpRequest);

            try
            {
                UserAuthorizationRequest oauthRequest = CableBeachServerState.OAuthServiceProvider.ReadAuthorizationRequest(requestInfo);

                if (oauthRequest != null && oauthRequest.ExtraData != null)
                {
                    IServiceProviderRequestToken requestToken = CableBeachServerState.OAuthTokenManager.GetRequestToken(oauthRequest.RequestToken);
                    if (requestToken.Callback != null)
                        oauthRequest.Callback = requestToken.Callback;

                    if (oauthRequest.Callback != null)
                    {
                        string capNameList;
                        if (oauthRequest.ExtraData.TryGetValue("cb_capabilities", out capNameList))
                        {
                            // Store the OAuth request state in a temporary dictionary to reference later
                            string[] capNames = capNameList.Split(',');
                            OAuthRequest thisRequest = new OAuthRequest(null, oauthRequest, capNames);
                            CableBeachServerState.OAuthCurrentRequests.AddOrUpdate(oauthRequest.RequestToken, thisRequest,
                                TimeSpan.FromMinutes(CableBeachServerState.OAUTH_OPENID_LOGIN_TIMEOUT_MINUTES));

                            HttpCookie cookie = (httpRequest.Cookies != null) ? httpRequest.Cookies["cb_auth"] : null;
                            AuthCookie authCookie;
                            if (cookie != null && CableBeachServerState.AuthCookies.TryGetValue(cookie.Value, out authCookie))
                            {
                                CableBeachServerState.Log.Debug("[CABLE BEACH SERVER]: Found auth cookie for " + authCookie.Identity);
                                thisRequest.Identity = authCookie.Identity;

                                // Return either a permission grant request page or a successful OAuth authorization response
                                return CableBeachServerState.MakeCheckPermissionsResponse(httpRequest, httpResponse, thisRequest);
                            }

                            #region Start OpenID Auth

                            try
                            {
                                // Redirect the user to do an OpenID login through our trusted identity provider
                                Identifier identifier;
                                Identifier.TryParse(CableBeachServerState.OpenIDProviderUrl.ToString(), out identifier);
                                Realm realm = new Realm(CableBeachServerState.ServiceUrl);

                                IAuthenticationRequest authRequest = CableBeachServerState.OpenIDRelyingParty.CreateRequest(
                                    identifier, realm, new Uri(CableBeachServerState.ServiceUrl, "/oauth/openid_callback"));
                                authRequest.AddCallbackArguments("oauth_request_token", oauthRequest.RequestToken);
                                return OpenAuthHelper.MakeOpenAuthResponse(httpResponse, authRequest.RedirectingResponse);
                            }
                            catch (Exception ex)
                            {
                                CableBeachServerState.Log.Error("[CABLE BEACH SERVER]: OpenID authentication failed: " + ex.Message, ex);
                                httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError;
                                return Encoding.UTF8.GetBytes("OpenID authentication failed: " + ex.Message);
                            }

                            #endregion Start OpenID Auth
                        }
                        else
                        {
                            // No capabilities were requested
                            CableBeachServerState.Log.Error("[CABLE BEACH SERVER]: Got an OAuth request with no capabilities being requested");
                            httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                            return Encoding.UTF8.GetBytes("Unknown capabilities");
                        }
                    }
                    else
                    {
                        // No callback was given
                        CableBeachServerState.Log.Error("[CABLE BEACH SERVER]: Got an OAuth request with no callback");
                        httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                        return Encoding.UTF8.GetBytes("Missing or invalid OAuth callback");
                    }
                }
                else
                {
                    CableBeachServerState.Log.Error("[CABLE BEACH SERVER]: authorize_token called with missing or invalid OAuth request");
                    httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                    return Encoding.UTF8.GetBytes("Missing or invalid OAuth request");
                }
            }
            catch (Exception ex)
            {
                CableBeachServerState.Log.Error("[CABLE BEACH SERVER]: authorize_token called with invalid data");
                httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
                return Encoding.UTF8.GetBytes("Failed to handle OAuth request: " + ex.Message);
            }
        }
Example #27
0
		public virtual async Task RequestAuthenticationAsync(HttpContextBase context, Uri returnUrl, CancellationToken cancellationToken = default(CancellationToken)) {
			Requires.NotNull(returnUrl, "returnUrl");

			var realm = new Realm(returnUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));
			IAuthenticationRequest request = await RelyingParty.CreateRequestAsync(this.providerIdentifier, realm, returnUrl, cancellationToken);

			// give subclasses a chance to modify request message, e.g. add extension attributes, etc.
			this.OnBeforeSendingAuthenticationRequest(request);

			await request.RedirectToProviderAsync(context);
		}
Example #28
0
 public IAuthenticationRequest CreateRequest(Identifier userSuppliedIdentifier, Realm realm, Uri returnToUrl)
 {
     return this.actual.CreateRequest(userSuppliedIdentifier, realm, returnToUrl);
 }