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)
- Install necessary packages: If you’re using Visual Studio, use NuGet Package Manager. You’ll need
Microsoft.AspNetCore.Authentication.JwtBearerand potentially others depending on your project setup.dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer - 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 }; }); - 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... } - 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
- 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> - Add JavaScript to handle form submission: Use
fetchto 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'); } }); - Access Protected Resources: Include the token in the
Authorizationheader 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'); } }

