Reputation: 499
I'm trying to implement basic authentication to a service using this question as a template.
For some reason the action filter is never applied to my controllers and I have no idea why.
My controller:
[BasicAuthenticationManager("username", "password")]
public class DataController : ApiController
{
private DataEntities db = new DataEntities();
// GET: api/Data
//[BasicAuthenticationManager]
public IHttpActionResult GetvwData()
{
return Json(db.vwData);
}
}
My filter:
public class BasicAuthenticationManager : ActionFilterAttribute
{
protected string userName { get; set; }
protected string password { get; set; }
public BasicAuthenticationManager(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 credentials = ASCIIEncoding.ASCII.GetString(Convert.FromBase64String(auth.Substring(6))).Split(':');
var user = new { Name = credentials[0], Pass = credentials[1] };
if (user.Name == userName && user.Pass == password) return;
}
filterContext.Result = new HttpUnauthorizedResult();
}
}
I don't get an error messaage and the filter is recogniced by code autocompletion.
Upvotes: 1
Views: 1569
Reputation: 1320
Inherit from System.Web.Http.AuthorizeAttribute instead of ActionFilterAttribute. You can override the IsAuthorized method.
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Auth logic
//return whether user is authorized or not.
}
Upvotes: 2