-
Notifications
You must be signed in to change notification settings - Fork 0
/
getjwt.ps1
61 lines (50 loc) · 2.1 KB
/
getjwt.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using namespace System
using namespace System.Net
using namespace System.Security.Cryptography.X509Certificates
#requires -Module PSJsonWebToken
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
[string]$body = @{status = "Access denied" } | ConvertTo-Json;
[HttpStatusCode]$statusCode = [HttpStatusCode]::OK;
# Environment variables below. First three should be in Azure Key Vault!
$base64Cert = $env:JWT_PFX;
$validationKey = $env:JWT_SECRET;
$tokenClaims = $env:JWT_CLAIMS;
$jwtTtl = $env:JWT_TTL;
$nbfSkew = $env:JWT_NBF_SKEW;
# Write to the Azure Functions log stream:
Write-Host "GetJwt function processed a request.";
# Attempt to get X-API-KEY:
$key = $Request.Headers["X-API-KEY"];
if (-not $key) {
$key = $Request.Body['X-API-KEY'];
}
# If proper key is passed, attempt to craft JWT:
if ($key -eq $validationKey) {
# Convert base 64 string to byte array and ultimately to X509Certfifcate2 object:
[byte[]]$certificateBytes = [Convert]::FromBase64String($base64Cert);
$certificate = [X509Certificate2]::new($certificateBytes, $null);
# Pull claims from environment variable, and convert to hash table to pass to New-JsonWebToken:
$claims = $tokenClaims | ConvertFrom-Json -AsHashTable;
# Generate JWT:
[string]$jwt = "";
try {
$jwt = New-JsonWebToken -Claims $claims -HashAlgorithm SHA256 -NotBeforeSkew $nbfSkew -AddJtiClaim -SigningCertificate $certificate -TimeToLive $jwtTtl -ErrorAction Stop;
$body = $jwt;
}
catch {
$statusCode = [HttpStatusCode]::Forbidden;
}
}
$responseHeaders = @{'Content-Type' = 'application/json; charset=utf-8';
'Strict-Transport-Security' = 'max-age=31536000; includeSubDomains';
'Content-Security-Policy' = "default-src 'self'";
'X-Content-Type-Options' = 'nosniff';
'X-Frame-Options' = "SAMEORIGIN";
'Referrer-Policy' = 'no-referrer-when-downgrade'
}
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = $statusCode;
Body = $body;
Headers = $responseHeaders;
})