public class BasicAuthenticationAttribute : ActionFilterAttribute
{
public string Rol { get; set; }
public BasicAuthenticationAttribute(string rol)
{
Rol = rol;//gönderilen user bilgisinin rolünü kontrol etmek için kullanılacak
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string username;
string password;
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(':');
username = cred[0];
password = cred[1];
}
bool authenticated = false;
bool authorized = false;
if(string.IsNullOrEmpty(username) == false && string.IsNullOrEmpty(password) == false)
{ //kullanıcı yetki kontrolü yap
authenticated = true;//gönderilen username ve password geçerli mi kontrolü burada yapılabilir
//yetki kontrolü
authorized = true;//
}
if (authenticated && authorized) return;//eğer kullanıcı geçerliyse ve yetkisi varsa çık
if (authenticated == false)
{
var res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AddHeader("WWW-Authenticate", "Basic realm=\"RTM\"");
res.Write("Kullanıcı adı ve şifre geçersiz");
res.End();
return;
}
if (authorized == false)
{
var res = filterContext.HttpContext.Response;
res.StatusCode = 403;
res.Write("Yetki yok");
res.End();
return;
}
}
}