Public/Invoke-SfAuthenticate.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<#
    .SYNOPSIS
    Authenticate to Salesforce using the current org configuration

    .DESCRIPTION
    Authenticate to salesforce using the current org configuration

    .INPUTS
    None. You cannot pipe objects to Invoke-SfAuthenticate.

    .OUTPUTS
    Returns as PSCustomObject with the following members:
        access_token
        id
        instance_url
        issued_at
        signature
        token_type

    .EXAMPLE
    PS> $sfAcessToken = (Invoke-SfAuthenticate).access_token

    .LINK
    Set-FileConfig

    .NOTES
    Assumes config is initialized for org access.
#>

function Invoke-SfAuthenticate {
    $config = Get-Config
    $body = @{
        grant_type = "password"
        client_id = $config.SfOauth.GetNetworkCredential().username
        client_secret = $config.SfOauth.GetNetworkCredential().password
        username = $config.SfCredentials.GetNetworkCredential().username
        password = $config.SfCredentials.GetNetworkCredential().password + $config.SfSecurityToken
    }
    $loginUrl = "https://$(&{If($config.Sandbox){"test"} Else {"login"}}).salesforce.com/services/oauth2/token"
    Write-Debug ($Body | ConvertTo-Json)
    Invoke-RestMethod -Uri $loginUrl -Method POST -Body $body -TimeoutSec 30
}