| | | 1 | | <# |
| | | 2 | | .SYNOPSIS |
| | | 3 | | Adds a GET endpoint that issues the antiforgery cookie and returns a JSON token payload. |
| | | 4 | | .DESCRIPTION |
| | | 5 | | Maps a token endpoint (default: /csrf-token) using the C# extension |
| | | 6 | | [Kestrun.Hosting.KestrunHostMapExtensions]::AddAntiforgeryTokenRoute(). |
| | | 7 | | The endpoint is exempt from CSRF validation and responds with: |
| | | 8 | | { "token": "<RequestToken>", "headerName": "<ConfiguredHeaderOrNull>" } |
| | | 9 | | .PARAMETER Server |
| | | 10 | | The Kestrun server instance (pipeline-friendly). |
| | | 11 | | .PARAMETER Path |
| | | 12 | | Route path to expose. Defaults to "/csrf-token". |
| | | 13 | | .PARAMETER PassThru |
| | | 14 | | Return the server instance for chaining. |
| | | 15 | | .EXAMPLE |
| | | 16 | | $server | Add-KrAntiforgeryMiddleware -CookieName ".Kestrun.AntiXSRF" -HeaderName "X-CSRF-TOKEN" -PassThru | |
| | | 17 | | Add-KrAntiforgeryTokenRoute -Path "/csrf-token" -PassThru |
| | | 18 | | .EXAMPLE |
| | | 19 | | # Client test (PowerShell): |
| | | 20 | | $session = New-Object Microsoft.PowerShell.Commands.WebRequestSession |
| | | 21 | | $info = Invoke-RestMethod "http://127.0.0.1:5000/csrf-token" -WebSession $session |
| | | 22 | | $hdr = $info.headerName ?? 'X-CSRF-TOKEN' |
| | | 23 | | Invoke-RestMethod "http://127.0.0.1:5000/profile" -Method Post -WebSession $session ` |
| | | 24 | | -Headers @{ $hdr = $info.token } -ContentType 'application/json' -Body (@{name='Max'}|ConvertTo-Json) |
| | | 25 | | #> |
| | | 26 | | function Add-KrAntiforgeryTokenRoute { |
| | | 27 | | [KestrunRuntimeApi('Definition')] |
| | | 28 | | [CmdletBinding()] |
| | | 29 | | [OutputType([Kestrun.Hosting.KestrunHost])] |
| | | 30 | | param( |
| | | 31 | | [Parameter(ValueFromPipeline = $true)] |
| | | 32 | | [Kestrun.Hosting.KestrunHost] $Server, |
| | | 33 | | |
| | | 34 | | [Parameter()] |
| | | 35 | | [ValidateNotNullOrEmpty()] |
| | | 36 | | [string] $Path = "/csrf-token", |
| | | 37 | | |
| | | 38 | | [Parameter()] |
| | | 39 | | [switch] $PassThru |
| | | 40 | | ) |
| | | 41 | | begin { |
| | 0 | 42 | | $Server = Resolve-KestrunServer -Server $Server |
| | 0 | 43 | | if (-not $Server) { throw "Server is not initialized. Call New-KrServer and Enable-KrConfiguration first." } |
| | | 44 | | } |
| | | 45 | | process { |
| | | 46 | | # Call the C# extension that maps the endpoint and disables antiforgery on it |
| | 0 | 47 | | $null = [Kestrun.Hosting.KestrunHostMapExtensions]::AddAntiforgeryTokenRoute($Server, $Path) |
| | | 48 | | |
| | 0 | 49 | | if ($PassThru) { return $Server } |
| | | 50 | | } |
| | | 51 | | } |