Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic authentication in ASP.NET MVC 5

What steps must be done to implement basic authentication in ASP.NET MVC 5?

I have read that OWIN does not support cookieless authentication, so is basic authentication generally possible?

Do I need a custom attribute here? I am not sure about how these attributes work.

like image 948
Sonic Avatar asked Nov 22 '13 11:11

Sonic


People also ask

What is authentication in ASP.NET MVC?

ASP.NET MVC Authentication is a feature in MVC that helps in making the website highly secure and safe. Authentication is the process of confirming or validating the user's identity if the user who is trying to access the web page or web application is a genuine user or not.

What is the default authentication in MVC?

The default authentication is, Individual User Accounts.


1 Answers

You can use this simple yet effective mechanism using a custom ActionFilter attribute:

public class BasicAuthenticationAttribute : ActionFilterAttribute {     public string BasicRealm { get; set; }     protected string Username { get; set; }     protected string Password { get; set; }      public BasicAuthenticationAttribute(string username, string password)     {         this.Username = username;         this.Password = password;     }      public override void OnActionExecuting(ActionExecutingContext filterContext)     {         var req = filterContext.HttpContext.Request;         var auth = req.Headers["Authorization"];         if (!String.IsNullOrEmpty(auth))         {             var cred = System.Text.ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');             var user = new { Name = cred[0], Pass = cred[1] };             if (user.Name == Username && user.Pass == Password) return;         }         filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Ryadel"));         /// thanks to eismanpat for this line: http://www.ryadel.com/en/http-basic-authentication-asp-net-mvc-using-custom-actionfilter/#comment-2507605761         filterContext.Result = new HttpUnauthorizedResult();     } } 

It can be used to put under Basic Authentication a whole controller:

[BasicAuthenticationAttribute("your-username", "your-password",      BasicRealm = "your-realm")] public class HomeController : BaseController {    ... } 

or a specific ActionResult:

public class HomeController : BaseController {     [BasicAuthenticationAttribute("your-username", "your-password",          BasicRealm = "your-realm")]     public ActionResult Index()      {         ...     } } 

In case you need additional info check out this blog post that I wrote on the topic.

like image 73
Darkseal Avatar answered Oct 19 '22 20:10

Darkseal