Example of using htpasswd to implement basic authentication authorization in Python

Source: Internet
Author: User
Tags http authentication

I have explained how to create a wireless route for Raspberry Pi. I feel that every time I run the command ssh to manage it, I wrote a Web interface by myself, I mainly use CGI programs written in Python. Here I use mini_httpd, a lightweight Web server. I wanted to install nginx, but I 'd like to streamline it. After all, resources are limited, besides, the Web management interface is only accessible 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:
Copy codeThe 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:
Copy codeThe 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 """
<Html>
<Head>
<Title> Not authenticated </title>
</Head>
<Body>
<H1> Not authenticated. </Body>
</Html> """
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.
Copy codeThe 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:
Copy codeThe Code is as follows:
Sudo easy_install htpasswd
The example provided in the official document is as follows. You can try it easily:
Copy codeThe 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

Related Article

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.