Python authentication username and password example

Lorraine 38 Published: 12/23/2024

Python authentication username and password example

I'd be happy to provide an example of Python authentication using username and password.

Python provides a built-in module called http.server for handling HTTP requests and responses. However, it does not provide direct support for authentication. To achieve this, you can create a custom server that handles the authentication process.

Here's an example of how you can implement basic authentication in a Python web server using the BaseHTTPRequestHandler class:

from http.server import BaseHTTPRequestHandler

import urllib.parse

class AuthenticationRequestHandler(BaseHTTPRequestHandler):

def do_GET(self):

if 'username' and 'password' not in self.headers:

self.send_response(401)

self.end_headers()

self.write_response("Authentication required. Please provide a username and password.")

else:

if self.is_authorized():

self.send_response(200)

self.end_headers()

self.write_response("Authorized!")

else:

self.send_response(403)

self.end_headers()

self.write_response("Access denied!")

def do_POST(self):

if 'username' and 'password' in self.headers:

username = urllib.parse.parse_qs(self.headers['username'])[0][0]

password = urllib.parse.parse_qs(self.headers['password'])[0][0]

if self.is_authorized(username, password):

self.send_response(201)

self.end_headers()

self.write_response("Authorized!")

else:

self.send_response(403)

self.end_headers()

self.write_response("Access denied!")

def is_authorized(self, username=None, password=None):

You can implement your own authorization logic here For demonstration purposes, I'll assume the user and password are valid if they match certain hardcoded values.

authorized_users = ['user1', 'user2']

authorized_passwords = ['password1', 'password2']

if username in authorized_users and password in authorized_passwords:

return True

else:

return False

def write_response(self, response):

self.send_response(200)

self.end_headers()

self.wfile.write(response.encode())

def run_server():

server_address = ('localhost', 8000)

httpd = http.server.HTTPServer(server_address, AuthenticationRequestHandler)

print("Starting HTTP Server on port 8000...")

httpd.serve_forever()

run_server()

In this example, we create a custom AuthenticationRequestHandler class that extends the BaseHTTPRequestHandler class. This handler handles both GET and POST requests.

For GET requests, it checks if the request headers contain 'username' and 'password'. If they do not, it returns a 401 response with an error message indicating that authentication is required. If the credentials are provided, but they are invalid or missing, it returns a 403 response with an error message stating access was denied.

For POST requests, it checks if the request body contains 'username' and 'password'. If they do, it calls the is_authorized method to check if the user is authorized. If the user is authorized, it returns a 201 response with a success message; otherwise, it returns a 403 response with an error message stating access was denied.

The is_authorized method contains placeholder logic that simply checks if the provided username and password match hardcoded values. In a real-world scenario, you would implement your own authorization logic here.

To run this server, we call the run_server function at the end of our script, which starts an HTTP server on port 8000 using the custom handler class.

This is just one example of how you can implement authentication in Python. You can customize it to fit your specific needs and requirements.

How to pass username and password in Python script

Passing username and password in a Python script is crucial when interacting with external services that require authentication. There are several ways to do this, but I'll focus on the most common approaches.

1. Hardcoding

The simplest way is to hardcode your username and password directly into your Python script:

import requests

username = 'your_username'

password = 'your_password'

response = requests.post('https://example.com/api/endpoint', auth=(username, password))

print(response.text)

However, this approach has severe security implications. You should never store sensitive information like passwords in plain text.

2. Environment Variables

A better approach is to store your username and password as environment variables:

import os

username = os.environ['YOUR_USERNAME']

password = os.environ['YOUR_PASSWORD']

response = requests.post('https://example.com/api/endpoint', auth=(username, password))

print(response.text)

This way, you can keep your sensitive information out of your code and store it in a secure location. Just remember to set the environment variables before running your script.

3. Configuration Files

You can also store your username and password in a configuration file, such as a JSON or YAML file:

import json

with open('config.json', 'r') as f:

config = json.load(f)

username = config['username']

password = config['password']

response = requests.post('https://example.com/api/endpoint', auth=(username, password))

print(response.text)

This approach allows you to separate your configuration from your code and store sensitive information securely.

4. Command-Line Arguments

Another way is to pass your username and password as command-line arguments:

import sys

if len(sys.argv) != 3:

print("Usage: python script.py ")

sys.exit(1)

username = sys.argv[1]

password = sys.argv[2]

response = requests.post('https://example.com/api/endpoint', auth=(username, password))

print(response.text)

This approach allows you to securely pass your username and password from the command line.

5. Secure Storage

Finally, you can use a secure storage solution like a secrets manager or an encrypted configuration file:

import os

secrets = os.environ['SECRETS']

username = json.loads(secrets)['username']

password = json.loads(secrets)['password']

response = requests.post('https://example.com/api/endpoint', auth=(username, password))

print(response.text)

This approach allows you to store your sensitive information securely and access it from within your Python script.

Remember, when working with sensitive information like passwords, security should always be your top priority. Always use secure storage solutions and never hardcode your credentials in plain text.