Salesforce REST API: Use the OAuth 2.0 Authentication Username-Password Flow

The Successful Response

The goal of authentication is to receive an authentication_token

If we make a successful OAuth request, we will receive response like this:

id           : https://test.salesforce.com/id/00DR00MAU/005R000
issued_at    : 142622342386
token_type   : Bearer
instance_url : https://jr7.salesforce.com
signature    : 4OF4kF+6e3aVaasdfeaf3NJC9DXm69b2WaJMg=
access_token : 00DR0000001yLiD!ARIAQKLyhA5TIdbsntX_JuHHVI5VW83b8F_VFc_7BnVI

The most important part is the access_token . We use that for REST requests.

With Fiddler

The Raw POST

POST https://test.salesforce.com/services/oauth2/token HTTP/1.1
Host: test.salesforce.com
Content-Type: Application/x-www-form-urlencoded
Content-Length: 235

grant_type=password&client_id=<consumer_id>&client_secret=<consumer_secret>
&username=<username>&password=<password_and_security_token>

Gotchas

With PowerShell

function Get-AuthorizationTokenWithUsernamePasswordFlow ($client_id, $client_secret, $username, $password, $security_token)
{
    Add-Type -AssemblyName System.Web

    $uri = "https://test.salesforce.com/services/oauth2/token";
    $grant_type = "password";

    $username = [System.Web.HttpUtility]::UrlEncode($username)
    $password = [System.Web.HttpUtility]::UrlEncode($password)

    $requestBody = "";
    $requestBody += "grant_type=$grant_type";
    $requestBody += "&client_id=$client_id";
    $requestBody += "&client_secret=$client_secret";
    $requestBody += "&username=$username";
    $requestBody += "&password=$password$security_token";

    Write-Host "Uri:" $uri
    Write-Host "Body:" $requestBody

    Invoke-RestMethod -Method Post -Uri $uri -Body $requestBody
}

# usage
$client_id = "";
$client_secret = "";
$username = "";
$password = "";
$security_token = ""

Get-AuthorizationTokenWithUsernamePasswordFlow $client_id $client_secret $username $password $security_token

With Internet Explorer

This requires a POST and is better with Fiddler or PowerShell.

Helpful Links

URL Encoder

Salesforce OAuth Docs