![]() |
|
|
|||||||
| Регистрация | << Правила форума >> | FAQ | Пользователи | Календарь | Поиск | Сообщения за сегодня | Все разделы прочитаны |
![]() |
|
|
Опции темы | Поиск в этой теме | Опции просмотра |
|
#1
|
|||
|
|||
|
Есть код на php (https://gist.github.com/moorer2k/562...09ffb402ca6b65)
Мне его нужно повторить на Delphi Что сделал: Код:
function GetAuthToken(var Parse:string):string;
begin
delete(Parse,1,pos('code=',Parse)+4);
Result:=copy(Parse,1,pos('"',Parse)-1);
end;
function GetCookie(var Parse:string):string;
begin
delete(Parse,1,pos('set-cookie',Parse)+11);
Result:=copy(Parse,1,pos(';',Parse)-1);
end;
//function postData($uri, $postData, $returnCookie = false, $cookieSession = '', $lastRequest = false) {
function postData(uri,postData:string; returnCookie:Boolean=False; cookieSession:string=''; lastRequest:Boolean=False):string;
var
Request:TStringList;
Response:TStringStream;
C:string;
begin
Result:='';
Request:=TStringList.Create;
Response:=TStringStream.Create('');
if Length(cookieSession)>1 then
begin
Request.Add(postData);
Form1.idhtp1.Request.CustomHeaders.Text:='Cookie: '+cookieSession;
Form1.idhtp1.Request.Referer:='https://auth.riotgames.com/authorize?redirect_uri=http://localhost/oauth2-callback&client_id=leagueconnect&response_type=code&scope=openid&ui_locales=en-US';
Form1.idhtp1.Request.ContentType:='application/json';
Form1.idhtp1.Post(uri,Request,Response);
end else if lastRequest then
begin
Request.Add(postData);
Form1.idhtp1.Request.CustomHeaders.Text:='';
Form1.idhtp1.Request.Referer:='';
Form1.idhtp1.Request.ContentType:='application/x-www-form-urlencoded; charset=utf-8';
Form1.idhtp1.Request.Accept:='*';
Form1.idhtp1.Request.UserAgent:='LoL%20Friends/490 CFNetwork/758.0.2 Darwin/15.0.0';
Form1.idhtp1.Post(uri,Request,Response);
end else
begin
Request.Add(postData);
Form1.idhtp1.Request.CustomHeaders.Text:='';
Form1.idhtp1.Request.Referer:='https://auth.riotgames.com/authorize?redirect_uri=http://localhost/oauth2-callback&client_id=leagueconnect&response_type=code&scope=openid&ui_locales=en-US';
Form1.idhtp1.Request.ContentType:='application/json';
Form1.idhtp1.Request.Accept:='';
Form1.idhtp1.Request.UserAgent:='';
Form1.idhtp1.Post(uri,Request,Response);
end;
Result:=Response.DataString;
if returnCookie then
begin
C:=Form1.idhtp1.Response.RawHeaders.Text;
Result:=GetCookie(C);
end;
Request.Free;
Response.Free;
end;
//protected function Login($username, $password, $region, $lang) {
procedure Login(username,password,region,lang:string);
const URLs='https://auth.riotgames.com/authz/status';
URLa='https://auth.riotgames.com/authz/auth';
URLt='https://auth.riotgames.com/token';
var
session1,session2,authToken,Request,jRequest:string;
begin
Request:='{"query":"redirect_uri=http:\/\/localhost\/oauth2-callback&client_id=leagueconnect&response_type=code&scope=openid&ui_locales=en-US"}';
session1:=postData(URLs,Request,True);
Request:='{"username":"'+username+'","password":"'+password+'","region":"'+region+'","remember":"true","lang":"'+lang+'"}';
session2:=postData(URLa,Request,False,session1);
authToken:=GetAuthToken(session2);
Request:='grant_type=authorization_code&code='+Trim(authToken)+'&redirect_uri=http%3A%2F%2Flocalhost%2Foauth2-callback&client_id=leagueconnect&client_secret=amVYw7iK_qSaGUNqxRvzgs16EMgdEUdu1mDVdMNJDC4';
jRequest:=postData(URLt,Request,False,'',True);//Тут ошибка 400 Bad Request
end;Парни утверждают что на пыхе этот алгоритм работает. Подскажите пожалуйста что у меня не так? P.S. Когда в С Date: Fri, 25 Aug 2017 14:56:15 GMT Content-Type: application/json; charset=utf-8 Content-Length: 198 Connection: close Set-Cookie: __cfduid=dbb1c2f34bf6bcaaa54d921a09d9ec8e215036729 75; expires=Sat, 25-Aug-18 14:56:15 GMT; path=/; domain=.riotgames.com; HttpOnly cache-control: no-store, no-cache, must-revalidate, proxy-revalidate etag: W/"c6-o9/4vzD5e6gDDB2ZQgRQH7wMrM8" expires: 0 pragma: no-cache set-cookie: did=f7c0e1e0d9ea4a2e91311034621a7fc9; Max-Age=1814400; Path=/; Expires=Fri, 15 Sep 2017 14:56:15 GMT set-cookie: asid=RLfc_ovponIki7dEDGX-GakHO_R26NWfhkVsVzU8VqY; Path=/; HttpOnly; Secure set-cookie: clid=ec1; Max-Age=432000; Path=/; Secure surrogate-control: no-store vary: Accept-Encoding x-content-type-options: nosniff x-download-options: noopen x-newrelic-app-data: PxQDWV9XCgQTVlBaAwEDVVMTGhE1AwE2QgNWEVlbQFtcCxYkSR FBBxdFXRJJM3dgZEtOA0JFXxxLQkJSFhMQQBxSFFIWCAMDBlII UwRQH0BVDw9DSkEPBVJXBVIFAwQEBwgDC0BKBQNcEV0/ X-RiotGames-CDN: Cloudflare Server: cloudflare-nginx CF-RAY: 393f659edbcf86f7-ARN функция GetCookie возвращает did=f7c0e1e0d9ea4a2e91311034621a7fc9 Когда в session2 {"location":"http://localhost/oauth2-callback?code=ZWMxOlo3YVJEQzhFR3ZBWkxqSGFSRTQ0TkEu aEZ2dDhmdFpaeVREekJJVkpIaGktdw%3D%3D","type":"redi rect"} Функция GetAuthToken возвращает ZWMxOlo3YVJEQzhFR3ZBWkxqSGFSRTQ0TkEuaEZ2dDhmdFpaeV REekJJVkpIaGktdw%3D%3D Последний раз редактировалось Shaft, 25.08.2017 в 18:02. |
|
#2
|
|||
|
|||
|
Канечна апшипка...
У тебя реквест в последнем случае сформирован как для строки адреса, а не json. тогда уж должно быть так, наверное: Код:
Request:='grant_type=authorization_code&code='+Trim(authToken)+'&redirect_uri=http%3A%2F%2Flocalhost%2Foauth2-callback&client_id=leagueconnect&client_secret=amVYw7iK_qSaGUNqxRvzgs16EMgdEUdu1mDVdMNJDC4'; jRequest:=postData(URLt + '?' + Request,'',False,'',True); |
|
#3
|
|||
|
|||
|
В общем дело такое, что код на пыхе не работает. Нашел на одном форуме что раньше он работал а сейчас нет. Специально повесил Апач и проверил.
Первые 2 обращения к postData думаю верны. Пробовал в них менять значения и происходит ошибка. Да и authToken сервер присылает. Судя по всему третий запрос не правильно формируется. Расковырял .apk оригинального приложения. Вот код формирования третьего запроса Код:
private String encodeBasicAuth(String paramString1, String paramString2)
{
return Base64Utils.encode(paramString1 + ":" + paramString2);
}
public TokenResponse authenticate(String paramString)
{
try
{
URIBuilder localURIBuilder = new URIBuilder().base(String.format("https://%s/token", new Object[] { this.endpointProvider.get() }));
paramString = new URIBuilder().param("grant_type", "authorization_code").param("code", paramString).param("redirect_uri", (String)this.redirectUrlProvider.get()).build();
Object localObject = encodeBasicAuth((String)this.clientIdProvider.get(), (String)this.clientSecretProvider.get());
localObject = ac.b("Authorization", "Basic " + (String)localObject);
paramString = new HttpDriver.RequestBody("application/x-www-form-urlencoded; charset=utf-8", paramString.getBytes());
paramString = this.http.postAsJson(TokenResponse.class, localURIBuilder.build(), (Map)localObject, paramString);
if (paramString.isSuccessful()) {
return (TokenResponse)paramString.getContent();
}
Log.severe("Failed authorization attempt, " + paramString);
throw new NetworkException(paramString);
}
catch (IOException paramString)
{
Log.severe("Error attempting to refresh, err=" + paramString);
throw new NetworkException(598, paramString.getMessage());
}
}endpointProvider = auth.riotgames.com redirectUrlProvider = http://localhost/oauth2-callback clientIdProvider = leagueconnect clientSecretProvider = amVYw7iK_qSaGUNqxRvzgs16EMgdEUdu1mDVdMNJDC4 paramString который передается в функцию, это authToken полученный после второго запроса Тут я совсем не силен. Если кто знает подскажите как эта функция формирует запрос. Все что я смог это Код:
function encodeBasicAuth(s1,s2:string):string; begin Result:=EncodeBase64(s1+':'+s2); end; Последний раз редактировалось Shaft, 28.08.2017 в 08:57. |