Example of using htpasswd to implement basic authentication authorization in Python

Source: Internet
Author: User
This article mainly introduces the example of using htpasswd to implement basic authentication and authorization in Python. the server uses mini_httpd. if you need a friend, refer to the section above to explain how to use Raspberry Pi) creating a wireless route makes it difficult to manage via ssh every time. Therefore, you can write your own Web interface, mainly using CGI programs written in Python, I used mini_httpd, a lightweight Web server. I wanted to install nginx, but I think it should be simplified. after all, resources are limited. besides, I only access the Web management interface by myself.

The CGI application is running, but the problem arises. how can I enable normal routing to pop up the dialog box for entering the user name and password on the page?

Here we mainly use the knowledge of the HTTP protocol, that is, basic HTTP authentication.

The server sends a header message similar to the following to implement authentication requests:

The code is as follows:


HTTP/1.0 401 Authorization Required
WWW-Authenticate: Basic realm = "Secure Area"
Content-Type: text/html


In response to the above requirements, I used the following Python code in CGI:

The code is as follows:


Def check_login ():
Import base64

If "Authorization" in OS. environ:
Try:
Cred = base64.b64decode (OS. environ ['authorization']. split ('') [1])
Username, password = cred. split (":")
If db_validate_user (username, password): # match the database username and password.
Return True
Except t:
Pass

Print 'status: 401 unauthorized'
Print 'pragma: no-cache'
Print 'Content-Type: text/html'
Print 'www-Authenticate: Basic realm = \ "My Wireless Router \"'
Print
Print """


Not authenticated


Not authenticated.

"""
Return False

# Call
If not check_login ():
Sys. exit (0)


However, after the actual operation, it is found that mini_httpd does not forward the username and password from the user's Authorization, that is, OS. environ cannot obtain this header information, resulting in authentication failure.

The native support of mini_httpd is obtained after searching on the Internet. htpasswd implements simple authentication technology, that is, we can create it in the directory that requires authorized access. the implementation of the htpasswd file, of course, has the format requirements. we can use the htpasswd command to create the file. This command is generally provided by the Apache server software, but also by mini_httpd, so you can directly use this command.

The code is as follows:


# Create an account name and password for a file name
Htpasswd-bc. htpasswd admin 123456


When a directory contains A. htpasswd file, the mini_httpd dialog box asking for the user name and password is displayed. you can view the file only after entering the correct information. if the file does not exist, you can view the file normally.

Because my cgi application is based on Python, I hope Python can be managed. the htpasswd file. Fortunately, there are ready-made libraries in the Python world, avoiding repeated wheel creation. the installation method of easy_install is as follows:

The code is as follows:


Sudo easy_install htpasswd


The example provided in the official document is as follows. you can try it easily:

The code is as follows:


Import htpasswd

With htpasswd. Basic ("/path/to/user. db") as userdb:

Try:
Userdb. add ("bob", "password ")
Partition T htpasswd. basic. UserExists, e:
Print e
Try:
Userdb. change_password ("alice", "newpassword ")
Failed T htpasswd. basic. UserNotExists, e:
Print e

With htpasswd. Group ("/path/to/group. db") as groupdb:

Try:
Groupdb. add_user ("bob", "admins ")
Failed T htpasswd. group. UserAlreadyInAGroup, e:
Print e
Try:
Groupdb. delete_user ("alice", "managers ")
Failed T htpasswd. group. UserNotInAGroup, e:
Print e

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.