secretserverapi.psm1

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType] -bxor 3072;

# ExampleCredentialAccessScripts

# Get-Credential with 2FA
$application = "<<span class="Secret Server">Secret Server</span> URL>"

function Get-Token
{
    [CmdletBinding()]
    param(
        $credentials
        [Switch] $UseTwoFactor
    )
    $creds = @{
        username   = $credentials.UserName
        password   = $credentials.GetNetworkCredential().Password
        grant_type = "password"
    };
    $headers = $null
    If ($UseTwoFactor)
    {
        $headers = @{
            "OTP" = (Read-Host-Prompt "Enter your OTP for 2FA: ")
        }
    }
    try
    {
        $response = Invoke-RestMethod "$application/oauth2/token" -Method Post -Body $creds -Headers $headers;
        $token = $response.access_token;
        return $token;
    }
    catch
    {
        $result = $_.Exception.Response.GetResponseStream();
        $reader = New-Object System.IO.StreamReader($result);
        $reader.BaseStream.Position = 0;
        $reader.DiscardBufferedData();
        $responseBody = $reader.ReadToEnd() | ConvertFrom-Json
        Write-Host "ERROR: $($responseBody.error)"
        return;
    }
}
$token = Get-Token -credentials (Get-Credential) -UseTwoFactor



# Prompting for Credentials with 2FA
$application = "<<span class="Secret Server">Secret Server</span> URL>"

function Get-Token
{
    [CmdletBinding()]
    param( [Switch] $UseTwoFactor
    )

    $creds = @{
        username   = Read-Host -Prompt "Enter your username: "
        password   = Read-Host -Prompt "Enter your password: "
        grant_type = "password"
    };

    $headers = $null
    If ($UseTwoFactor)
    {
        $headers = @{
            "OTP" = (Read-Host-Prompt "Enter your OTP for 2FA: ")
        }
    }
    try
    {
        $response = Invoke-RestMethod "$application/oauth2/token" -Method Post -Body $creds -Headers $headers;
        $token = $response.access_token;
        return $token;
    }
    catch
    {
        $result = $_.Exception.Response.GetResponseStream();
        $reader = New-Object System.IO.StreamReader($result);
        $reader.BaseStream.Position = 0;
        $reader.DiscardBufferedData();
        $responseBody = $reader.ReadToEnd() | ConvertFrom-Json
        Write-Host "ERROR: $($responseBody.error)"
        return;
    }
}

$token = Get-Token -UseTwoFactor