Convert Figma logo to code with AI

lepture logoauthlib

The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.

4,483
447
4,483
95

Top Related Projects

A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

15,556

The most scalable and customizable OpenID Certified™ OpenID Connect and OAuth Provider on the market. Become an OpenID Connect and OAuth2 Provider over night. Broad support for related RFCs. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

4,924

Open Source, Google Zanzibar-inspired permissions database to enable fine-grained authorization for customer applications

17,484

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang: https://discord.gg/S5UjpzGZjN

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

22,126

Open Source Identity and Access Management For Modern Applications and Services

Quick Overview

Authlib is a comprehensive Python library for building OAuth and OpenID Connect servers and clients. It provides a robust set of tools for implementing various authentication and authorization protocols, making it easier for developers to integrate secure authentication systems into their applications.

Pros

  • Supports multiple OAuth and OpenID Connect specifications
  • Flexible and extensible architecture
  • Well-documented with clear examples
  • Actively maintained and regularly updated

Cons

  • Steeper learning curve for beginners
  • Some advanced features may require additional configuration
  • Limited support for non-Python environments

Code Examples

  1. Creating an OAuth 2.0 client:
from authlib.integrations.requests_client import OAuth2Session

client = OAuth2Session(
    'client_id',
    'client_secret',
    redirect_uri='https://example.com/callback'
)
authorization_url, state = client.create_authorization_url('https://example.com/oauth/authorize')
  1. Implementing an OpenID Connect provider:
from authlib.oauth2.rfc6749 import grants
from authlib.oidc.core import UserInfo
from authlib.oidc.core.grants import OpenIDCode as _OpenIDCode

class OpenIDCode(_OpenIDCode):
    def get_jwt_config(self, grant):
        return {
            'key': 'your-secret-key',
            'alg': 'HS256',
            'iss': 'https://example.com',
            'exp': 3600
        }

    def get_userinfo(self, user, scope):
        return UserInfo(sub=user.id, name=user.name, email=user.email)

server.register_grant(OpenIDCode())
  1. Verifying a JWT token:
from authlib.jose import jwt

token = 'your.jwt.token'
claims = jwt.decode(token, 'your-secret-key')
print(claims)

Getting Started

To get started with Authlib, first install it using pip:

pip install Authlib

Then, import the necessary modules and create a client or server instance:

from authlib.integrations.flask_client import OAuth

app = Flask(__name__)
oauth = OAuth(app)

github = oauth.register(
    name='github',
    client_id='your_github_client_id',
    client_secret='your_github_client_secret',
    access_token_url='https://github.com/login/oauth/access_token',
    access_token_params=None,
    authorize_url='https://github.com/login/oauth/authorize',
    authorize_params=None,
    api_base_url='https://api.github.com/',
    client_kwargs={'scope': 'user:email'},
)

This example sets up a GitHub OAuth client using Flask. You can then use this client to implement OAuth authentication in your application.

Competitor Comparisons

A generic, spec-compliant, thorough implementation of the OAuth request-signing logic

Pros of oauthlib

  • More comprehensive OAuth support, covering OAuth 1.0a and OAuth 2.0
  • Extensive documentation and examples
  • Larger community and more frequent updates

Cons of oauthlib

  • Steeper learning curve due to its extensive feature set
  • Requires additional libraries for full functionality (e.g., requests-oauthlib)
  • Can be overly complex for simple use cases

Code Comparison

oauthlib:

from oauthlib.oauth2 import WebApplicationClient

client = WebApplicationClient(client_id)
uri = client.prepare_request_uri(
    'https://example.com/oauth/authorize',
    redirect_uri='https://example.com/callback',
    scope=['profile', 'email'],
)

Authlib:

from authlib.integrations.requests_client import OAuth2Session

client = OAuth2Session(client_id, client_secret, redirect_uri='https://example.com/callback')
uri, state = client.create_authorization_url('https://example.com/oauth/authorize')

Key Differences

  • oauthlib focuses solely on OAuth protocols, while Authlib provides a broader range of authentication and authorization solutions
  • Authlib offers more integrated solutions for web frameworks like Flask and Django
  • oauthlib requires separate client libraries for different use cases, whereas Authlib provides a more unified approach

Use Case Recommendations

  • Choose oauthlib for projects requiring deep customization of OAuth flows
  • Opt for Authlib in web applications needing quick integration with popular frameworks and services
15,556

The most scalable and customizable OpenID Certified™ OpenID Connect and OAuth Provider on the market. Become an OpenID Connect and OAuth2 Provider over night. Broad support for related RFCs. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters.

Pros of Hydra

  • More comprehensive OAuth2 and OpenID Connect server implementation
  • Highly scalable and designed for cloud-native environments
  • Extensive documentation and active community support

Cons of Hydra

  • Steeper learning curve due to its complexity
  • Requires more resources to set up and maintain
  • May be overkill for simpler authentication needs

Code Comparison

Authlib (Flask integration):

from authlib.integrations.flask_oauth2 import AuthorizationServer

server = AuthorizationServer(app, generate_token)
server.init_app(app)

Hydra (Go SDK):

import "github.com/ory/hydra-client-go/client"

hydra := client.NewHTTPClientWithConfig(nil, &client.TransportConfig{
    Schemes:  []string{"http"},
    Host:     "localhost:4444",
    BasePath: "/",
})

Summary

Hydra is a more robust and feature-rich OAuth2 and OpenID Connect server, suitable for large-scale and complex applications. It offers excellent scalability and cloud-native support but comes with a steeper learning curve.

Authlib, on the other hand, provides a simpler and more lightweight authentication solution, making it easier to integrate into existing projects. It's more suitable for smaller applications or those with less complex authentication requirements.

The choice between the two depends on the specific needs of your project, considering factors such as scale, complexity, and required features.

4,924

Open Source, Google Zanzibar-inspired permissions database to enable fine-grained authorization for customer applications

Pros of SpiceDB

  • Designed for fine-grained authorization with a focus on scalability
  • Supports complex relationship-based permissions
  • Provides a gRPC API for easy integration with various languages and platforms

Cons of SpiceDB

  • Steeper learning curve due to its specialized authorization model
  • Requires more setup and infrastructure compared to simpler auth libraries
  • May be overkill for projects with basic authentication needs

Code Comparison

SpiceDB schema definition:

definition user {}

definition document {
    relation viewer: user
    relation editor: user
    permission view = viewer + editor
    permission edit = editor
}

Authlib OAuth 2.0 client setup:

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name='github',
    client_id='...',
    client_secret='...',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    api_base_url='https://api.github.com/',
    client_kwargs={'scope': 'user:email'},
)

SpiceDB focuses on complex authorization scenarios, while Authlib provides a more general-purpose authentication and authorization solution. SpiceDB is better suited for large-scale applications with intricate permission structures, whereas Authlib offers easier integration for common auth flows like OAuth.

17,484

An authorization library that supports access control models like ACL, RBAC, ABAC in Golang: https://discord.gg/S5UjpzGZjN

Pros of Casbin

  • More flexible and powerful authorization model with support for various access control models (ACL, RBAC, ABAC, etc.)
  • Supports multiple programming languages and frameworks
  • Extensive documentation and community support

Cons of Casbin

  • Steeper learning curve due to its more complex configuration and rule syntax
  • May be overkill for simpler authorization requirements
  • Requires separate storage for policies and rules

Code Comparison

Casbin example:

e := casbin.NewEnforcer("model.conf", "policy.csv")
sub := "alice"
obj := "data1"
act := "read"
if e.Enforce(sub, obj, act) == true {
    // permit alice to read data1
}

Authlib example:

from authlib.integrations.flask_oauth2 import ResourceProtector

require_oauth = ResourceProtector()

@app.route('/api/user')
@require_oauth('profile')
def user_profile():
    return jsonify(g.current_user)

Summary

Casbin offers a more comprehensive and flexible authorization solution suitable for complex scenarios across multiple languages. Authlib, while more focused on authentication, provides a simpler and more straightforward approach to authorization, particularly for Python and web applications. The choice between the two depends on the specific requirements of the project and the desired level of granularity in access control.

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

Pros of IdentityServer4

  • More comprehensive and feature-rich for enterprise-level identity and access management
  • Supports a wide range of OAuth 2.0 and OpenID Connect protocols
  • Extensive documentation and community support

Cons of IdentityServer4

  • Steeper learning curve due to its complexity
  • Requires more setup and configuration
  • Primarily focused on .NET ecosystem, which may limit its use in other environments

Code Comparison

IdentityServer4 (C#):

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddInMemoryApiResources(Config.Apis)
        .AddInMemoryClients(Config.Clients);
}

Authlib (Python):

from authlib.integrations.flask_oauth2 import AuthorizationServer

def create_authorization_server(app):
    server = AuthorizationServer(app)
    server.init_app(app)
    return server

Summary

IdentityServer4 is a robust, enterprise-grade identity server for .NET applications, offering extensive features and protocol support. It excels in complex scenarios but may be overkill for simpler projects. Authlib, on the other hand, is a more lightweight and flexible option, suitable for various programming languages and frameworks. It's easier to set up but may lack some advanced features found in IdentityServer4. The choice between the two depends on the specific requirements of your project, the development ecosystem, and the level of complexity needed in identity management.

22,126

Open Source Identity and Access Management For Modern Applications and Services

Pros of Keycloak

  • Comprehensive identity and access management solution with a wide range of features
  • Supports multiple protocols (OpenID Connect, SAML, OAuth 2.0) out of the box
  • Provides a user-friendly admin console for easy management and configuration

Cons of Keycloak

  • Can be resource-intensive and may require significant setup and maintenance
  • Steeper learning curve due to its extensive feature set
  • May be overkill for smaller projects or simple authentication needs

Code Comparison

Authlib (Python):

from authlib.integrations.flask_client import OAuth

oauth = OAuth(app)
oauth.register(
    name='github',
    client_id='your-client-id',
    client_secret='your-client-secret',
    access_token_url='https://github.com/login/oauth/access_token',
    authorize_url='https://github.com/login/oauth/authorize',
    api_base_url='https://api.github.com/',
    client_kwargs={'scope': 'user:email'},
)

Keycloak (Java):

import org.keycloak.adapters.KeycloakConfigResolver;
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;

@Configuration
public class KeycloakConfig {
    @Bean
    public KeycloakConfigResolver keycloakConfigResolver() {
        return new KeycloakSpringBootConfigResolver();
    }
}

The code examples show that Authlib focuses on simplicity and flexibility for various OAuth providers, while Keycloak provides a more structured approach with built-in configuration and integration options.

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

Authlib

Build Status Coverage Status PyPI Version Maintainability Follow Twitter

The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included.

Authlib is compatible with Python3.6+.

Migrating from authlib.jose to joserfc

Sponsors

Kraken is the world's leading customer & culture platform for energy, water & broadband. Licensing enquiries at Kraken.tech.
A blogging and podcast hosting platform with minimal design but powerful features. Host your blog and Podcast with Typlog.com.

Fund Authlib to access additional features

Features

Generic, spec-compliant implementation to build clients and providers:

Connect third party OAuth providers with Authlib built-in client integrations:

Build your own OAuth 1.0, OAuth 2.0, and OpenID Connect providers:

Useful Links

  1. Homepage: https://authlib.org/.
  2. Documentation: https://docs.authlib.org/.
  3. Purchase Commercial License: https://authlib.org/plans.
  4. Blog: https://blog.authlib.org/.
  5. Twitter: https://twitter.com/authlib.
  6. StackOverflow: https://stackoverflow.com/questions/tagged/authlib.
  7. Other Repositories: https://github.com/authlib.
  8. Subscribe Tidelift: https://tidelift.com/subscription/pkg/pypi-authlib.

Security Reporting

If you found security bugs, please do not send a public issue or patch. You can send me email at me@lepture.com. Attachment with patch is welcome. My PGP Key fingerprint is:

72F8 E895 A70C EBDF 4F2A DFE0 7E55 E3E0 118B 2B4C

Or, you can use the Tidelift security contact. Tidelift will coordinate the fix and disclosure.

License

Authlib offers two licenses:

  1. BSD (LICENSE)
  2. COMMERCIAL-LICENSE

Companies can purchase a commercial license at Authlib Plans.

If your company is creating a closed source OAuth provider, it is strongly suggested that your company purchasing a commercial license.

Support

If you need any help, you can always ask questions on StackOverflow with a tag of "Authlib". DO NOT ASK HELP IN GITHUB ISSUES.

We also provide commercial consulting and supports. You can find more information at https://authlib.org/support.