Fra*_*nko 11 c# asp.net asp.net-mvc basic-authentication antiforgerytoken
我正在开发支持表单身份验证的ASP.NET MVC5项目.Project目前处于测试阶段,并在Azure上进行在线托管,但项目所有者希望禁用对该站点的所有公共访问(因为站点的某些部分根本不需要用户进行身份验证).
在此测试阶段,我们决定从此链接实施基本HTTP身份验证.我已经更改了代码,因此它更符合我的需求:
public class BasicAuthenticationAttribute : FilterAttribute, IAuthorizationFilter
{
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 void OnAuthorization (AuthorizationContext 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;
}
var res = filterContext.HttpContext.Response;
var alreadySent = HttpContext.Current.Items.Contains("headers-sent");
if (!alreadySent)
{
res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
我还将它注册为全局过滤器:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorExtendedAttribute());
filters.Add(new BasicAuthenticationAttribute(AppConfig.BasicUsername, AppConfig.BasicPassword));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,运行项目时存在一些问题.如果我使用这个版本的代码:
if (!alreadySent)
{
res = filterContext.HttpContext.Response;
res.StatusCode = 401;
res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
}
Run Code Online (Sandbox Code Playgroud)
成功登录后,它会不断重定向到表单登录页面.
但是,如果我追加
res.End();
Run Code Online (Sandbox Code Playgroud)
后
res.AppendHeader("WWW-Authenticate", String.Format("Basic realm=\"{0}\"", BasicRealm ?? "Test"));
Run Code Online (Sandbox Code Playgroud)
cshtml文件中的Antiforgerytoken抛出System.Web.HttpException
发送HTTP标头后,服务器无法附加标头.
但在这种情况下,它最终成功进行了身份验证.
我目前仍然坚持这一点,并且不知道如何解决这个问题,因为关闭表单身份验证不是和选项,我无法删除所有AntiForgeryTokens及其验证.
您在 res.AppendHeader(..) 之前尝试过这一行吗?
Response.ClearHeaders();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
837 次 |
| 最近记录: |