This tutorial will teach you how to build a RESTful API in ASP.NET MVC (C#.NET) that secures API access using basic authentication. This is a great way for novices to gain practical knowledge and comprehend how web API authentication functions. We'll improve a basic API for student information so that only individuals with legitimate login credentials can access student information.

Tools Needed

  • Visual Studio 2019/2022
  • .NET Framework (4.7 or later)
  • Basic knowledge of C# and HTTP concepts

Step 1: Start a New Project for an ASP.NET Web API

  • Open Visual Studio.
  • Select File > New > Project.
  • Select the ASP.NET Web Application (.NET Framework) option.
  • Name it SecureStudentAPI, then click OK.
  • Click Create after choosing the Web API template.

The folder structure required for models, controllers, and configuration is scaffolded by Visual Studio.

Step 2. Define the Student Model
Create a Student.cs file beneath the Models folder.

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 = "Peter",
                DateOfBirth = new DateTime(2000, 4, 21),
                ZipCode = "600042",
                Major = "Electrical Engineering"
            },
            new Student
            {
                StudentId = "S102",
                Name = "
Peter",
                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": "Peter",
  "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.