Giter Site home page Giter Site logo

fenix-hub / godot-engine.jwt Goto Github PK

View Code? Open in Web Editor NEW
50.0 4.0 10.0 81 KB

JSON Web Token library for Godot Engine written in GDScript

Home Page: https://nicolosantilio.com/godot-engine.jwt

License: MIT License

GDScript 100.00%
gdscript godotengine hmac http jwt oauth2 security

godot-engine.jwt's Introduction

Godot Engine GDScript JWT

JSON Web Token library for Godot Engine written in GDScript

Godot 3.x - Godot 4.x

Create HS256 JWT

var secret: String = JWTAlgorithmBuilder.random_secret(5)
var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.HS256(secret)
var jwt_builder: JWTBuilder = JWT.create() \
.with_expires_at(OS.get_unix_time()) \
.with_issuer("Godot") \
.with_claim("id","someid")
var jwt: String = jwt_builder.sign(jwt_algorithm)

Verify HS256 JWT

var jwt: String = "<a jwt>"
var secret: String = "<your secret token>"
var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.HS256(secret)
var jwt_verifier: JWTVerifier = JWT.require(jwt_algorithm) \
    .with_claim("my-claim","my-value") \
    .build() # Reusable Verifier
if jwt_verifier.verify(jwt) == JWTVerifier.JWTExceptions.OK :
	print("Verified!")
else:
	print(jwt_verifier.exception)

Create RS256 JWT

var private_key : CryptoKey = crypto.generate_rsa(4096)
var public_key : CryptoKey = CryptoKey.new()
public_key.load_from_string(private_key.save_to_string(true))

var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.RS256(public_key, private_key)
var jwt_builder: JWTBuilder = JWT.create() \
    .with_expires_at(OS.get_unix_time()) \
    .with_issuer("Godot") \
    .with_claim("id","someid")
var jwt: String = jwt_builder.sign(jwt_algorithm)

Verify RS256 JWT

var private_key: CryptoKey = CryptoKey.new()
var public_key: CryptoKey = CryptoKey.new()
private_key.load_from_string("<your private key PEM string>", false)
public_key.load_from_string("<your public key PEM string>", true)

var jwt: String = "<a jwt>"
var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.RS256(public_key)
var jwt_verifier: JWTVerifier = JWT.require(jwt_algorithm) \
    .with_claim("id","someid") \
    .build() # Reusable Verifier
if jwt_verifier.verify(jwt) == JWTVerifier.JWTExceptions.OK :
	print("Verified!")
else:
	print(jwt_verifier.exception)

Decode JWT

var jwt: String = "<a jwt>"
var jwt_decoder: JWTDecoder = JWT.decode(jwt)
# Get the JWT as an Array
print("%s.%s.%s" % jwt_decoder.parts)
# Decode a specific part
print(JWTUtils.base64URL_decode(jwt_decoder.get_payload()))

JWT Utils

JWTUtils.base64URL_encode(bytes: PoolByteArray) -> String
JWTUtils.base64URL_decode(string: String) -> PoolByteArray

Supported Algorithms

  • HS1 (HMAC with SHA1)
  • HS256 (HMAC with SHA256)
  • RS256 (RSA with SHA256)

godot-engine.jwt's People

Contributors

fenix-hub avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

godot-engine.jwt's Issues

Invalid set index 'parts'

I am getting the error Invalid set index 'parts' pointing to this line.

self.parts = jwt.split(".")

It appears that the parts variable was perhaps renamed to _parts but the usages were not updated?

EDIT: It looks to me like a lot of variables were renamed without their usage updated. It might be good to perform a test run on this code once before merging PRs? ๐Ÿ˜…

P.S. I made a PR that gets it working again. Hope this helps, and again, thank you for all of the excellent work going on here!

Verify JWT using JWKS key

Feature request

I'm writing an app that uses OAuth 2.0 for user login, and I'd like to verify the JWT tokens returned by the authentication server, but there doesn't seem to be a way to validate signatures using JWKS... am I missing something?

Variables shadow already-declared variables

Bug report

There are a number of function parameter names that shadow already-declared variable names, e.g.

W 0:03:38:0605   The local function parameter "leeway" is shadowing an already-declared variable at line 6.
  <GDScript Error>SHADOWED_VARIABLE
  <GDScript Source>JWTVerifierBuilder.gd:36

This isn't a bug per-se, but it can "lead to confusion, as it may be unclear which variable subsequent uses of the shadowed variable name refer to..."

PR forthcoming

Unable to verify audience with multiple audiences.

Bug report

Unable to verify the aud claim.

Describe the bug

In a JWT, the aud claim is an array.

JWT creation using JWTBaseBuilder treats the array as a PackedStringArray

func with_audience(audience: PackedStringArray) -> JWTBaseBuilder:

So does JWTVerifierBuilder:

func with_any_of_audience(audience: PackedStringArray) -> JWTVerifierBuilder:

However, the _parse_json function in JWTDecoder will treat incoming aud claims as Array. This makes verification impossible because of an error in assert_claim_values:

Invalid operands 'Array' and 'PackedStringArray' in operator '=='.

To Reproduce

# This stuff needs to be configured
var alg : JWTAlgorithm
var jwt : String

var jwt_verifier: JWTVerifier = JWT.require(alg) \
    .with_audience(["expected audience"]) \
    .build()

if jwt_verifier.verify(jwt) != JWTVerifier.JWTExceptions.OK :
    print(jwt_verifier.exception)

Expected behavior

Expectation is that the verification either succeeds or fails.

Screenshots

image

System information

  • OS: macOS

Invalid type in JWTDecoder function parse

in JWTDecoder.gd:

func _init(jwt: String):
	self.parts = jwt.split(".")
	var header: PoolByteArray = JWTUtils.base64URL_decode(self.parts[0])
	var payload: PoolByteArray = JWTUtils.base64URL_decode(self.parts[1])
	self.header_claims = _parse_json(header)
	self.payload_claims = _parse_json(payload)

func _parse_json(field) -> Dictionary:
	var parse_result: JSONParseResult = JSON.parse(field)
	if parse_result.error != OK:
		return {}
	return parse_result.result

JSON.parse(field) field should be a string according to godot docs, but here a PoolByteArray is passed instead

Unable to verify using `with_any_of_issuers`

Bug report

Describe the bug

The JWTVerifier::verify_claims_values function has the following block for verifying issuers, and does not take into account that the expected claim could be a PackedStringArray of issuers where only one must match.

JWTClaims.Public.ISSUER:
	if not jwt_decoder.get_issuer() == expected_claims.get(claim):
		self.exception = "The Claim 'iss' value doesn't match the required issuer."
		return false

To Reproduce

	var jwt_verifier: JWTVerifier = (
		JWT
		. require(<an algorithm>)
		. with_any_of_issuers(["issuer a", "issuer b"])
		. build()
	)

	if jwt_verifier.verify(<a jwt>) != JWTVerifier.JWTExceptions.OK:
		print(jwt_verifier.exception)
		return false

This will crash with Invalid operands 'String' and 'PackedStringArray' in operator '==' because the iss claim in the JWT is actually a string, but even if that gets fixed the == comparison will require all issuers specified, not any issuer specified.

Can't verify token - "The provided Algorithm doesn't match the one used to sign the JWT." [godot 4]

Hello, I followed the readme's insturctions on creating HS256 token and created these functions:

static func dict_to_jwt(data: Dictionary = {}) -> String:
	var secret: String = JWTAlgorithmBuilder.random_secret()
	var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.HS256(secret)
	var jwt_builder: JWTBuilder = JWT.create() \
	.with_expires_at(Time.get_unix_time_from_system()) \
	.with_issuer("Godot") \
	.with_payload(data)
	var jwt: String = jwt_builder.sign(jwt_algorithm)
	return jwt

static func verify_jwt(jwt: String, secret: String) -> bool:
	var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.HS256(secret)
	var jwt_verifier: JWTVerifier = JWT.require(jwt_algorithm) \
		.build() # Reusable Verifier
	var is_valid = jwt_verifier.verify(jwt) == JWTVerifier.JWTExceptions.OK
	if !is_valid:
		print(jwt_verifier.exception)
	return is_valid

But I get an error in verify_jwt saying The provided Algorithm doesn't match the one used to sign the JWT.
even though I used the same algorithem
Godot version: v4.1.3.stable.official [f06b6836a]
I used the code from the main godot 4 branch

Verify RS256 JWT signature without private key

Many tools online only require the public key to verify the JWT signature
example: https://developer.pingidentity.com/en/tools/jwt-decoder.html

In the documentation section of this addon to Verify RS256 JWT:

var private_key: CryptoKey = CryptoKey.new()
var public_key: CryptoKey = CryptoKey.new()
private_key.load_from_string("<your private key PEM string>", false)
public_key.load_from_string("<your public key PEM string>", true)

var jwt: String = "<a jwt>"
var jwt_algorithm: JWTAlgorithm = JWTAlgorithmBuilder.RS256(public_key)
var jwt_verifier: JWTVerifier = JWT.require(jwt_algorithm) \
    .with_claim("id","someid") \
    .build() # Reusable Verifier
if jwt_verifier.verify(jwt) == JWTVerifier.JWTExceptions.OK :
	print("Verified!")
else:
	print(jwt_verifier.exception)

How can I skip verifying the algorithm here JWT.require(jwt_algorithm) ? I only need to verify the signature and claims.

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.