/web-to-ai-ml-integrations

Add User Authentication to ML Web App

Add secure user authentication to your ML web app with our easy step-by-step guide. Enhance security and boost user trust!

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

Add User Authentication to ML Web App

Add User Registration Route

 
  • This step creates a route where new users can sign up by providing their email and password.
  • The password is securely hashed using a library (like bcrypt) so that raw passwords are never stored.
  • The endpoint then stores the user in a database (for prototyping, a simple in-memory store can be used).

import datetime
from flask import Flask, request, jsonify
import bcrypt         // For password hashing
import jwt            // For token-based authentication

app = Flask(**name**)
app.config['SECRET\_KEY'] = 'your-secret-key'  // Secret key used for JWT encoding

// Using a simple dictionary to simulate a user database
users\_db = {}     

// Endpoint where users register
@app.route('/register', methods=['POST'])
def register():
    data = request.get\_json()         // Extract JSON data from the request
    email = data.get('email')
    password = data.get('password')
    
    if email in users\_db:
        return jsonify({'message': 'User already exists!'}), 400
    
    // Hash the password with bcrypt
    hashed\_pass = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
    
    // Store the user with hashed password
    users\_db[email] = {
        'email': email,
        'password': hashed\_pass
    }
    
    return jsonify({'message': 'Registration successful!'}), 201

if **name** == '**main**':
    app.run(debug=True)

 

Add User Login Endpoint with JWT Generation

 
  • This endpoint authenticates user credentials by comparing the provided password with the stored hash.
  • If authentication is successful, a JSON Web Token (JWT) is generated.
  • JWTs are tokens that securely store user data in encrypted format and are used for stateless session management.

@app.route('/login', methods=['POST'])
def login():
    data = request.get\_json()         // Extract login data from request
    email = data.get('email')
    password = data.get('password')
    
    user = users\_db.get(email)
    if not user:
        return jsonify({'message': 'Invalid email or password!'}), 401
    
    // Check provided password against the stored hashed password
    if not bcrypt.checkpw(password.encode('utf-8'), user['password']):
        return jsonify({'message': 'Invalid email or password!'}), 401
    
    // Generate a token that expires in 30 minutes
    token = jwt.encode(
        {'email': email, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=30)},
        app.config['SECRET\_KEY'], algorithm='HS256'
    )
    
    return jsonify({'token': token}), 200

 

Create a Middleware to Protect ML API Endpoint

 
  • This middleware verifies the JWT token in incoming requests for routes that should be protected.
  • If the token is valid, the request is allowed; otherwise, a 401 error is returned.
  • Protecting ML endpoint is critical to ensure that only authenticated users can access ML predictions.

from functools import wraps

// Function to check token validity
def token\_required(f):
    @wraps(f)
    def decorated(_args, _\*kwargs):
        token = None
        // Check if 'Authorization' header is present
        if 'Authorization' in request.headers:
            // Typical header: "Bearer "
            token = request.headers['Authorization'].split()[1]
        
        if not token:
            return jsonify({'message': 'Token is missing!'}), 401
        
        try:
            // Decode token with the app's secret key
            data = jwt.decode(token, app.config['SECRET\_KEY'], algorithms=['HS256'])
            current_user = users_db.get(data['email'])
            if current\_user is None:
                return jsonify({'message': 'User not found!'}), 401
        except Exception as e:
            return jsonify({'message': 'Token is invalid!', 'error': str(e)}), 401
        
        return f(current\_user, _args, _\*kwargs)
    return decorated

 

Integrate Authentication with ML Prediction Endpoint

 
  • Create an endpoint where users can request predictions from your ML model.
  • This endpoint is decorated with the authentication middleware so it is accessible only to authenticated users.
  • ML Model Endpoint processes data inputs and returns model predictions.

// Dummy ML prediction function for demonstration
def ml_predict(input_data):
    // In a real application, call your machine learning model here
    return {'prediction': 'predicted\_value'}

// Secure ML prediction endpoint with token verification
@app.route('/predict', methods=['POST'])
@token\_required
def predict(current\_user):
    data = request.get\_json()         // Get input data for prediction
    result = ml\_predict(data)
    return jsonify(result), 200

 

Integrating the Authentication Flow with the ML Web App

 
  • When a user logs in, the JWT is returned to the client application.
  • The client must include this token in the Authorization header (format: "Bearer token") in subsequent API calls.
  • This ensures that all ML model interactions are performed in an authenticated context.
  • Client-side implementation should manage token storage securely (e.g., using HttpOnly cookies or secure storage).

// Example: Client-side use of token in a fetch call
/\*
fetch('/predict', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token  // token obtained from login
    },
    body: JSON.stringify({input: 'your_data_here'})
})
.then(response => response.json())
.then(data => {
    // Process ML prediction result
    console.log(data);
});
\*/

 

Conclusion and Security Considerations

 
  • Ensure that your secret key is sensitive and stored securely, for example using environment variables.
  • Implement HTTPS to secure data transmission, especially for authentication tokens and user credentials.
  • Beyond basic JWT validation, consider adding token revocation strategies and refresh tokens if needed for longer sessions.
  • This implementation provides a backbone to secure not only traditional web routes but also specialized ML endpoints.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â