Decode an OAuth Token with F#

October 9, 2024    Development .Net FunctionalProgramming FSharp

Decode an OAuth Token with F#

I usually go to Jwt.io to decode OAuth tokens, but it’s not private. I’m sure they don’t, but what if they are recording the entries?

So I decided to look into how to run it locally with F#.

Thanks to the Bing Chat AI , I quickly got the code and ran it.

In VS Code, with the Ionide extension you can quickly run FSharp code in a .fsx file.

Here’s the code from Bing Chat. I only had to change from the dotnet add package suggestion to using the inline #r "nuget: System.IdentityModel.Tokens.Jwt"


#r "nuget: System.IdentityModel.Tokens.Jwt"
open System.IdentityModel.Tokens.Jwt

let decodeJwtToken (token: string) =
    let handler = JwtSecurityTokenHandler()
    let jsonToken = handler.ReadToken(token) :?> JwtSecurityToken
    jsonToken.Claims
    |> Seq.map (fun claim -> claim.Type, claim.Value)
    |> Seq.toList

// Example usage
let token = "your_token_here"
let claims = decodeJwtToken token
claims |> List.iter (fun (typ, value) -> printfn "%s: %s" typ value)

Bing referenced https://fsharpforfunandprofit.com/posts/capability-based-security-3/ , https://github.com/Gab-km/OAuth-in-FSharp and https://blog.bitscry.com/2018/03/05/retrieving-oauth2-tokens-in-net/

I saw this just after writing the above and am impressed. You can decode the JWT in the Visual Studio Previewer!

VS Previewer