Get a Pentest and security assessment of your IT network.

Cyber Security

WebAPI Authentication: HTML/JS Client

TL;DR

This guide shows you how to add basic username/password authentication to a WebAPI and create a simple HTML/JavaScript client to connect securely.

Setting up the WebAPI (C# .NET Example)

  1. Install necessary packages: If you’re using Visual Studio, use NuGet Package Manager. You’ll need Microsoft.AspNetCore.Authentication.JwtBearer and potentially others depending on your project setup.
    dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
  2. Configure Authentication in Program.cs: Add authentication services and JWT bearer options.
    builder.Services.AddAuthentication("DefaultScheme")
        .AddJwtBearer(options => {
            options.RequireHttpsMetadata = false; // For testing only!
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = your_secret_key,
                ValidateAudience = false,
                ValidateLifetime = true
            };
        });
  3. Create a Controller: Add the [Authorize] attribute to your controller or specific actions.
    [ApiController]
    [Route("[controller]")]
    [Authorize]
    public class MyController : ControllerBase {
        // Your API endpoints here...
    }
  4. Implement Login Endpoint: Create an endpoint to handle user login and generate a JWT token.
    [HttpPost("login"])
    public IActionResult Login([FromBody] UserLoginModel model) {
        // Validate credentials (against database, etc.)
        if (IsValidCredentials(model.Username, model.Password)) {
            var token = GenerateJwtToken(model.Username);
            return Ok(new { Token = token });
        } else {
            return Unauthorized();
        }
    }
    

Creating the HTML/JavaScript Client

  1. Create an HTML form: A simple form to collect username and password.
    <form id="loginForm">
      Username: <input type="text" id="username" name="username"><br>
      Password: <input type="password" id="password" name="password" type="password"><br>
      <button type="submit">Login</button>
    </form>
  2. Add JavaScript to handle form submission: Use fetch to send the credentials to the login endpoint.
    document.getElementById("loginForm").addEventListener("submit", async (event) => {
      event.preventDefault();
      const username = document.getElementById("username").value;
      const password = document.getElementById("password").value;
    
      const response = await fetch('/api/MyController/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });
    
      if (response.ok) {
        const data = await response.json();
        localStorage.setItem('token', data.Token); // Store token in local storage
        // Redirect to protected page or update UI
        console.log("Login successful!");
      } else {
        alert('Invalid credentials');
      }
    });
  3. Access Protected Resources: Include the token in the Authorization header when making requests to protected API endpoints.
    async function fetchData() {
      const token = localStorage.getItem('token');
      const response = await fetch('/api/MyController/someProtectedEndpoint', {
        headers: {
          'Authorization': 'Bearer ' + token // Add the token to the header
        }
      });
    
      if (response.ok) {
        const data = await response.json();
        console.log(data);
      } else {
        alert('Unauthorized');
      }
    }
Related posts
Cyber Security

Zip Codes & PII: Are They Personal Data?

Cyber Security

Zero-Day Vulnerabilities: User Defence Guide

Cyber Security

Zero Knowledge Voting with Trusted Server

Cyber Security

ZeroNet: 51% Attack Risks & Mitigation