ASP.NET MVC中的基本认证5

前端之家收集整理的这篇文章主要介绍了ASP.NET MVC中的基本认证5前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
ASP.NET MVC 5中执行基本认证必须采取哪些步骤?

我读过OWIN不支持无Cookie认证,基本认证通常是可能的吗?

我需要一个自定义属性吗?我不知道这些属性如何工作。

解决方法

您可以使用此简单而有效的机制使用自定义ActionFilter属性
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();
    }
}

它可以用于将基本认证置于整个控制器中:

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

或具体ActionResult:

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

你也可以read here for more info

猜你在找的asp.Net相关文章