Skip to content

Instantly share code, notes, and snippets.

@lboulard
Created May 22, 2024 12:47
Show Gist options
  • Save lboulard/6362e97558c625c6be09b7d87919cb8f to your computer and use it in GitHub Desktop.
Save lboulard/6362e97558c625c6be09b7d87919cb8f to your computer and use it in GitHub Desktop.
Get GitHub API from Windows Credential Store
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
using System.Text;
public class CredentialManager {
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool CredRead(string target, int type, int reservedFlag, out IntPtr credentialPtr);
[DllImport("advapi32", SetLastError = true)]
public static extern void CredFree(IntPtr cred);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct CREDENTIAL {
public int Flags;
public int Type;
public IntPtr TargetName;
public IntPtr Comment;
public long LastWritten;
public int CredentialBlobSize;
public IntPtr CredentialBlob;
public int Persist;
public int AttributeCount;
public IntPtr Attributes;
public IntPtr TargetAlias;
public IntPtr UserName;
}
public static string GetCredential(string targetName) {
IntPtr credPtr;
if (CredRead(targetName, 1, 0, out credPtr)) {
var credential = (CREDENTIAL)Marshal.PtrToStructure(credPtr, typeof(CREDENTIAL));
string password = Marshal.PtrToStringUni(credential.CredentialBlob, credential.CredentialBlobSize / 2);
CredFree(credPtr);
return password;
} else {
throw new Exception("Failed to retrieve credential from Windows Credential Manager.");
}
}
}
"@
function Get-GitHubToken {
param (
[string]$targetName = "git:https://github.com"
)
try {
$token = [CredentialManager]::GetCredential($targetName)
return $token
} catch {
Write-Error $_.Exception.Message
return $null
}
}
# Get the GitHub API token
$githubToken = Get-GitHubToken
# Check if the token was retrieved successfully
if ($githubToken) {
# Make a GitHub API request
$headers = @{
Authorization = "token $githubToken"
}
$url = "https://api.github.com/user"
# Perform the API request
$response = Invoke-RestMethod -Uri $url -Headers $headers -Method Get
# Output the response
$response
} else {
Write-Error "Failed to retrieve GitHub API token."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment