Scope
This applies to users wishing to issue app tokens from the command line in PowerShell Universal using a username and password.
Process
You can use the PowerShell Universal form authentication endpoint to produce a cookie that can then be used to call the app token API. The below command calls the authentication API and establishes a web session in $Session variable.
Invoke-RestMethod http://localhost:5000/api/v1/signin -Method Post -Body (@{
Username = $UserName
Password = $Password
} | ConvertTo-Json) -SessionVariable Session -ContentType "application/json"
Once established, you can use the App Token API to generate a token for the user.
$Token = Invoke-RestMethod http://localhost:5000/api/v1/apptoken/grant -WebSession $Session
$Token.Token
Method 2 - Basic Authentication
Basic authentication can be used on recent versions of PowerShell Universal v4 and later. This allows you to create an app token in a single command.
Invoke-RestMethod https://localhost:443/api/v1/apptoken/grant -Authentication Basic -Credential (Get-Credential)
Note, you will need to include the -AllowUnencryptedAuthentication parameter if your server is not listening on HTTPS.
Invoke-RestMethod http://localhost/api/v1/apptoken/grant -Authentication Basic -Credential (Get-Credential) -AllowUnencryptedAuthentication
Method 3 - Grant An App Token for Another Identity
You can use either of the above authentication methods, but you will need an administrator account to accomplish this method. This method is used to grant an app token to another identity with options for the app token's properties like expiration time.
First, authenticate with forms or basic authentication. Next, you will need to invoke the grant API, but with a POST rather than a GET. If the identity does not exist, it will be created.
Identity = @{
Name = "testuser"
}
Role = "User"
Expiration = (Get-Date).AddDays(30)
Description = "A test token"
} | ConvertTo-Json) -ContentType "application/json"