2

I am trying to get the authorization code from my VBA macro as given here, https://learn.microsoft.com/en-us/onedrive/developer/rest-api/getting-started/graph-oauth?view=odsp-graph-online

While I know a web page URL will get the code appended, I am not sure how to get the code value from the redirect Uri in a VBA object in those while I have set the redirect uri for mobile and desktop applications as suggested - "https://login.microsoftonline.com/common/oauth2/nativeclient" for the registered client in azure.

Below is the code,

Dim WinHttpReq As XMLHTTP60
Set WinHttpReq = New XMLHTTP60
myURL="https://login.microsoftonline.com/<MyTenantID>/oauth2/v2.0/authorize?client_id={MyClientID}&response_type=code&redirect_uri={https://login.microsoftonline.com/common/oauth2/nativeclient}&response_mode=query&scope=https://graph.microsoft.com/.default"
WinHttpReq.Open "POST", myURL   
WinHttpReq.send
Debug.Print WinHttpReq.responseText
'Debug.Print WinHttpReq.responseBody

The above code returns some HTML and javascript as the response but not the Authorization code value.

I am trying to follow this - msGraph API from msAccess VBA - Planner plans credentials issue - but it looks like the redirect uri is pointing to web page to get the auth code.

How can I get it in my VBA WinHttpReq object?

codebug
  • 197
  • 1
  • 3
  • 15
  • Did you ever find out how to do this? I've tried a ton of stuff without success. Odd that the http request returns status 200 when it redirects. – Jamie Garroch - MVP Feb 10 '23 at 01:40

1 Answers1

0

I tried this (which works if you pass a redirecting bit.ly URL to it) but for OAuth, since the status returns 200 and not 301, the OAuth flow doesn't seem to look like a redirect as far as the HTTP object is concerned:

With WinHttpReq
    .Open "POST", myURL 
    .Option(6) = True ' 6=WinHttpRequestOption_EnableRedirects
    .Send
    Debug.Print .Option(1) ' 1=WinHttpRequestOption_URL
    Debug.Print .GetResponseHeader("Location")
End With

But this does work:

Function GetAuthCodeIE(myURL As String) As String
    Const READYSTATE_COMPLETE As Long = 4
    
    Dim oIE As Object
    
    Set oIE = CreateObject("InternetExplorer.Application")
    
    oIE.Navigate myURL
    
    ' Wait for response
    While oIE.Busy Or oIE.readyState <> READYSTATE_COMPLETE
        DoEvents
    Wend
    
    Dim Response As String
    Response = oIE.LocationURL
    
    Dim aResponse() As String
    aResponse = Split(Response, "?")
    
    aResponse = Split(aResponse(1), "&")
    GetAuthCodeIE = Replace(aResponse(0), "code=", "")
End Function
Jamie Garroch - MVP
  • 2,839
  • 2
  • 16
  • 24