KB0067 - Granting an app token with a username and password on the command line

KB0067 - Granting an app token with a username and password on the command line

Scope

This applies to users wishing to issue app tokens from the command line in PowerShell Universal using a username and password. 

Process

Method 1 - Form Authentication

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. 
  1.         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. 
  1. $Token = Invoke-RestMethod http://localhost:5000/api/v1/apptoken/grant -WebSession $Session
  2. $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.
  1. 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. 
  1. 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.
  1. Invoke-RestMethod 'http://localhost:5000/api/v1/apptoken/grant' -Method POST -WebSession $Session -Body (@{
        Identity = @{
            Name = "testuser"
        }
        Role = "User"
        Expiration = (Get-Date).AddDays(30)
        Description = "A test token"
    } | ConvertTo-Json) -ContentType "application/json"