Skip to content

Add an authentication on the API #3

@seilorjunior

Description

@seilorjunior

Today we don't have any kind of authentication or validation for the API, so this can be a security issue.

We can start having a simple validation to secure that.

As example

// Get the Authorization header
if (!Request.Headers.ContainsKey("Authorization"))
{
_logger.LogError("Missing Authorization header");
return Unauthorized("Missing Authorization header");
}

    string authorizationHeader = Request.Headers["Authorization"];
    if (!authorizationHeader.StartsWith("Basic "))
    {
        _logger.LogError("Invalid Authorization header");
        return Unauthorized("Invalid Authorization header");
    }

    string base64Credentials = authorizationHeader.Substring("Basic ".Length).Trim();
    byte[] decodedBytes;
    try
    {
        decodedBytes = Convert.FromBase64String(base64Credentials);
    }
    catch (FormatException)
    {
        _logger.LogError("Invalid Base64 string");
        return BadRequest("Invalid Base64 string");
    }

    string decodedString = Encoding.UTF8.GetString(decodedBytes);

    // Extract user and password from the decoded string
    var parts = decodedString.Split(':');
    if (parts.Length != 2)
    {
        _logger.LogError("Invalid user and password format");
        return BadRequest("Invalid user and password format");
    }

    string user = parts[0];
    string password = parts[1];

    // Validate user and password (replace with your actual validation logic)
    if (user != "expectedUser" || password != "expectedPassword")
    {
        _logger.LogError("Invalid user or password");
        return Unauthorized("Invalid user or password");
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions