Introduction
In this tutorial, you’ll learn how to create a RESTful API in ASP.NET MVC (C#.NET) that uses simple Basic Authentication to secure API access. This is an ideal example for beginners to understand how authentication works in web APIs and to build hands-on experience.
We’ll enhance a simple student info API so that only users with valid credentials can access student details.
Tools Required
- Visual Studio 2019/2022
- .NET Framework (4.7 or later)
- Basic knowledge of C# and HTTP concepts
Step 1. Create a New ASP.NET Web API Project
- Open Visual Studio.
- Click File > New > Project.
- Choose ASP.NET Web Application (.NET Framework).
- Name it SecureStudentAPI, then click OK.
- Select the Web API template and click Create.
Visual Studio scaffolds the necessary folder structure for models, controllers, and configuration.
Step 2. Define the Student Model
Create a Student.cs file under the Models folder.
using System;
namespace SecureStudentAPI.Models
{
public class Student
{
public string StudentId { get; set; }
public string Name { get; set; }
public DateTime DateOfBirth { get; set; }
public string ZipCode { get; set; }
public string Major { get; set; }
}
}
This is the same as our previous student API.
Step 3. Create a Basic Authentication Filter
We will write a custom AuthorizationFilterAttribute class to handle Basic Auth.
File: Filters/BasicAuthenticationAttribute.cs.
using System;
using System.Net;
using System.Net.Http;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace SecureStudentAPI.Filters
{
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
var authHeader = actionContext.Request.Headers.Authorization;
if (authHeader != null && authHeader.Scheme == "Basic")
{
var credentials = Encoding.UTF8
.GetString(Convert.FromBase64String(authHeader.Parameter))
.Split(':');
var username = credentials[0];
var password = credentials[1];
if (IsAuthorizedUser(username, password))
{
Thread.CurrentPrincipal = new GenericPrincipal(
new GenericIdentity(username), null);
return;
}
}
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
actionContext.Response.Headers.Add("WWW-Authenticate", "Basic realm=\"StudentAPI\"");
}
private bool IsAuthorizedUser(string username, string password)
{
// For demo: simple hardcoded username/password
return username == "admin" && password == "pass123";
}
}
}

Join the conversation! Your thoughts help the community grow.