我尝试使用此question作为模板对服务实施基本身份验证。
由于某种原因,动作过滤器永远不会应用于我的控制器,我不明白为什么。
我的控制器:
[BasicAuthenticationManager("username", "password")]
public class DataController : ApiController
{
private DataEntities db = new DataEntities();
// GET: api/Data
//[BasicAuthenticationManager]
public IHttpActionResult GetvwData()
{
return Json(db.vwData);
}
}
我的过滤器:
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();
}
}
我没有收到错误消息,并且代码自动完成会识别过滤器。
答案 0 :(得分:2)
继承自System.Web.Http.AuthorizeAttribute而不是ActionFilterAttribute。 您可以覆盖IsAuthorized方法。
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//Auth logic
//return whether user is authorized or not.
}