Skip to content

Instantly share code, notes, and snippets.

@LasseSkogland
Created April 20, 2021 17:38
Show Gist options
  • Save LasseSkogland/0e26e88b5f8818820680002a4bdc4c2a to your computer and use it in GitHub Desktop.
Save LasseSkogland/0e26e88b5f8818820680002a4bdc4c2a to your computer and use it in GitHub Desktop.
Sparebank 1 - Personal API (Powershell)
# Go here for more information: https://developersparebank1.no/personlig-klient
$ClientID = ''
$ClientSecret = ''
$FinInst = ''
$RedirectUrl = 'http://localhost:8089/callback'
function New-StateCode {
return [System.Random]::new().Next();
}
# New Token
function Start-ListenCallback {
# enter this URL to reach PowerShell’s web server
$url = 'http://localhost:8089/'
# start web server
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
try
{
while ($listener.IsListening) {
# process received request
$context = $listener.GetContext()
$Request = $context.Request
$Response = $context.Response
$received = $Request.url.Query
if($received -match "code=(.*?)(?:&|$)") {
$Response.statuscode = 200
$buffer = [Text.Encoding]::UTF8.GetBytes("Ok")
$Response.ContentLength64 = $buffer.length
$Response.OutputStream.Write($buffer, 0, $buffer.length)
$Response.Close()
return $Matches[1]
}
else {
$Response.statuscode = 400
$buffer = [Text.Encoding]::UTF8.GetBytes("Error")
$Response.ContentLength64 = $buffer.length
$Response.OutputStream.Write($buffer, 0, $buffer.length)
$Response.Close()
}
}
}
finally
{
$listener.Close();
}
}
$authUrl = "https://api.sparebank1.no/oauth/authorize?finInst=$FinInst&client_id=$ClientID&state=$(New-StateCode)&redirect_uri=$([System.Web.HttpUtility]::UrlEncode($RedirectUrl))&response_type=code";
Start-Process $authUrl
$code = Start-ListenCallback
$req = Invoke-RestMethod -Method Post -Uri 'https://api.sparebank1.no/oauth/token' -ContentType 'application/x-www-form-urlencoded' -Body @{
client_id = $ClientID
client_secret = $ClientSecret
code = $code
grant_type = 'authorization_code'
state = New-StateCode
redirect_uri = $RedirectUrl
}
# Refresh Token
$RefreshToken = ''
$req = Invoke-RestMethod -Method Post -Uri 'https://api.sparebank1.no/oauth/token' -ContentType 'application/x-www-form-urlencoded' -Body @{
client_id = $ClientID
client_secret = $ClientSecret
grant_type = 'refresh_token'
refresh_token = $RefreshToken
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment