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";
}
}
}
Explanation
- The filter checks the Authorization header.
- It decodes the Base64-encoded string.
- Validates the username and password using a helper method.
- Returns 401 Unauthorized if the credentials are invalid.
Step 4. Create the Student API Controller
This controller is protected using the custom authentication filter.
File: Controllers/StudentController.cs.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using SecureStudentAPI.Models;
using SecureStudentAPI.Filters;
namespace SecureStudentAPI.Controllers
{
[BasicAuthentication]
public class StudentController : ApiController
{
private static List<Student> students = new List<Student>
{
new Student
{
StudentId = "S101",
Name = "Srinivas P",
DateOfBirth = new DateTime(2000, 4, 21),
ZipCode = "600042",
Major = "Electrical Engineering"
},
new Student
{
StudentId = "S102",
Name = "Lavanya Devi",
DateOfBirth = new DateTime(2001, 10, 5),
ZipCode = "620001",
Major = "Civil Engineering"
}
};
public IHttpActionResult Get(string id)
{
var student = students.FirstOrDefault(
s => s.StudentId.Equals(id, StringComparison.OrdinalIgnoreCase));
if (student == null)
return NotFound();
return Ok(student);
}
}
}
Explanation
- The [BasicAuthentication] attribute protects the controller.
- Only users with correct credentials (admin/pass123) can access the data.
Step 5. Configure Routing
Open App_Start/WebApiConfig.cs and ensure that this routing setup is in place.
using System.Web.Http;
namespace SecureStudentAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable attribute routing
config.MapHttpAttributeRoutes();
// Define default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
Step 6. Test with Postman or a Browser
Using Postman
- Set request to GET.
- URL: http://localhost:[PORT]/api/student/S102
- Click the Authorization tab.
- Type: Basic Auth
- Username: admin | Password: pass123
- Click Send.
Response
{
"StudentId": "S102",
"Name": "Lavanya Devi",
"DateOfBirth": "2001-10-05T00:00:00",
"ZipCode": "620001",
"Major": "Civil Engineering"
}
If you don’t send credentials, you will get a 401 Unauthorized response.
Summary
You’ve now learned.
- How to create a Web API.
- How to implement basic username/password authentication.
- How to secure your endpoints with custom filters.
This lays the foundation for advanced authentication using JWT, OAuth, and other similar technologies.
Next Steps for Practice
- Store credentials in a config file.
- Implement token-based authentication.
- Add logging for unauthorized access attempts.
Hands-On Task Ideas
- Add a login endpoint and generate tokens.
- Create roles (Admin and Student) and restrict access to specific routes.
- Connect with a real database to validate users.
Basic authentication is useful for learning and prototyping. For production systems, always use HTTPS and consider OAuth 2.0 or JWT for robust security.
Happy coding!
Please share your thoughts and doubts, so we can provide a better article that makes your learning more interesting.