Cookie / Авторизация не переносится с POST на GET - PullRequest
0 голосов
/ 10 апреля 2020

Я начал использовать Postman для проверки своих запросов, и теперь я могу аутентифицировать и получать данные, которые я ищу. Когда я пытаюсь сделать то же самое в C#, мне не так много везет. Я понял, что заголовок авторизации «X-com-ibm-team-repository-web-auth-msg» будет существовать только в том случае, если авторизация все еще необходима или если она не удалась. Поскольку теперь он исчезает после попытки аутентификации с помощью «_formPost», я вполне уверен, что это успешно. Когда я делаю «запрос», я снова получаю заголовок с authrequired. Так что это не переносится. Я думаю, что мне нужно сделать что-то еще с печеньем. Что мне нужно сделать?

Обновление: очевидно, проблема заключалась в повторном использовании моего "запроса" HttpWebRequest. Почему я не могу использовать это снова? Почему я должен сделать копию fre sh?

// All the real strings are trustworthy as compared with Postman which works.
string basicCredentials = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(un + ":" + pw));
string formCredentials = "j_username=" + un + "&j_password=" + pw;
string host = "https://my.host.com/ccm/";
string itemUrl = host + "oslc/contexts/_mYsp3ci4lK3y/workitems?stuff"

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(item);
request.Headers.Add("Authorization", basicCredentials);
request.CookieContainer = new CookieContainer(); // Do I need anything more here?
request.Headers.Add("OSLC-Core-Version", "2.0");
request.Accept = "application/rdf+xml";
request.Method = "GET";

WebResponse response = request.GetResponse();
string AuthHeader = response.Headers["X-com-ibm-team-repository-web-auth-msg"];

if (AuthHeader.Equals("authrequired")) // Always does
{
    // Now to authenticate with form authentication
    HttpWebRequest _formPost = (HttpWebRequest)WebRequest.Create(host + "j_security_check"); // Confirmed with Postman
    _formPost.Method = "POST";
    _formPost.Headers.Add("OSLC-Core-Version", "2.0");
    _formPost.UserAgent = "PostmanHadOneSoIPopulatedThis"; // No clue if necessary
    _formPost.Accept = "text/xml";
    _formPost.ContentType = "application/x-www-form-urlencoded";

    // Setting the cookie container to the request's container hoping
    // it would carry over the authorization. Does this get populated on success?
    _formPost.CookieContainer = request.CookieContainer;

    // Oddly enough, I must have basic authorization credentials in order to post my form credentials.
    // Otherwise, without this, it continues to say "authrequired" in the header
    _formPost.Headers.Add("Authorization", basicCredentials); 

    // This must be all good. If/When I mess it up, I get the header "authfailed".
    Byte[] _outBuffer = Encoding.UTF8.GetBytes(formCredentials);
    _formPost.ContentLength = _outBuffer.Length;
    Stream _str = _formPost.GetRequestStream();
    _str.Write(_outBuffer, 0, _outBuffer.Length);
    _str.Close();

    HttpWebResponse _formResponse = (HttpWebResponse)_formPost.GetResponse();
    string _rtcAuthHeader = _formResponse.Headers["X-com-ibm-team-repository-web-auth-msg"];

    // Always null now which means it passed authentication
    if (_rtcAuthHeader == null)
    {
        // Trying the request again
        response = (HttpWebResponse)request.GetResponse();
        // Updating header to check authorization
        _rtcAuthHeader = response.Headers["X-com-ibm-team-repository-web-auth-msg"];

        // _rtcAuthHeader always == authrequired
        // Did not retain authorization.
    }

}

1 Ответ

0 голосов
/ 12 апреля 2020

Видимо не понравилось, что я снова использовал "Запрос". Мне пришлось создать «NewRequest» с теми же данными и повторить попытку. Понятия не имею почему. Если вы знаете, не стесняйтесь поделиться, но это решило мою проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...