authlib
The ultimate Python library in building OAuth, OpenID Connect clients and servers. JWS,JWE,JWK,JWA,JWT included.
Top Related Projects
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic
The only web-scale, fully customizable OpenID Certified™ OpenID Connect and OAuth2 Provider in the world. Become an OpenID Connect and OAuth2 Provider over night. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters. Relied upon by OpenAI and others for web-scale security.
Open Source Identity and Access Management For Modern Applications and Services
OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js
Simple, unobtrusive authentication for Node.js.
Spring Security
Quick Overview
Authlib is a comprehensive Python library for building OAuth and OpenID Connect servers and clients. It provides a set of tools to implement various authentication and authorization protocols, supporting both OAuth 1.0 and OAuth 2.0, as well as OpenID Connect.
Pros
- Versatile and feature-rich, supporting multiple OAuth versions and OpenID Connect
- Well-documented with clear examples and explanations
- Actively maintained and regularly updated
- Flexible and extensible, allowing for custom implementations
Cons
- Steeper learning curve compared to simpler OAuth libraries
- May be overkill for basic authentication needs
- Some users report occasional issues with specific edge cases
- Documentation, while comprehensive, can be overwhelming for beginners
Code Examples
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')
Implementing an OAuth 2.0 server:
from authlib.oauth2 import AuthorizationServer
from authlib.oauth2.rfc6749 import grants
server = AuthorizationServer(
client_model,
token_model,
token_generator
)
server.register_grant(grants.AuthorizationCodeGrant)
server.register_grant(grants.RefreshTokenGrant)
Using OpenID Connect:
from authlib.integrations.flask_client import OAuth
oauth = OAuth()
oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_kwargs={'scope': 'openid email profile'}
)
@app.route('/login')
def login():
return oauth.google.authorize_redirect(redirect_uri='https://example.com/callback')
Getting Started
To get started with Authlib, first install it using pip:
pip install Authlib
For a basic OAuth 2.0 client setup:
from authlib.integrations.requests_client import OAuth2Session
client = OAuth2Session('client_id', 'client_secret')
resp = client.get('https://api.example.com/user')
print(resp.json())
For more detailed instructions and advanced usage, refer to the official Authlib documentation at https://docs.authlib.org/.
Competitor Comparisons
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic
Pros of oauthlib
- More mature and widely adopted project with a larger community
- Extensive documentation and examples available
- Supports a broader range of OAuth 1.0 and 2.0 features
Cons of oauthlib
- Steeper learning curve for beginners
- Requires additional libraries for full functionality (e.g., requests-oauthlib)
- Less frequent updates and maintenance compared to Authlib
Code Comparison
oauthlib:
from oauthlib.oauth2 import WebApplicationClient
client = WebApplicationClient(client_id)
uri = client.prepare_request_uri(authorization_base_url, redirect_uri=redirect_uri, scope=['profile', 'email'])
Authlib:
from authlib.integrations.requests_client import OAuth2Session
client = OAuth2Session(client_id, client_secret, redirect_uri=redirect_uri)
uri, state = client.create_authorization_url(authorization_base_url, scope='profile email')
Both libraries provide similar functionality for OAuth 2.0 client implementation, but Authlib offers a more streamlined API with built-in integration for popular web frameworks. oauthlib requires additional setup and configuration, while Authlib provides a more user-friendly experience out of the box.
Authlib also includes support for more advanced features like JWT and JWK, making it a more comprehensive solution for authentication and authorization needs. However, oauthlib's longer history and larger community can be advantageous for developers seeking extensive resources and third-party integrations.
The only web-scale, fully customizable OpenID Certified™ OpenID Connect and OAuth2 Provider in the world. Become an OpenID Connect and OAuth2 Provider over night. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters. Relied upon by OpenAI and others for web-scale security.
Pros of Hydra
- More comprehensive OAuth2 and OpenID Connect server implementation
- Designed for high-availability and horizontal scalability
- Extensive documentation and enterprise support options
Cons of Hydra
- Steeper learning curve due to its complexity
- Requires more infrastructure setup and maintenance
- May be overkill for smaller projects or simpler authentication needs
Code Comparison
Hydra (Go):
import "github.com/ory/hydra/client"
c := client.NewHTTPClientWithConfig(nil, &client.TransportConfig{
Schemes: []string{"http", "https"},
Host: "localhost:4444",
BasePath: "/",
})
Authlib (Python):
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',
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'},
)
Hydra is a more robust, scalable solution for OAuth2 and OpenID Connect, while Authlib provides a simpler, more lightweight approach for Python-based applications. Hydra is better suited for large-scale, enterprise deployments, whereas Authlib is more appropriate for smaller projects or those primarily using Python.
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 simpler authentication needs
Code Comparison
Keycloak (Java):
KeycloakBuilder.builder()
.serverUrl("https://keycloak-server/auth")
.realm("myrealm")
.clientId("myclient")
.clientSecret("client-secret")
.build();
Authlib (Python):
from authlib.integrations.flask_client import OAuth
oauth = OAuth(app)
oauth.register(
name='myauth',
client_id='client_id',
client_secret='client_secret',
access_token_url='https://example.com/oauth/token',
authorize_url='https://example.com/oauth/authorize'
)
Summary
Keycloak is a robust, full-featured IAM solution suitable for large-scale applications and complex authentication scenarios. It offers extensive functionality but may be more complex to set up and maintain. Authlib, on the other hand, is a lightweight library focused on implementing OAuth and OpenID Connect protocols, making it more suitable for smaller projects or when integrating authentication into existing applications. The choice between the two depends on the specific requirements and scale of the project.
OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js
Pros of node-oidc-provider
- Specialized for OpenID Connect, offering comprehensive OIDC implementation
- Highly customizable with extensive configuration options
- Active development and frequent updates
Cons of node-oidc-provider
- Limited to Node.js environment
- Steeper learning curve due to its extensive feature set
- Focused solely on OIDC, lacking broader authentication protocols support
Code Comparison
node-oidc-provider:
const Provider = require('oidc-provider');
const configuration = {
clients: [{ client_id: 'foo', client_secret: 'bar', redirect_uris: ['http://localhost:8080/cb'] }],
};
const oidc = new Provider('http://localhost:3000', configuration);
Authlib:
from authlib.integrations.flask_oauth2 import AuthorizationServer
from authlib.oauth2.rfc6749 import grants
server = AuthorizationServer(app, db.session, token_generator)
server.register_grant(grants.AuthorizationCodeGrant)
Key Differences
- node-oidc-provider is Node.js-specific, while Authlib supports multiple languages and frameworks
- Authlib provides a broader range of authentication protocols beyond OIDC
- node-oidc-provider offers more granular OIDC-specific configurations
- Authlib's API is generally simpler, making it easier for beginners to implement basic authentication flows
Both libraries are well-maintained and offer robust solutions for implementing authentication and authorization, with node-oidc-provider excelling in OIDC-specific implementations and Authlib providing a more versatile toolkit for various authentication needs.
Simple, unobtrusive authentication for Node.js.
Pros of Passport
- Extensive ecosystem with numerous strategies for various authentication methods
- Well-established and widely adopted in the Node.js community
- Flexible middleware architecture for easy integration with Express.js
Cons of Passport
- Primarily focused on Node.js, limiting its use in other environments
- Can be complex to set up and configure for newcomers
- Requires additional modules for certain authentication flows
Code Comparison
Passport (Express.js setup):
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
Authlib (Flask setup):
from authlib.integrations.flask_client import OAuth
oauth = OAuth(app)
Key Differences
- Authlib is a more comprehensive solution, supporting multiple frameworks and protocols
- Passport is Node.js-specific, while Authlib supports Python, JavaScript, and other languages
- Authlib provides built-in support for more complex OAuth flows, whereas Passport often requires additional modules
Use Cases
- Choose Passport for Node.js projects, especially those using Express.js
- Opt for Authlib when working with Python frameworks or requiring multi-language support
- Consider Authlib for projects needing advanced OAuth and OpenID Connect features out-of-the-box
Community and Support
- Passport has a larger community and more third-party strategies
- Authlib offers comprehensive documentation and supports a wider range of technologies
Both libraries are actively maintained and provide robust authentication solutions, with the choice depending on specific project requirements and technology stack.
Spring Security
Pros of Spring Security
- Comprehensive security framework with extensive features for authentication, authorization, and protection against common vulnerabilities
- Seamless integration with Spring ecosystem and widely adopted in enterprise Java applications
- Robust documentation, community support, and regular updates
Cons of Spring Security
- Steeper learning curve due to its complexity and extensive configuration options
- Can be overkill for smaller projects or applications with simpler security requirements
- Primarily focused on Java ecosystem, limiting its use in other programming languages
Code Comparison
Spring Security configuration example:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and().formLogin();
}
}
Authlib usage example:
from authlib.integrations.flask_client import OAuth
oauth = OAuth(app)
oauth.register(
name='google',
client_id='YOUR_CLIENT_ID',
client_secret='YOUR_CLIENT_SECRET',
access_token_url='https://accounts.google.com/o/oauth2/token',
access_token_params=None,
authorize_url='https://accounts.google.com/o/oauth2/auth',
authorize_params=None,
api_base_url='https://www.googleapis.com/oauth2/v1/',
client_kwargs={'scope': 'openid email profile'},
)
Spring Security offers a more comprehensive and integrated approach for Java applications, while Authlib provides a lightweight and flexible solution for Python-based projects, especially for OAuth and OpenID Connect implementations.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
The ultimate Python library in building OAuth and OpenID Connect servers. JWS, JWK, JWA, JWT are included.
Authlib is compatible with Python3.9+.
Migrations
Authlib will deprecate authlib.jose
module, please read:
Sponsors
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/overview. | |
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:
- The OAuth 1.0 Protocol
- The OAuth 2.0 Authorization Framework
- RFC6749: The OAuth 2.0 Authorization Framework
- RFC6750: The OAuth 2.0 Authorization Framework: Bearer Token Usage
- RFC7009: OAuth 2.0 Token Revocation
- RFC7523: JWT Profile for OAuth 2.0 Client Authentication and Authorization Grants
- RFC7591: OAuth 2.0 Dynamic Client Registration Protocol
- RFC7592: OAuth 2.0 Dynamic Client Registration Management Protocol
- RFC7636: Proof Key for Code Exchange by OAuth Public Clients
- RFC7662: OAuth 2.0 Token Introspection
- RFC8414: OAuth 2.0 Authorization Server Metadata
- RFC8628: OAuth 2.0 Device Authorization Grant
- RFC9068: JSON Web Token (JWT) Profile for OAuth 2.0 Access Tokens
- RFC9101: The OAuth 2.0 Authorization Framework: JWT-Secured Authorization Request (JAR)
- RFC9207: OAuth 2.0 Authorization Server Issuer Identification
- Javascript Object Signing and Encryption
- RFC7515: JSON Web Signature
- RFC7516: JSON Web Encryption
- RFC7517: JSON Web Key
- RFC7518: JSON Web Algorithms
- RFC7519: JSON Web Token
- RFC7638: JSON Web Key (JWK) Thumbprint
- RFC7797: JSON Web Signature (JWS) Unencoded Payload Option
- RFC8037: ECDH in JWS and JWE
- draft-madden-jose-ecdh-1pu-04: Public Key Authenticated Encryption for JOSE: ECDH-1PU
- OpenID Connect 1.0
- OpenID Connect Core 1.0
- OpenID Connect Discovery 1.0
- OpenID Connect Dynamic Client Registration 1.0
Connect third party OAuth providers with Authlib built-in client integrations:
Build your own OAuth 1.0, OAuth 2.0, and OpenID Connect providers:
- Flask
- Django
Useful Links
- Homepage: https://authlib.org/.
- Documentation: https://docs.authlib.org/.
- Purchase Commercial License: https://authlib.org/plans.
- Blog: https://blog.authlib.org/.
- Twitter: https://twitter.com/authlib.
- StackOverflow: https://stackoverflow.com/questions/tagged/authlib.
- Other Repositories: https://github.com/authlib.
- 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:
- BSD LICENSE
- COMMERCIAL-LICENSE
Any project, open or closed source, can use the BSD license. If your company needs commercial support, you can purchase a commercial license at Authlib Plans. You can find more information at https://authlib.org/support.
Top Related Projects
A generic, spec-compliant, thorough implementation of the OAuth request-signing logic
The only web-scale, fully customizable OpenID Certified™ OpenID Connect and OAuth2 Provider in the world. Become an OpenID Connect and OAuth2 Provider over night. Written in Go, cloud native, headless, API-first. Available as a service on Ory Network and for self-hosters. Relied upon by OpenAI and others for web-scale security.
Open Source Identity and Access Management For Modern Applications and Services
OpenID Certified™ OAuth 2.0 Authorization Server implementation for Node.js
Simple, unobtrusive authentication for Node.js.
Spring Security
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot