Andre Rubnikowich
Andre Rubnikowich

Reputation: 475

Generate token in Azure RunBook

How to create a token with PowerShell from a secret key in Azure runbook to call Invoke-RestMethod ....

This code is how I go about it in c#

  public string Create(string secret, TimeSpan expiration)
        {
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var tokenHandler = new JwtSecurityTokenHandler();
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Expires = DateTime.UtcNow + expiration,
                Subject = new ClaimsIdentity(new[]
                {
                    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
                }),
                SigningCredentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256Signature)
            };

            var securityToken = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(securityToken);
        }

Upvotes: 0

Views: 320

Answers (1)

Jahnavi
Jahnavi

Reputation: 8018

How to create a token with PowerShell from a secret key in Azure runbook to call
Invoke-RestMethod:

Use below PowerShell Script in an automation account runbook to achieve your requirement.

$resurl = "https://management.azure.com/"
$clientID = "CLIENT_ID"
$clientSecret = "CLIENT_SECRET"
$tenant = "TENANT_ID"
$body = @{
    grant_type    = "client_credentials"
    client_id     = $clientID
    client_secret = $clientSecret
    resource      = $resurl
}
$token = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$tenant/oauth2/token" -Method POST -Body $body
write-output $token
$headers = @{
    "Authorization" = "Bearer $($token.access_token)"
}
Invoke-RestMethod -Uri "https://login.microsoftonline.com/" -Method GET -Headers $headers

Generated token successfully:

enter image description here

Upvotes: 1

Related Questions