Jump to content

Multiple OAuth 2.0 autorization with TCP on localhost


Recommended Posts

I want to get access code for some REST API website (www.allegro.pl) which use OAuth 2.0 protocol. I have code which works fine. After code execution, new tab in my default browser is open with the webpage where I enter login and password and then script read the access code using TCP build in functions in AutoIt.

Everything works good but when I try to use my function in loop for multiple accounts then it works only for the first time, the other time TCPRecv() return empty string. I am not familiar with TCP stuff. Maybe there is some more experienced user here who can help me to figure this out?

#include <MsgBoxConstants.au3>
#include <WinAPIError.au3>
#include <Array.au3>


Global $g_ALLEGRO_CLIENT_ID = "123456789" ; not real data
Global $g_URL_REDIRECTION = "http://localhost:80"
GLobal $g_URL = "https://allegro.pl/auth/oauth/authorize?response_type=code&client_id=" & $g_ALLEGRO_CLIENT_ID & "&redirect_uri=" & $g_URL_REDIRECTION
Global $g_IP = "127.0.0.1"
Global $g_PORT = 80
Global $g_aAccessCodes[0]

For $i=0 to 12
    $access_code = Oauth($g_URL, $g_IP, $g_PORT)
    _ArrayAdd($g_aAccessCodes, $access_code)
Next

_ArrayDisplay($g_aAccessCodes)

Func OAuth($url, $ip, $port)
    TCPStartup() ; Start the TCP service.

    ; Register OnAutoItExit to be called when the script is closed.
    OnAutoItExitRegister("OnAutoItExit")

    ; Assign a Local variable the Listening socket and bind to the IP Address and Port specified with a maximum of 100 pending connexions.
    Local $MainSocketIdentifier = TCPListen($ip, $port, 100)
    if @error then Exit MsgBox($MB_ICONERROR, Default, "TCPListen() error. Could not listen, Error code: " & @error & @CRLF & @CRLF & _WinAPI_GetErrorMessage(@error))

    ShellExecute($url)

    Local $hTimer = TimerInit()
    Local $bErrorTimeout = False
    Local $ConnectedSocketIdentifier
    Do ; Wait for someone to connect (Unlimited).
        ; Accept incomming connexions if present (Socket to close when finished; one socket per client).
        $ConnectedSocketIdentifier = TCPAccept($MainSocketIdentifier)
        If @error Then Exit MsgBox($MB_ICONERROR, Default, "Could not accept the incoming connection, Error code: " & @error & @CRLF & @CRLF & _WinAPI_GetErrorMessage(@error))
        If TimerDiff($hTimer) > (1000 * 10) Then
            $bErrorTimeout = True
            ExitLoop
        EndIf
        Sleep(100)
    Until $ConnectedSocketIdentifier <> -1
    If $bErrorTimeout Then Exit MsgBox($MB_ICONERROR, Default, "TCPAccept() timeout")

    ; Close the Listening socket to allow afterward binds.
    TCPCloseSocket($MainSocketIdentifier)

    ; Assign a Local variable the data received.
    Local $sReceived = TCPRecv($ConnectedSocketIdentifier, 1024)
    $sReceived = BinaryToString($sReceived, 4)
    ConsoleWrite("$sReceived: " & $sReceived & @CRLF)

    Local $aReg = StringRegExp($sReceived, "(?m)(?s)\?code=(.*) HTTP", 3)
    Local $sAuthorizationCode = ""
    If IsArray($aReg) Then $sAuthorizationCode = $aReg[0]
    ConsoleWrite("$sAuthorizationCode: [" & $sAuthorizationCode & "]" & @CRLF)

    TCPSend($ConnectedSocketIdentifier, "The authentication flow has completed. You may close this window.")
    If $ConnectedSocketIdentifier <> -1 Then
        TCPCloseSocket($ConnectedSocketIdentifier)
        TCPShutdown()
    EndIf

    Local $sCode = $sAuthorizationCode
    if $sCode = "" then Exit MsgBox($MB_ICONERROR, Default, "Unable To Get Access Code")
    ConsoleWrite("Access Code: " & $sCode & @CRLF)
    Return $sCode
EndFunc

Func OnAutoItExit()
    TCPShutdown() ; Close the TCP service.
EndFunc   ;==>OnAutoItExit
Edited by maniootek
Link to comment
Share on other sites

9 hours ago, maniootek said:

Everything works good but when I try to use my function in loop for multiple accounts then it works only for the first time, the other time TCPRecv() return empty string.

Q1: Multpile times per each account ?
Q2: How you loop them ?
Q3: Do you close connection each time ?
Q4: Do you store connection handle for each account separately ?
Q5: Did you try winhttp.au3 ?
 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

9 minutes ago, mLipok said:

Q1: Multpile times per each account ?
Q2: How you loop them ?
Q3: Do you close connection each time ?
Q4: Do you store connection handle for each account separately ?
Q5: Did you try winhttp.au3 ?
 

Q1. I have 12 accounts and I want to get API access code for each of them using OAuth protocol
Q2. I use my OAuth() function in loop and I store API access codes in array $g_aAccessCodes
Q3. Yes I use TCPCloseSocket() and TCPShutdown() but it looks like TCPShutdown() does not reset TCP session I made
Q4. There is no such a thing as connection handle, there is sockets which I close
Q5. I didn't try winhttp.au3. As I said, I am not familiar with http/web stuff. The code I posted was oryginally wrote by @Danyfirex long time ago

Link to comment
Share on other sites

Maybe there is more simple way to get what I want.

Let me explain what I need to do:

1. Go to the webpage with special url
this I can do using code ShellExecute($url) which open new tab with that url in my default browser like Google Chrome

2. On that webpage there is a form to log in with username and password.
This must be done manually by user and we wait for it

3. After user logged in, webpage redirect to new address in localhost (could be specified some web server too but I want to do it locally on user computer) with special code in address bar which I need to read, but I don't know how?

Maybe there is easier way? I can do it easily with IE.au3 with code:
 

EPropertyGet($oIE, "locationurl")

but it's not supported anymore on my users computer.
 

image.png.b7a687dcfcdc34bf81293def7d2a8405.png

Link to comment
Share on other sites

I also noticed that when I close all sockets with TCPCloseSocket() function and close TCP session with TCPShutdown() function then when I run this command:

Quote

netstat -ano | find "127.0.0.1:80"

with my cmd.exe as admin then I still got this entry with TIME_WAIT state for like 1 minute:

Quote

  TCP    127.0.0.1:80           127.0.0.1:59566        TIME_WAIT       0

Like session is still open or something. It's not closed fully yet. Maybe this is the problem?

image.png.ff00f0bc5c77f9ffb867596470e31356.png

Link to comment
Share on other sites

OK I think I solved the problem. I just have to wait few seconds after TCPShutdown() function is called
All entries in netstat with SYN_SENT state must gone before I use TCPStartup() function again

image.png.0a1e4db9ba366a02cdc18cb1c92118ee.png

Link to comment
Share on other sites

Still I think you can do it better with winhttp.au3

EDIT:
For example you should be able to handle connection to each account and just switch between them without a need to start/stop new connection for each loop iteration.

Edited by mLipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...