A powerful tool for Python authentication and authorization

590e5e173087c7c4937d43aa1f49f834.png

Lost little book boy

Needed after reading

7

minute

Speed ​​reading only takes 3 minutes

1

   

Introduction

authlib is an open source Python library designed to provide simple and powerful authentication and authorization solutions. It supports multiple authentication and authorization protocols such as OAuth, OpenID Connect and JWT. authlib's flexible architecture and rich functionality enable developers to easily integrate authentication and authorization functionality into their applications. authlib was originally created by Hsiaoming Yang in 2018 and open sourced on GitHub. It has received extensive community support and contributions, continues to develop and improve, and has become one of the preferred authentication and authorization libraries for Python developers.

2

   

Implementation principle

The underlying implementation principles of authlib involve the specifications and processes of multiple authentication and authorization protocols. It uses Python's encryption and hashing algorithm libraries, such as cryptography and hashlib, and HTTP request libraries, such as requests. Authlib also provides easy-to-use APIs and tools, greatly simplifying developers' work.

3

   

installation steps

To install the authlib library, you can use Python's package management tool pip. Run the following command from the command line to install the latest version of authlib

pip install authlib

4

   

Instructions

authlib is suitable for various application scenarios, including web applications, mobile applications and API services. It can be used for user authentication, third-party login, API authorization and security access control. authlib provides a set of simple and powerful APIs for handling authentication and authorization related operations. See the following code example.

from flask import Flask, jsonify, url_for
from authlib.integrations.flask_client import OAuth


app = Flask(__name__)
oauth = OAuth(app)
github = oauth.register('github', {...})


@app.route('/login')
def login():
    redirect_uri = url_for('authorize', _external=True)
    return github.authorize_redirect(redirect_uri)


@app.route('/authorize')
def authorize():
    token = github.authorize_access_token()
    # you can save the token into database
    profile = github.get('/user', token=token)
    return jsonify(profile)

This code is an example of using the flask framework and authlib library to implement the GitHub login function.

First, the code imports the required modules, then creates a flask application instance app and an OAuth instance oauth, and uses the oauth.register method to register a GitHub authentication service provider. Next, two routing functions login and authorize are defined. The login function is used to process user login requests. It first uses the url_for function to generate the URL of the authorization callback and passes it as a parameter to the github.authorize_redirect method, which redirects the user to GitHub's authorization page. The authorize function is used to handle authorization callback requests. It first calls the github.authorize_access_token method to obtain the access token, and then uses the token to call the github.get method to obtain the user's GitHub profile information. Finally, use the jsonify function to convert the profile information into JSON format and return it to the client.

Let’s look at another example

from authlib.client import OAuth2Session


session = OAuth2Session(
    client_id='Your Client ID', client_secret='Your Client Secret',
    scope='user:email',
    redirect_uri='https://newexample.com/callback'
)


uri, state = session.create_authorization_url(
    'https://example.com/authorize'
)


authorization_response = 'https://newexample.com/callback?code=24..e2&state=s..w'


tokens = session.fetch_access_token(
    access_token_url='https://example.com/api/access_token',
    authorization_response=authorization_response
)


session = OAuth2Session(
    client_id='Your Client ID', client_secret='Your Client Secret',
    scope='user:email', state=state, redirect_uri='https://newexample.com/callback'
)
new_tokens = session.refresh_token(
    access_token_url, refresh_token=tokens['refresh_token']
)

This code uses the authlib library to implement the OAuth2 authorization process. OAuth2 is an open standard for authorization and authentication that allows users to authorize third-party applications to access their protected resources.

First, the code creates an OAuth2Session object and passes in the necessary parameters, such as client_id, client_secret, scope, and redirect_uri. client_id and client_secret are the credentials obtained when registering a third-party application, scope represents the scope of authorization, and redirect_uri is the URL redirected after user authorization.

Next, the code calls the create_authorization_url method to generate the authorization URL and passes in the authorization entry URL of the target URL. The generated URL will contain parameters for the authorization request, such as client_id, redirect_uri, and state. state is a randomly generated string used to prevent CSRF attacks.

Then, the code simulates the user to authorize at the authorization portal and obtains the authorization callback URL. The callback URL contains the authorization code and the previously generated state.

Next, the code calls the fetch_access_token method, passing in the access_token_url of the authorization portal of the target URL and the authorization callback URL. This method will use the authorization code to exchange the access token and return the token information.

Finally, the code uses the refresh token refresh_token to refresh the access token to maintain long-term access. Call the refresh_token method and pass in access_token_url and the previously obtained refresh token to obtain a new access token.

Please note that some parameters and URLs in the above code need to be replaced according to the actual situation, such as client_id, client_secret, scope, redirect_uri, authorization_response, access_token_url, etc. In addition, you need to understand the specific authorization process and parameter requirements based on the API documentation of the authorization portal of the target URL.

5

   

Summarize

authlib is a powerful Python library that focuses on the implementation of authentication and authorization. It provides simple yet powerful APIs and tools that enable developers to easily integrate authentication and authorization functionality into their applications. I hope this article will be helpful for you to learn and use authlib`! For more information, please refer to the official documentation and code.

6

   

References

  • https://github.com/lepture/authlib ( https://github.com/lepture/authlib )

  • https://docs.authlib.org/en/latest/ ( https://docs.authlib.org/en/latest/ )

7

   

free community

2cb3e1865629ec2fdb464eca66e625c5.jpeg

fe7f21ebb3f35427d7c15e77ce1db206.gif

Guess you like

Origin blog.csdn.net/djstavaV/article/details/133224243