Trying to get a new token with a Refresh token

38 Views Asked by At

The following code is attempting to get a new token using a refresh token in Basic4android but all that returns is an Error 503. Does it look like the post data is formed correctly?, does the endpoint look correct?

This is the error I get back from MS Graph: {"error":"server_error","error_description":"AADSTS40008: There was an unexpected error from the external identity provider.\r\nTrace ID: 866cab93-5042-43d1-9331-fe5f9b005100\r\nCorrelation ID: 06250287-46ed-4511-9610-fea73d2ea737\r\nTimestamp: 2023-10-20 17:19:41Z","error_codes":[40008],"timestamp":"2023-10-20 17:19:41Z","trace_id":"866cab93-5042-43d1-9331-fe5f9b005100","correlation_id":"06250287-46ed-4511-9610-fea73d2ea737","error_uri":"https://login.microsoftonline.com/error?code=40008"}

Sub RefreshAccessToken(refToken As String) As ResumableSub
    Log("RefreshAccessToken Called with refToken: " & refToken)

    If CheckConnection = False Then
        Log("No network connection. Aborted.")
        Return Null
    End If

    Dim params As Map
    params.Initialize
    params.Put("client_id", ConfigData.clientID)
    params.Put("client_secret", ConfigData.clientSecret)
    params.Put("refresh_token", refToken)
    params.Put("grant_type", "refresh_token")
    'params.Put("scope", ConfigData.clientID & "/.default openid profile offline_access")
    params.Put("scope", "openid profile offline_access https://graph.microsoft.com/.default")
    params.Put("tenant", ConfigData.clientTenant)
    params.Put("redirect_uri", ConfigData.redirectURI)
    Log("Parameters set up.")

    Dim SB As StringBuilder
    SB.Initialize
    For Each key As String In params.Keys
        SB.Append(key).Append("=").Append(params.Get(key)).Append("&")
    Next
    SB.Remove(SB.Length - 1, SB.Length)
    Log("POST data prepared.")

    Try
        'hc.Initialize("hc")
        Log("POST Data: " & SB.ToString)
        req.InitializePost2("https://login.microsoftonline.com/" & ConfigData.clientTenant & "/oauth2/v2.0/token", SB.ToString.GetBytes("UTF8"))
        req.SetContentType("application/x-www-form-urlencoded")
        hc.Execute(req, 1)
        Log("HTTP request executed.")
        'Log("Full URL: " & "https://login.microsoftonline.com/" & ConfigData.clientTenant & "/oauth2/v2.0/token" & SB.ToString.GetBytes("UTF8"))
        Wait For hc_ResponseSuccess (Response As OkHttpResponse, TaskId As Int)
        Wait For hc_ResponseError (Response As OkHttpResponse, Reason As String, StatusCode As Int, TaskId As Int)
        Log("HTTP Response Status: " & Response & " Status Code =" & StatusCode & "Task ID = " & TaskId)
        Log("hc_ResponseSuccess triggered.")
        
        If TaskId = 1 Then
            Response.GetAsynchronously("response", File.OpenOutput(File.DirInternalCache, "response.txt", False), True, TaskId)
            Log("Response being gotten asynchronously.")
            Wait For response_StreamFinish (Success As Boolean, TaskId As Int)
            Log("response_StreamFinish triggered.")
            
            If Success Then
                Try
                    Dim parser As JSONParser
                    parser.Initialize(File.ReadString(File.DirInternalCache, "response.txt"))
                    Dim root As Map = parser.NextObject
                    Log("JSON parsed successfully.")
                    
                    Dim newAccessToken As String = root.Get("access_token")
                    Dim newRefreshToken As String = root.Get("refresh_token")
                    Dim newExpiresIn As Long = root.Get("expires_in")
                    
                    SaveTokens(newAccessToken, newRefreshToken, newExpiresIn, SubFolderID, MainFolderID)
                    Log("Tokens saved successfully.")
                    
                    Return Success  ' Successfully refreshed the token
                Catch
                    Log("JSON Parsing failed: " & LastException.Message)
                    Return Null  ' Failed due to JSON parsing
                End Try
            Else
                Log("Error in response_StreamFinish: " & LastException.Message)
                Return False  ' Failed due to stream finish
            End If
        Else
            Log("Unexpected TaskId: " & TaskId)
            Return Null  ' TaskId doesn't match, ignore
        End If
    Catch
        Log("HTTP Request failed: " & LastException.Message)
        Return Null  ' Failed due to HTTP request
    End Try
End Sub

I have tried different endpoints and redirect URL and still get the same errors.

0

There are 0 best solutions below