2016-04-21 12 views
1

Ich versuche, die Basisauthentifizierung für einen Dienst zu implementieren, der question als Vorlage verwendet.MVC 5 Angepasster ActionFilter funktioniert nicht

Aus irgendeinem Grund wird der Aktionsfilter nie auf meine Controller angewendet und ich habe keine Ahnung warum.

Mein Controller:

[BasicAuthenticationManager("username", "password")] 
public class DataController : ApiController 
{ 
    private DataEntities db = new DataEntities(); 

    // GET: api/Data 

    //[BasicAuthenticationManager] 
    public IHttpActionResult GetvwData() 
    { 
     return Json(db.vwData); 
    } 
} 

Mein 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(); 
    } 
} 

ich keinen Fehler messaage und der Filter wird durch Code Auto-Vervollständigung recogniced.

Antwort

1

Vererben von System.Web.Http.AuthorizeAttribute anstelle von ActionFilterAttribute. Sie können die IsAuthorized-Methode überschreiben.

protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) 
{ 
    //Auth logic 
    //return whether user is authorized or not. 
} 
Verwandte Themen