问题
I am using VBA to get authorization in Salesforce and then ultimately want to run a Salesforce report and dump the results in Excel. I have written the following to handle the authorization, but I am getting an unsupported_grant_type error. The code I have so far:
Dim XMLHTTP As New MSXML2.XMLHTTP60
Dim username As String
Dim password As String
Dim PasswordnUsername As String
Dim argumentString As String
username = "myUsername"
password = "myPassword"
PasswordnUsername = password & ":" & username
argumentString = "?grant_type=password&" & _
"client_id=abc123&" & _
"client_secret=123abc&" & _
"username=" & username & "&password=" & password
MsgBox (argumentString)
Set XMLHTTP = CreateObject("MSXML2.XMLHTTP.6.0")
XMLHTTP.Open "POST", "https://mysalesforce.com/services/oauth2/token", False
XMLHTTP.setRequestHeader "content-type", "application/x-www-form-urlencoded"
XMLHTTP.setRequestHeader "Authorization", "basic " + Base64Encode(PasswordnUsername)
XMLHTTP.send (argumentString)
MsgBox (XMLHTTP.responseText)
When I print XMLHTTP.responseText, this is where the unsupported_grant_type is reported.
Any help would be appreciated. Thanks in advance.
T
回答1:
You're using "Username-password flow". All params in the URL, without displaying a popup letting user type his credentials straight to SF (ideally if there's user interaction rather than backend systems talking to each other you're supposed to use another OAuth flow so your app doesn't handle passwords, can't leak them).
Troubleshooting:
- Make sure
username
in your request is encoded. At very least put%40
instead of@
. If your attempt doesn't even show up in user's login history - wrong / incorrectly encoded username. - You might need the security token also silently appended to the password (again, look into user's login history, maybe there's "Failed: API security token required").
- If you use Setup -> My Domain feature, check whether you're allowed to log in from generic
login.salesforce.com
. Maybe your organisation disabled it and allows only the branded login domain (will impact API access too). Or maybe your admins allow logging in only from certain IPs... - Also you don't need to add
Authorization: Basic
+ username & pass in this call, you pass it in POST's payload and that's enough.
If you have Postman, curl, SoapUI or any client like that - might help before jumping straight to VBA?
This works for me (with Content-Type: application/x-www-form-urlencoded
header)
来源:https://stackoverflow.com/questions/53558262/unsupported-grant-type-salesforce-oauth2