我有一个使用身份验证过滤器的操作方法:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我想在主页上显示已通过这种方式验证过的用户的某些信息,但这在我的View中不起作用:(
@if (Request.IsAuthenticated)
{
<h1>Hello</h1>
}
Run Code Online (Sandbox Code Playgroud)
我知道它不起作用,因为我不使用身份,但是有什么办法可以做到这一点?
谢谢你的回答:)
小智 4
我想,在标头中发送登录名和密码是不安全的。更好的解决方案是验证用户一次。检查后,您可以检查所有请求。
例如,如果您使用FormsAuthenticationauthCookie,那就非常简单:
在 web.config 中设置 authmentod:<authentication mode="Forms" />
当登录名和密码有效时,使用FormsAuthentication.SetAuthCookie(userName, createPersistentCookie = true);当用户登录应用程序时,此步骤仅执行一次。
然后您可以在this.Request.IsAuthenticated视图或HttpContext.Current.Request.IsAuthenticated控制器(或过滤器)中使用属性。
它适用[Authorize]于控制器或操作(控制器中的公共方法)的属性。当请求未经过身份验证时,请求将重定向到默认(或在 web.config 中设置)登录页面。