Giter Site home page Giter Site logo

nim-jwt's Introduction

JWT Implementation for Nim-lang Build Status

This is a implementation of JSON Web Tokens for Nim, it allows for the following operations to be performed:

proc toJWT*(node: JsonNode): JWT - parse a JSON object representing a JWT token to create a JWT token object.

proc toJWT*(s: string): JWT - parse a base64 string to decode it to a JWT token object

sign*(token: var JWT, secret: string) - sign a token. Creates a signature property on the given token and assigns the signature to it.

proc verify*(token: JWT, secret: string, alg: SignatureAlgorithm): bool - verify a token (typically on your incoming requests)

proc $*(token: JWT): string - creates a b64url string from the token

Example

An example to demonstrate use with a userId

import jwt, times, json, tables

var secret = "secret"

proc sign(userId: string): string =
  var token = toJWT(%*{
    "header": {
      "alg": "HS256",
      "typ": "JWT"
    },
    "claims": {
      "userId": userId,
      "exp": (getTime() + 1.days).toSeconds().int
    }
  })

  token.sign(secret)

  result = $token

proc verify(token: string): bool =
  try:
    let jwtToken = token.toJWT()
    result = jwtToken.verify(secret, HS256)
  except InvalidToken:
    result = false

proc decode(token: string): string =
  let jwt = token.toJWT()
  result = $jwt.claims["userId"].node.str

Getting google api oauth2 token:

import jwt, json, times, httpclient, cgi

const email = "[email protected]" # Acquired from google api console
const scope = "https://www.googleapis.com/auth/androidpublisher" # Define needed scope
const privateKey = """
-----BEGIN PRIVATE KEY-----
The key should be Acquired from google api console
-----END PRIVATE KEY-----
"""

var tok = initJWT(
  header = JOSEHeader(alg: RS256, typ: "JWT"),
  claims = toClaims(%*{
  "iss": email,
  "scope": scope,
  "aud": "https://www.googleapis.com/oauth2/v4/token",
  "exp": int(epochTime() + 60 * 60),
  "iat": int(epochTime())
}))

tok.sign(privateKey)

let postdata = "grant_type=" & encodeUrl("urn:ietf:params:oauth:grant-type:jwt-bearer") & "&assertion=" & $tok

proc request(url: string, body: string): string =
  var client = newHttpClient()
  client.headers = newHttpHeaders({ "Content-Length": $body.len, "Content-Type": "application/x-www-form-urlencoded" })
  result = client.postContent(url, body)
  client.close()

let resp = request("https://www.googleapis.com/oauth2/v4/token", postdata).parseJson()
echo "Access token is: ", resp["access_token"].str

Troubleshooting

This library requires a recent version of libcrypto. Specifically the one that has EVP_DigestSign* functions.

nim-jwt's People

Contributors

yglukhov avatar treeform avatar xmonader avatar alphashuro avatar disruptek avatar tormund avatar kodkuce avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.