ASP.NET MVC 5 中的基本身份验证 [英] Basic authentication in ASP.NET MVC 5

查看:17
本文介绍了ASP.NET MVC 5 中的基本身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

必须执行哪些步骤才能在 ASP.NET MVC 5 中实现基本身份验证?

What steps must be done to implement basic authentication in ASP.NET MVC 5?

我已经读到 OWIN 不支持无 cookie 身份验证,所以基本身份验证通常是可能的吗?

I have read that OWIN does not support cookieless authentication, so is basic authentication generally possible?

这里需要自定义属性吗?我不确定这些属性是如何工作的.

Do I need a custom attribute here? I am not sure about how these attributes work.

推荐答案

您可以使用自定义 ActionFilter 属性来使用这种简单而有效的机制:

You can use this simple yet effective mechanism using a custom ActionFilter attribute:

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

它可用于将整个控制器置于基本身份验证之下:

It can be used to put under Basic Authentication a whole controller:

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

或特定的 ActionResult:

or a specific ActionResult:

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

如果您需要更多信息,请查看这篇博文是我写的关于这个主题的.

In case you need additional info check out this blog post that I wrote on the topic.

这篇关于ASP.NET MVC 5 中的基本身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆