密码保护整个网站的基本身份验证

时间:2016-05-04 18:33:33

标签: c# asp.net-mvc authentication

对于beta测试,我想使用基本身份验证(或摘要),但我无法将MVC中默认提供的Cookie身份验证与基本身份验证相结合。

关注Dead simple ASP.NET MVC 5 password protection?(以及link1link2等较旧的帖子),我在FilterConfig.cs中设置了一个操作过滤器:

GlobalFilters.Filters.Add(new BasicAuthenticationAttribute("myUsername", "myPassword"));

然而,结果是一个无限的登录循环:

http://localhost:52200/account/login?ReturnUrl=%2Faccount%2Flogin%3FReturnUrl%3D%252Faccount%252Flogin%253FReturnUrl%253D%25252Faccount%25252Flogin%25253FReturnUrl%25253D%2525252Faccount%2525252Flogin%2525253FReturnUrl%2525253D%252525252Faccount%252525252Flogin%252525253FReturnUrl%252525253D%25252525252Faccount%25252525252Flogin%25252525253FReturnUrl%25252525253D%2525252525252Faccount%2525252525252Flogin%2525252525253FReturnUrl%2525252525253D%252525252525252Faccount%252525252525252Flogin%252525252525253FReturnUrl%252525252525253D%25252525252525252Faccount%25252525252525252Flogin%25252525252525253FReturnUrl%25252525252525253D%2525252525252525252F

项目已Anonymous Authentication 已启用Windows Authentication 已停用。 BasicAuthentication过滤器如下:

using System;
using System.Web;
using System.Web.Mvc;

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)
    {
        Username = username;
        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.Encoding.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;
            }
            else
            {
                throw new HttpException(403, "Forbidden"); // For Elmah
            }
        }
        var res = filterContext.HttpContext.Response; // The 4 lines below cause the login redirect
        res.StatusCode = 401;
        res.AddHeader("WWW-Authenticate", string.Format("Basic realm=\"{0}\"", BasicRealm ?? "MyProject"));
        res.End();
    }
}

我的理解是,在触发http 401时,UseCookieAuthentication中的Startup.Auth.cs重定向到登录,然后又调用BasicAuthentication,从而启动循环直到浏览器抛出错误。这是默认的UseCookieAuthentication

app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });

许多帖子表明web.config需要修改(OwinformsAuthentication等等。)我不会在这里引用它们,因为似乎没有普遍接受的答案。

临时密码保护的index是否会更加明智/优于Beta测试?

1 个答案:

答案 0 :(得分:0)

OWIN Authentication with IIS Basic Authentication,必须删除Startup.Auth.cs中的以下行,以避免启动无限登录循环:

LoginPath = new PathString("/Account/Login"),

这是Cookie身份验证和基本身份验证在MVC中同时工作的唯一方法 - IIS中无需进一步设置。用户通过基本身份验证进行身份验证后,已登录的用户仍然可以通过该站点成功登录。