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

Step 1. Create a New ASP.NET Web API Project

  1. Open Visual Studio.
  2. Click File > New > Project.
  3. Choose ASP.NET Web Application (.NET Framework).
  4. Name it SecureStudentAPI, then click OK.
  5. 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

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

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

  1. Set request to GET.
  2. URL: http://localhost:[PORT]/api/student/S102
  3. Click the Authorization tab.
  4. Type: Basic Auth
  5. Username: admin | Password: pass123
  6. 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.

This lays the foundation for advanced authentication using JWT, OAuth, and other similar technologies.

Next Steps for Practice

Hands-On Task Ideas

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.