Contents

    Server response 401 Unauthorized

    Understanding HTTP Status Code 401 (Unauthorized)

    HTTP status code 401 (Unauthorized) indicates that the request has not been applied because valid authentication credentials for the target resource are missing. This code is prevalent in web development and can cause confusion among developers, especially when working with APIs. In this article, we will explore the practical examples of this status, its causes, and methods for addressing it across different programming languages.

    401 - Unauthorized

    Causes of HTTP Status 401

    • Absence of authentication credentials
    • Incorrect login details
    • Expired access tokens
    • Improper format of authentication headers

    Practical Examples

    1. Example 1: Accessing a Protected Resource

      Description: A user attempts to access an API that requires authentication but does not provide any credentials.

      Expected Behavior: The server returns status 401.

    2. Example 2: Invalid Credentials

      Description: A user submits a request with an incorrect username and password.

      Expected Behavior: The server returns status 401 with a message indicating failed authentication.

    3. Example 3: Using an Expired Token

      Description: A user tries to use a token that has expired.

      Expected Behavior: The server returns status 401 with a request to refresh the token.

    Handling 401 Errors in Different Programming Languages

    JavaScript (Node.js)

    Authentication can be managed using the jsonwebtoken library. Below is an example of how to check a token and return a 401 status when the token is missing or invalid.

    
    const jwt = require('jsonwebtoken');
    
    app.get('/protected', (req, res) => {
        const token = req.headers['authorization'];
        if (!token) {
            return res.status(401).send('Unauthorized');
        }
        jwt.verify(token, 'secret_key', (err, user) => {
            if (err) {
                return res.status(401).send('Unauthorized');
            }
            res.send('Access granted');
        });
    });
    

    Python (Flask)

    Using the Flask library to verify authentication credentials is straightforward. The following example shows how to return a 401 status if the user is not authenticated.

    
    from flask import Flask, request, jsonify
    
    app = Flask(__name__)
    
    @app.route('/protected')
    def protected():
        auth = request.authorization
        if not auth or not (auth.username == 'user' and auth.password == 'pass'):
            return jsonify({'message': 'Unauthorized'}), 401
        return jsonify({'message': 'Access granted'})
    

    PHP

    Authentication can be handled by checking headers in PHP. The example below checks for the presence of authentication headers and returns a 401 status if they are absent.

        
    
    if (!isset($_SERVER['PHP_AUTH_USER'])) {
        header('HTTP/1.0 401 Unauthorized');
        echo 'Unauthorized';
        exit;
    } else {
        if ($_SERVER['PHP_AUTH_USER'] !== 'user' || $_SERVER['PHP_AUTH_PW'] !== 'pass') {
            header('HTTP/1.0 401 Unauthorized');
            echo 'Unauthorized';
            exit;
        }
        echo 'Access granted';
    }
    
    

    Summary of HTTP 401 Handling

    Programming Language Library/Method Code Example
    JavaScript (Node.js) jsonwebtoken Check token in headers
    Python (Flask) Flask Use request.authorization
    PHP PHP Authentication Headers Check $_SERVER variables

    This article has discussed the meaning of HTTP status code 401 (Unauthorized), its causes, examples, and methods for handling and correcting it in various programming languages.

    Additionals Codes

    CodeDescription
    401.1Logon failed - The logon attempt failed due to incorrect username or password.
    401.2Logon failed due to server configuration - There is an issue with the authentication configuration on the server.
    401.3Unauthorized due to ACL on resource - Access is denied due to NTFS file system permissions.
    401.4Authorization failed by filter - An ISAPI filter blocked the request due to authorization issues.
    401.5Authorization failed by ISAPI/CGI application - The ISAPI or CGI application blocked the request due to authorization issues.
    401.501Access denied: concurrent request rate limit reached - Too many concurrent requests from the same client IP.
    401.502Access denied: maximum request rate limit reached - The client IP exceeded the maximum number of requests in a specified time.
    401.503Access denied: IP address denied - The client IP address is on the deny list.
    401.504Access denied: host name denied - The client host name is on the deny list.