Year End Sale: Get Upto 40% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
Securing ASP.NET Web API using basic Authentication

Securing ASP.NET Web API using basic Authentication

05 Dec 2024
Advanced
155K Views
4 min read
Learn with an interactive course and practical hands-on labs

ASP.NET MVC with Web API Foundations Course - Free

In the previous article, I have explained Custom Authentication and Authorization in ASP.NET MVC. Now, I am going to show you how to implement basic HTTP authentication for your Web API by extending ASP.NET WEB API's AuthotrizeAttribute. Before implementing basic HTTP authentication, let's understand what is it?

Basic HTTP Authentication

In basic HTTP authentication, the client passes their username and password in the HTTP request header. Typically, using this technique we encrypt user credentials string into base64 encoded string and decrypt this base64 encoded string into plain text. You can also use another encryption and decryption technique.

Custom Principal

Since WebAPI is build on the top of ASP.NET Framework, hence it can use ASP.NET Framework features like ASP.NET membership and provider. ASP.NET provides IPrincipal and IIdentity interfaces to represents the identity and role for a user. For ASP.NET Web API, you can also create a custom solution by evaluating the IPrincipal and IIdentity interfaces which are bound to the HttpContext as well as the current thread.

public class CustomPrincipal : IPrincipal
 {
 public IIdentity Identity { get; private set; }
 public bool IsInRole(string role)
 {
 if (roles.Any(r => role.Contains(r)))
 {
 return true;
 }
 else
 {
 return false;
 }
 }

 public CustomPrincipal(string Username)
 {
 this.Identity = new GenericIdentity(Username);
 }

 public int UserId { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string[] roles { get; set; }
 } 

Now you can put this CustomPrincipal objects into the thread’s currentPrinciple property and into the HttpContext’s User property to accomplish your custom authentication and authorization process.

Custom ASP.NET Web API Authorization Filter

Like ASP.NET MVC, Web API also provides Authorization filter to authorize a user. This filter can be applied to an action, a controller, or even globally. This filter is based on AuthorizeAttribute class exist in System.Web.Http namespace. You can customize this filter by overriding OnAuthorization() method as shown below:

//custom authorize filter attribute
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
 private const string BasicAuthResponseHeader = "WWW-Authenticate";
 private const string BasicAuthResponseHeaderValue = "Basic";
 readonly DataContext Context = new DataContext();

 public string UsersConfigKey { get; set; }
 public string RolesConfigKey { get; set; }

 protected CustomPrincipal CurrentUser
 {
 get { return Thread.CurrentPrincipal as CustomPrincipal; }
 set { Thread.CurrentPrincipal = value as CustomPrincipal; }
 }

 public override void OnAuthorization(HttpActionContext actionContext)
 {
 try
 {
 AuthenticationHeaderValue authValue = actionContext.Request.Headers.Authorization;

 if (authValue != null && !String.IsNullOrWhiteSpace(authValue.Parameter) && authValue.Scheme == BasicAuthResponseHeaderValue)
 {
 Credentials parsedCredentials = ParseAuthorizationHeader(authValue.Parameter);

 if (parsedCredentials != null)
 {
 var user = Context.Users.Where(u => u.Username == parsedCredentials.Username && u.Password == parsedCredentials.Password).FirstOrDefault();
 if (user != null)
 {
 var roles = user.Roles.Select(m => m.RoleName).ToArray();
 var authorizedUsers = ConfigurationManager.AppSettings[UsersConfigKey];
 var authorizedRoles = ConfigurationManager.AppSettings[RolesConfigKey];

 Users = String.IsNullOrEmpty(Users) ? authorizedUsers : Users;
 Roles = String.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

 CurrentUser = new CustomPrincipal(parsedCredentials.Username, roles);

 if (!String.IsNullOrEmpty(Roles))
 {
 if (!CurrentUser.IsInRole(Roles))
 {
 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
 return;
 }
 }

 if (!String.IsNullOrEmpty(Users))
 {
 if (!Users.Contains(CurrentUser.UserId.ToString()))
 {
 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Forbidden);
 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
 return;
 }
 }

 }
 }
 }
 }
 catch (Exception)
 {
 actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
 actionContext.Response.Headers.Add(BasicAuthResponseHeader, BasicAuthResponseHeaderValue);
 return;

 }
 }

 private Credentials ParseAuthorizationHeader(string authHeader)
 {
 string[] credentials = Encoding.ASCII.GetString(Convert.FromBase64String(authHeader)).Split(new[] { ':' });

 if (credentials.Length != 2 || string.IsNullOrEmpty(credentials[0]) || string.IsNullOrEmpty(credentials[1]))
 return null;

 return new Credentials() { Username = credentials[0], Password = credentials[1], };
 }
}
//Client credential
public class Credentials
{
 public string Username { get; set; }
 public string Password { get; set; }
}

Applying CustomAuthorize attribute

To make secure your service, decorate your Web API controllers with CustomAuthorize attribute as defined above and specify the uses or roles to access specific service actions/methods. The below product service action Getproduct can be access only by Admin users.

public class ProductController : ApiController
{
 [CustomAuthorize(Roles="Admin")]
 public HttpResponseMessage Getproducts()
 {
 var products = new Product[]
 {
 new Product()
 {
 Id = 1,
 Name = "Soap",
 Price =25.12
 },
 new Product()
 {
 Id = 2,
 Name = "Shampoo",
 Price =25.12
 }
 };

 var response = Request.CreateResponse>(HttpStatusCode.OK, products);
 return response;
 }
}

Calling Web API and passing client credential from ASP.NET MVC

public class HomeController : Controller
{
 //
 // GET: /Home/
 public ActionResult Index()
 {
 string FullName = User.FirstName + " " + User.LastName; 
 
 HttpClient client = new HttpClient();
 
 string authInfo = "admin" + ":" + "123456";
 authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
 client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authInfo);

 client.BaseAddress = new Uri("http://localhost:63173/");

 HttpResponseMessage response = client.GetAsync("api/product/").Result;
 if (response.IsSuccessStatusCode)
 {
 // Parse the response body. Blocking!
 var data = response.Content.ReadAsAsync>().Result;
 return View();
 }
 return View();
 }
}
Read More: Rest API Interview Questions and Answers
What do you think?

I hope you will enjoy the tips while implementing role-based or user-based security in your ASP.NET Web API. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Share Article
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at ScholarHat)

Shailendra Chauhan, Founder and CEO of ScholarHat by DotNetTricks, is a renowned expert in System Design, Software Architecture, Azure Cloud, .NET, Angular, React, Node.js, Microservices, DevOps, and Cross-Platform Mobile App Development. His skill set extends into emerging fields like Data Science, Python, Azure AI/ML, and Generative AI, making him a well-rounded expert who bridges traditional development frameworks with cutting-edge advancements. Recognized as a Microsoft Most Valuable Professional (MVP) for an impressive 9 consecutive years (2016–2024), he has consistently demonstrated excellence in delivering impactful solutions and inspiring learners.

Shailendra’s unique, hands-on training programs and bestselling books have empowered thousands of professionals to excel in their careers and crack tough interviews. A visionary leader, he continues to revolutionize technology education with his innovative approach.
Accept cookies & close this