Public/Get-SFToken.ps1


<#
.SYNOPSIS
Exchanges authentication credentials for an OAuth 2.0 access token.

.DESCRIPTION
Returns an access token for the SuccessFactors API. Supports both the SAML2 assertion flow (with bearer assertion) and the client credentials flow (with client secret). The token is returned with expiry information.

.PARAMETER BaseUrl
The base URL of the SuccessFactors API instance.

.PARAMETER ClientID
The OAuth 2.0 client ID registered in SuccessFactors.

.PARAMETER CompanyID
The SuccessFactors company ID.

.PARAMETER Assertion
The SAML2 assertion (Assertion flow only).

.PARAMETER ClientSecret
The OAuth 2.0 client secret (ClientCredentials flow only).

.PARAMETER ForceNew
Request a new token even if one exists.

.OUTPUTS
Hashtable - Contains access_token, token_type, and expires_in fields.
#>

function Get-SFToken {
    [CmdletBinding(DefaultParameterSetName = 'Assertion')]
    param(
        [Parameter(Mandatory = $true)]
        [string]
        $BaseUrl,

        [Parameter(Mandatory = $true)]
        [string]
        $ClientID,

        [Parameter(Mandatory = $true)]
        [string]
        $CompanyID,

        [Parameter(Mandatory = $true, ParameterSetName = 'Assertion')]
        [string]
        $Assertion,

        [Parameter(Mandatory = $true, ParameterSetName = 'ClientCredentials')]
        [string]
        $ClientSecret,

        [Parameter(Mandatory = $false)]
        [switch]
        $ForceNew
    )

    $uri = "$BaseUrl/oauth/token"

    $tokenHeader = @{
        "Content-Type" = "application/x-www-form-urlencoded"
    }

    if ($PSCmdlet.ParameterSetName -eq 'Assertion') {
        $body = @{
            client_id  = $ClientID
            company_id = $CompanyID
            grant_type = "urn:ietf:params:oauth:grant-type:saml2-bearer"
            assertion  = $Assertion
        }
    } 
    else {
        $body = @{
            client_id     = $ClientID
            company_id    = $CompanyID
            grant_type    = "client_credentials"
            client_secret = $ClientSecret
        }
    }

    if ($ForceNew) {
        $body['new_token'] = 'true'
    }

    try {
        $response = Invoke-RestMethod -Method Post -Uri $uri -Headers $tokenHeader -Body $body
        return $response
    } 
    catch {
        throw "Failed to obtain SuccessFactors access token from '$uri': $_"
    }
}