@DancingOnWater

В чем может быть причина получения 401 кода после успешной авторизации?

Добрый день всем старожилам. Есть такая задача: нужно скачивать в автоматическом режиме с норада определенные tle.

Завел логин, прочитал доку.

Запускаю код примера (пишу на шарпах) отсюда, ан не работает. Пишет, что не авторизован.

Что происходит когда авторизуюсь: Пишу правильный логин-пароль ответ пустой(что странно), если что-то меняю в ответ приходит сообщениях об ошибках (что ожидаемо).

Как дополнительная информация: сижу за прокси, который требует авторизации. Мой код:

public class SpaceTrackConnection
    {
        public SpaceTrackConnection()
        {
            client.Encoding = Encoding.UTF8;
        }

        public bool login(string login, string password)
        {
            client.Proxy = WebProxy.GetDefaultProxy();
                client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            var data = new NameValueCollection
            {
                { "identity", login },
                { "password", password },
                //{ "query", "class/tle_latest/MEAN_MOTION/13--14/orderby/ORDINAL asc/format/tle/metadata/true"}
            };
            byte[] response;
            try{
                response = client.UploadValues(uriBase + "ajaxauth/login", "POST", data);
            }
            catch{
                return false;
            }
            var responseText = Encoding.UTF8.GetString(response);
                responseText.ToLowerInvariant();
            //response =client.DownloadData(uriBase + "basicspacedata/query/class/tle_latest/MEAN_MOTION/13--14/orderby/ORDINAL asc/format/tle/metadata/true");
            return responseText == "\"\"";
        }

        public void logout()
        {
            var tmp = client.UploadValues(uriBase + "ajaxauth/logout", new NameValueCollection());
        }
        public string sendReqest(string request)
        {
            client.Proxy = WebProxy.GetDefaultProxy();
                client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            return Encoding.UTF8.GetString(client.DownloadData(uriBase + request));
        }

        public class WebClientEx : WebClient
        {
            // Create the container to hold all Cookie objects
            private CookieContainer _cookieContainer = new CookieContainer();

            // Override the WebRequest method so we can store the cookie 
            // container as an attribute of the Web Request object
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);

                if (request is HttpWebRequest)
                    (request as HttpWebRequest).CookieContainer = _cookieContainer;

                return request;
            }
        }   // END WebClient Class

        WebClientEx client = new WebClientEx();
        string uriBase   = "https://www.space-track.org/";
    }
  • Вопрос задан
  • 2658 просмотров
Решения вопроса 1
@DancingOnWater Автор вопроса
Проблема была в том, что я посылал Cookie, но не принимал их, работающий код:

public class SpaceTrackConnection
    {
        public SpaceTrackConnection()
        {
            client.Encoding = Encoding.UTF8;
        }

        public bool login(string login, string password)
        {
            try{
                logout();
            }
            catch { }
            
            var data = new NameValueCollection
            {
                { "identity", login },
                { "password", password },
            };
            byte[] response;
            try{
                response = client.UploadValues(uriBase + "auth/login", "POST", data);
            }
            catch{
                return false;
            }
             
            var responseText = Encoding.UTF8.GetString(response);
                responseText.ToLowerInvariant();
            return responseText == "\"\"";
        }

        public void logout()
        {
            var tmp = client.DownloadData(uriBase + "ajaxauth/logout");
        }
        public string sendReqest(string request)
        {
            return Encoding.UTF8.GetString(client.DownloadData(uriBase + request));
        }

        public class WebClientEx : WebClient
        {
            // Create the container to hold all Cookie objects
            private CookieContainer m_cookieContainer = new CookieContainer();

            // Override the WebRequest method so we can store the cookie 
            // container as an attribute of the Web Request object
            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest request = base.GetWebRequest(address);

                if (request is HttpWebRequest)
                {
                    var httpRequest = request as HttpWebRequest;
                    ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
                    httpRequest.Proxy = WebProxy.GetDefaultProxy();
                        httpRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
                    httpRequest.CookieContainer = m_cookieContainer;
                }

                return request;
            }

            protected override WebResponse GetWebResponse(WebRequest request)
            {
                var tmp = base.GetWebResponse(request);
                if( tmp is HttpWebResponse)
                {
                    var resopnse = tmp as HttpWebResponse;
                    m_cookieContainer.Add(resopnse.Cookies);
                }
                return tmp;
            }
        }   // END WebClient Class

        WebClientEx client = new WebClientEx();
        string uriBase   = "https://www.space-track.org/";
    }
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 1
EnterSandman
@EnterSandman
Эникей
wireshark в зубы. пробуете сначала браузером (или чем там надо), потом своим кодом. ищите разницу в алгоритме
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы