gpt4 book ai didi

asp.net - ASP.NET MVC 5 中的基本身份验证

转载 作者:行者123 更新时间:2023-12-03 07:07:21 25 4
gpt4 key购买 nike

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

我了解到 OWIN 不支持 cookieless 身份验证,那么基本身份验证通常可行吗?

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

最佳答案

您可以通过自定义 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();
}
}

它可用于将整个 Controller 置于基本身份验证下:

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

或特定的 ActionResult:

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

如果您需要更多信息,请查看 this blog post我就这个主题写的。

关于asp.net - ASP.NET MVC 5 中的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20144364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com