Вход в переполнение стека с помощью cURL

Я работаю над проектом, и я хочу войти в Qaru через cURL.

Я использую Google как поставщик openID, что означает, что мне нужно сначала войти в Google через свой API.

Вот код, который у меня есть до сих пор:

#!/bin/sh
. ./params.sh #the script with $username and $password
curl --silent https://www.google.com/accounts/ClientLogin \
-d Email=$username -d Passwd=$password \
-d accountType=GOOGLE \
-d source=localhost-test-1 \
-d service=lso \
-o tokens
. ./tokens
echo $Auth; #$Auth is correct here - I did not get a BadAuth error.

endpoint="https://www.google.com/accounts/o8/id";

curl http://stackoverflow.com/users/authenticate \
    -d "openid_identifier=$endpoint" \
    -w %{redirect_url}> ./google_url
google_url=$(cat ./google_url);
echo $google_url;
echo;
echo;
echo;
curl -L --silent --header "Authorization: GoogleLogin auth=$Auth" $google_url;

На этом этапе я получаю страницу от Google, сообщающую мне, что Qaru хочет получить информацию, и я должен войти в систему. Согласно эта страница, часть --header ... $Auth должна считаться логином и перенаправлять меня на Stack Overflow.

Вот форма, которую я получаю, когда запускаю этот script:

<form id="gaia_universallogin"
      action="https://www.google.com/accounts/ServiceLoginAuth?service=lso" method="post">
  <input type="hidden" name="continue" id="continue"
           value="https://www.google.com/accounts/o8/ud?st=SOME_KEY" />
  <input type="hidden" name="service" id="service"
           value="lso" />
  <input type="hidden" name="dsh" id="dsh"
           value="SOME_NEG_NUMBER" />
</form>

Когда я попробую ответить ниже, я получаю следующую ошибку:

    Can't call method "attr" on an undefined value at - line 8.
    curl: (3) <url> malformed
--></style>

вот результат от google2.html

<form id="gaia_loginform"      
        action="https://www.google.com/accounts/ServiceLoginAuth?service=lso" method="post"                >
  <input type="hidden" name="continue" id="continue"            value="https://www.google.com/accounts/o8/ud?st=RNADOM" />
  <input type="hidden" name="service" id="service"            value="lso" />
  <input type="hidden" name="dsh" id="dsh"            value="NEG_NUMEBER" />
  <input type="hidden"              name="GALX"             value="ABCD" />
  <input type="text" name="Email"  id="Email" />
  <input type="password"   name="Passwd" id="Passwd" > 
  <input type="checkbox" name="PersistentCookie" id="PersistentCookie"    value="yes"
  <input type="hidden" name='rmShown' value="1" />
  <input type="submit" class="gaia le button" name="signIn" id="signIn"                 />
<input type="hidden" name="asts"    >
</form>

Ответы

Ответ 1

Служба входа в Google предназначена для конкретной службы, которую вы используете (документы Google против Google Analytics и Карты Google и т.д.). Указанная служба (lh2) относится к Google Picasa.

К сожалению, похоже, что для OpenId эквивалентный код (по крайней мере, не тот, который я мог найти!)

Страница, которую вы возвращаете из Google, должна содержать форму входа. Если вы посмотрите на это, можно будет создать вызов curl для входа в систему; который затем должен перенаправить вас обратно в SO (или любую страницу openID, к которой вы хотите войти) войти в систему.

Оказалось, что делать это немного сложно, потому что вам нужно разобрать некоторые поля формы, чтобы отправить их обратно в Google, а также потому, что Google не отправляет прямой HTTP-перенаправление, а HTML-документ с тегом <meta http-equiv="redirect" ...>. И, конечно же, вы должны включить файлы cookie. Но все это возможно в script с использованием curl - для меня следующие работы:

#!/bin/bash

# Utility function for parsing values out of an HTML form
get_value()
{
    local tagtype="$1" attrname="$2" attrvalue="$3" getattr="$4"
    perl -MHTML::TreeBuilder - "[email protected]" <<EOF
         @[email protected];
         \$h=HTML::TreeBuilder->new;
         \$h->parse_file("$htmlfile");
         while (\$#args > 0) {
             \$h=\$h->look_down(_tag => shift @args,
                                shift @args => shift @args);
         }
         print \$h->attr(shift @args);
EOF
}

# Empty the cookie jar
cj="cookiejar"
rm -f "$cj"

# Attempt to log in to SO. This will redirect to a google URL.
endpoint="https://www.google.com/accounts/o8/id"

google_url=`curl -L -s -S http://stackoverflow.com/users/authenticate \
    -d "openid_identifier=$endpoint" \
    -o /dev/null -b "$cj" -c "$cj" \
    -w %{url_effective}`
echo $google_url
echo
echo

# Retrieve the form from Google
htmlfile=googleform.html
curl -L -s -S -o "$htmlfile" -b "$cj" -c "$cj" "$google_url"

# Parse out the form fields
form_url=`get_value form id gaia_loginform action`

fdsh=`get_value form id gaia_loginform input name dsh value`
fcontinue=`get_value form id gaia_loginform input name continue value`
fservice=`get_value form id gaia_loginform input name service value`
fGALX=`get_value form id gaia_loginform input name GALX value`
frmShown=`get_value form id gaia_loginform input name rmShown value`
fsignIn=`get_value form id gaia_loginform input name signIn value`

fEmail='INSERT LOGIN EMAIL HERE'
fPasswd='INSERT PASSWORD HERE'

# Submit the login form
htmlfile=google2.html
curl -L -s -S -o "$htmlfile" -b "$cj" -c "$cj" --data-urlencode dsh="$fdsh" \
  --data-urlencode continue="$fcontinue" \
  --data-urlencode service="$fservice" \
  --data-urlencode GALX="$fGALX" \
  --data-urlencode Email="$fEmail" \
  --data-urlencode Passwd="$fPasswd" \
  --data-urlencode rmShown="$frmShown" \
  --data-urlencode signIn="$fsignIn" \
  "$form_url"

# Interpret the redirect
redirect=`get_value meta http-equiv refresh content | sed "s/^.*'\(.*\)'.*$/\1/"`

# Follow it
htmlfile=google3.html
curl -L -s -S -o "$htmlfile" -b "$cj" -c "$cj" "$redirect"

(Обратите внимание, что у меня, похоже, немного отличается от вас завиток, поэтому мне пришлось немного изменить параметры -w, я предполагаю, что моя версия будет работать для вас, но вам, возможно, потребуется ее настроить.)