Python uses HTPASSWD to implement Basic authentication authorization examples _python

Source: Internet
Author: User
Tags base64

Before I explained how to make the raspberry pie (raspberry Pi) to make no line, feeling every time through the command SSH management trouble, so I write the Web interface, mainly using Python CGI program, where the use of MINI_HTTPD this lightweight Web server , would like to install Nginx, but think or streamline some of it, after all, resources are limited, and the Web management interface is only one person to visit.

CGI application ran up, but the question is, how to achieve the common route of the kind of open the page pop-up input username password dialog box?

One of the main uses of the HTTP protocol here is the HTTP Basic authentication.

The server side implements the required authentication request by sending a header message similar to the following:

Copy Code code as follows:

http/1.0 401 Authorization Required
Www-authenticate:basic realm= "Secure area"
Content-type:text/html

In response to these requirements, I used the following Python code in CGI:
Copy Code code 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): # Here match database username password
Return True
Except
Pass

print ' status:401 unauthorized '
print ' Pragma:no-cache '
print ' content-type:text/html '
print ' Www-authenticate:basic realm=\ ' my Wireless router\ '
Print
Print "" "
<title>not authenticated</title>
<body>
</body>
Return False

# call
If not Check_login ():
Sys.exit (0)

However, the actual operation found that MINI_HTTPD does not forward from the user's authorization username and password, that is, Os.environ can not get this header information, resulting in authentication failure.

After the internet search learned mini_ HTTPD native support through. htpasswd to implement a simple authentication technology, that is to say, we can create a. htpasswd file implementation in a directory that requires access, of course, the file is formatted, and we can create it through the HTPASSWD command. This command general Apache Server Software will bring itself, but MINI_HTTPD also brought, so you can directly use this command.

Copy Code code as follows:

# Create filename Account name password
HTPASSWD-BC. htpasswd Admin 123456

When there is a. htpasswd file in a directory, the MINI_HTTPD will pop up a dialog box that asks for a username and password, and the input is correct before you can browse, if not the file is normal browsing.

Because my CGI application is based on Python, I want Python to be able to manage the. htpasswd file, but luckily there are libraries in the Python world that prevent us from repeating the wheel, and the installation of the Easy_install is as follows:

Copy Code code as follows:

sudo easy_install htpasswd

The official document gives the example below, the feeling operation is very convenient, everybody may try:
Copy Code code as follows:

Import htpasswd

With HTPASSWD. Basic ("/path/to/user.db") as UserDB:

Try
Userdb.add ("Bob", "password")
Except Htpasswd.basic.UserExists, E:
Print E
Try
Userdb.change_password ("Alice", "NewPassword")
Except Htpasswd.basic.UserNotExists, E:
Print E

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

Try
Groupdb.add_user ("Bob", "admins")
Except Htpasswd.group.UserAlreadyInAGroup, E:
Print E
Try
Groupdb.delete_user ("Alice", "managers")
Except 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.