Convert Figma logo to code with AI

jpadilla logopyjwt

JSON Web Token implementation in Python

5,433
708
5,433
33

Top Related Projects

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

10,733

Java JWT: JSON Web Token for Java and Android

9,663

PHP package for JWT

2,174

Jwt.Net, a JWT (JSON Web Token) implementation for .NET

10,803

ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:

11,409

🔐 JSON Web Token Authentication for Laravel & Lumen

Quick Overview

PyJWT is a Python library that allows you to encode and decode JSON Web Tokens (JWTs). It provides a simple and secure way to create, sign, and verify JWTs, which are commonly used for authentication and information exchange in web applications and APIs.

Pros

  • Easy to use with a straightforward API
  • Supports various algorithms for signing and verifying tokens
  • Actively maintained with regular updates and bug fixes
  • Comprehensive documentation and examples

Cons

  • Limited to JWT functionality, not a complete authentication solution
  • Requires careful implementation to avoid security vulnerabilities
  • Some advanced features may require additional dependencies
  • Performance may be a concern for high-volume applications

Code Examples

  1. Creating and encoding a JWT:
import jwt

payload = {"user_id": 123, "username": "johndoe"}
secret = "your-secret-key"
token = jwt.encode(payload, secret, algorithm="HS256")
print(token)
  1. Decoding and verifying a JWT:
import jwt

token = "your.jwt.token"
secret = "your-secret-key"

try:
    decoded = jwt.decode(token, secret, algorithms=["HS256"])
    print(decoded)
except jwt.ExpiredSignatureError:
    print("Token has expired")
except jwt.InvalidTokenError:
    print("Invalid token")
  1. Creating a token with expiration:
import jwt
from datetime import datetime, timedelta

payload = {
    "user_id": 123,
    "exp": datetime.utcnow() + timedelta(hours=1)
}
secret = "your-secret-key"
token = jwt.encode(payload, secret, algorithm="HS256")
print(token)

Getting Started

To get started with PyJWT, follow these steps:

  1. Install the library:

    pip install pyjwt
    
  2. Import the library in your Python script:

    import jwt
    
  3. Create a simple JWT:

    payload = {"user_id": 123, "username": "johndoe"}
    secret = "your-secret-key"
    token = jwt.encode(payload, secret, algorithm="HS256")
    print(token)
    
  4. Decode and verify the JWT:

    decoded = jwt.decode(token, secret, algorithms=["HS256"])
    print(decoded)
    

Competitor Comparisons

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Pros of node-jsonwebtoken

  • Larger community and more frequent updates
  • Built-in support for async/await and Promises
  • More comprehensive documentation with examples

Cons of node-jsonwebtoken

  • Limited to JavaScript/Node.js environments
  • Slightly more complex API compared to PyJWT

Code Comparison

PyJWT:

import jwt

encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

node-jsonwebtoken:

const jwt = require('jsonwebtoken');

const token = jwt.sign({ some: 'payload' }, 'secret', { algorithm: 'HS256' });
const decoded = jwt.verify(token, 'secret', { algorithms: ['HS256'] });

Both libraries provide similar core functionality for encoding and decoding JWTs. PyJWT offers a simpler API with fewer options, while node-jsonwebtoken provides more flexibility and features.

PyJWT is ideal for Python projects, offering easy integration with Python web frameworks. node-jsonwebtoken is better suited for JavaScript/Node.js applications, particularly those using Express.js or other Node-based web frameworks.

Choose PyJWT for Python projects prioritizing simplicity, or node-jsonwebtoken for JavaScript projects requiring more advanced features and async support.

10,733

Java JWT: JSON Web Token for Java and Android

Pros of jjwt

  • Written in Java, offering native integration with Java/JVM ecosystems
  • Extensive support for various JWT algorithms and claims
  • Comprehensive documentation and examples

Cons of jjwt

  • Limited to Java/JVM environments
  • Larger library size compared to PyJWT
  • Steeper learning curve for non-Java developers

Code Comparison

PyJWT (Python):

import jwt

encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

jjwt (Java):

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

String jwt = Jwts.builder()
    .setPayload("{\"some\":\"payload\"}")
    .signWith(SignatureAlgorithm.HS256, "secret")
    .compact();
Claims claims = Jwts.parser().setSigningKey("secret").parseClaimsJws(jwt).getBody();

Summary

PyJWT is a lightweight Python library for JWT handling, while jjwt is a more comprehensive Java-based solution. PyJWT offers simplicity and ease of use for Python developers, whereas jjwt provides robust features and integration for Java applications. The choice between the two depends on the programming language and specific project requirements.

9,663

PHP package for JWT

Pros of php-jwt

  • Lightweight and simple implementation, focusing solely on JWT functionality
  • Easy to integrate into PHP projects without additional dependencies
  • Supports both symmetric and asymmetric algorithms for JWT signing

Cons of php-jwt

  • Limited features compared to PyJWT, which offers more comprehensive JWT handling
  • Less active community and fewer contributors, potentially slower bug fixes and updates
  • Lacks built-in token validation and verification features found in PyJWT

Code Comparison

PyJWT (Python):

import jwt

encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

php-jwt (PHP):

use \Firebase\JWT\JWT;

$encoded = JWT::encode(["some" => "payload"], "secret", "HS256");
$decoded = JWT::decode($encoded, "secret", ["HS256"]);

Both libraries offer similar basic functionality for encoding and decoding JWTs. PyJWT provides more advanced features and a wider range of supported algorithms, while php-jwt focuses on core JWT operations in a PHP environment. The choice between them depends on the specific project requirements and the programming language used in the development stack.

2,174

Jwt.Net, a JWT (JSON Web Token) implementation for .NET

Pros of jwt

  • Native .NET implementation, optimized for C# and .NET ecosystem
  • Supports both JWT and JWE (JSON Web Encryption)
  • Extensive documentation and examples for .NET developers

Cons of jwt

  • Limited to .NET environment, less versatile across platforms
  • Smaller community and fewer contributors compared to PyJWT
  • Less frequent updates and releases

Code Comparison

PyJWT (Python):

import jwt

encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

jwt (C#):

using JWT.Algorithms;
using JWT.Builder;

var token = JwtBuilder.Create()
      .WithAlgorithm(new HMACSHA256Algorithm())
      .WithSecret("secret")
      .AddClaim("some", "payload")
      .Encode();

var json = JwtBuilder.Create()
      .WithAlgorithm(new HMACSHA256Algorithm())
      .WithSecret("secret")
      .MustVerifySignature()
      .Decode(token);

Both libraries provide similar functionality for encoding and decoding JWTs, but PyJWT offers a more concise syntax. The jwt library for .NET provides a fluent interface with more explicit configuration options, which can be beneficial for complex use cases in .NET applications.

10,803

ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:

Pros of jwt-go

  • Written in Go, offering better performance and concurrency support
  • More comprehensive support for various JWT signing algorithms
  • Active development and maintenance, with frequent updates

Cons of jwt-go

  • Limited to Go language, whereas PyJWT is Python-based and more versatile for Python projects
  • Steeper learning curve for developers not familiar with Go

Code Comparison

PyJWT (Python):

import jwt

encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

jwt-go (Go):

import "github.com/dgrijalva/jwt-go"

token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
    "some": "payload",
})
tokenString, _ := token.SignedString([]byte("secret"))

Additional Notes

Both libraries provide robust JWT implementation for their respective languages. PyJWT is more suitable for Python developers and integrates well with Python web frameworks, while jwt-go offers better performance and is ideal for Go-based applications. The choice between the two largely depends on the programming language and ecosystem of the project.

11,409

🔐 JSON Web Token Authentication for Laravel & Lumen

Pros of jwt-auth

  • Specifically designed for Laravel, offering seamless integration with the framework
  • Provides built-in authentication guards and middleware for easy implementation
  • Offers extensive configuration options tailored for Laravel applications

Cons of jwt-auth

  • Limited to Laravel ecosystem, not suitable for other PHP frameworks or languages
  • May have a steeper learning curve for developers not familiar with Laravel
  • Less frequently updated compared to PyJWT

Code Comparison

PyJWT (Python):

import jwt
encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
decoded = jwt.decode(encoded, "secret", algorithms=["HS256"])

jwt-auth (PHP/Laravel):

$token = JWTAuth::attempt($credentials);
$user = JWTAuth::parseToken()->authenticate();

Summary

PyJWT is a versatile JWT library for Python, while jwt-auth is a Laravel-specific package for JWT authentication. PyJWT offers broader language support and more frequent updates, making it suitable for various projects. jwt-auth, on the other hand, provides deep integration with Laravel, including pre-built authentication features, but is limited to the Laravel ecosystem. The choice between the two depends on the specific project requirements and the development framework being used.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PyJWT

.. image:: https://github.com/jpadilla/pyjwt/workflows/CI/badge.svg :target: https://github.com/jpadilla/pyjwt/actions?query=workflow%3ACI

.. image:: https://img.shields.io/pypi/v/pyjwt.svg :target: https://pypi.python.org/pypi/pyjwt

.. image:: https://codecov.io/gh/jpadilla/pyjwt/branch/master/graph/badge.svg :target: https://codecov.io/gh/jpadilla/pyjwt

.. image:: https://readthedocs.org/projects/pyjwt/badge/?version=stable :target: https://pyjwt.readthedocs.io/en/stable/

A Python implementation of RFC 7519 <https://tools.ietf.org/html/rfc7519>. Original implementation was written by @progrium <https://github.com/progrium>.

Sponsor

.. |auth0-logo| image:: https://github.com/user-attachments/assets/ee98379e-ee76-4bcb-943a-e25c4ea6d174 :width: 160px

+--------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ | |auth0-logo| | If you want to quickly add secure token-based authentication to Python projects, feel free to check Auth0's Python SDK and free plan at auth0.com/signup <https://auth0.com/signup?utm_source=external_sites&utm_medium=pyjwt&utm_campaign=devn_signup>_. | +--------------+-----------------------------------------------------------------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+

Installing

Install with pip:

.. code-block:: console

$ pip install PyJWT

Usage

.. code-block:: pycon

>>> import jwt
>>> encoded = jwt.encode({"some": "payload"}, "secret", algorithm="HS256")
>>> print(encoded)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg
>>> jwt.decode(encoded, "secret", algorithms=["HS256"])
{'some': 'payload'}

Documentation

View the full docs online at https://pyjwt.readthedocs.io/en/stable/

Tests

You can run tests from the project root after cloning with:

.. code-block:: console

$ tox