我有一个使用我的身份验证过滤器的操作方法:
public class TutorAuthenticationAttribute : ActionFilterAttribute
{
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], Password = cred[1] };
if (userService.AuthorizeTutor(user.Name, user.Password))
{
return;
}
}
filterContext.HttpContext.Response.AddHeader("WWW-Authenticate", $"Basic realm= {BasicRealm}");
filterContext.Result = new HttpUnauthorizedResult();
}
}
然后我想在主页上为已经通过这种方式进行身份验证的用户显示一些内容,但这在我的 View 中不起作用:(
@if (Request.IsAuthenticated)
{
<h1>Hello</h1>
}
我知道它不起作用,因为我不使用 Identity,但有什么方法可以做到这一点吗?
谢谢你的回答:)
最佳答案
我想,在 header 中发送登录名和密码是不安全的。更好的解决方案是验证用户一次。检查后,您可以检查所有请求。
例如,如果您使用 FormsAuthentication
和 authCookie 非常简单:
在 web.config 中设置身份验证:
<authentication mode="Forms" />
当登录名和密码有效时,使用
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie = true);
此步骤仅在用户登录应用程序时执行一次。然后你可以使用属性
this.Request.IsAuthenticated
在 View 中或HttpContext.Current.Request.IsAuthenticated
在 Controller (或过滤器)中。它的工作属性
[Authorize]
关于 Controller 或操作( Controller 中的公共(public)方法)。当请求未通过身份验证时,请求将重定向到默认(或在 web.config 中设置)登录页面。
关于c# - 如何获取用户是否通过 ASP.NET MVC View 中的自定义 Action Filter 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307316/