c# - 如何获取用户是否通过 ASP.NET MVC View 中的自定义 Action Filter 进行身份验证?

标签 c# asp.net

我有一个使用我的身份验证过滤器的操作方法:

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 非常简单:

  1. 在 web.config 中设置身份验证:<authentication mode="Forms" />

  2. 当登录名和密码有效时,使用FormsAuthentication.SetAuthCookie(userName, createPersistentCookie = true);此步骤仅在用户登录应用程序时执行一次。

  3. 然后你可以使用属性this.Request.IsAuthenticated在 View 中或 HttpContext.Current.Request.IsAuthenticated在 Controller (或过滤器)中。

  4. 它的工作属性[Authorize]关于 Controller 或操作( Controller 中的公共(public)方法)。当请求未通过身份验证时,请求将重定向到默认(或在 web.config 中设置)登录页面。

关于c# - 如何获取用户是否通过 ASP.NET MVC View 中的自定义 Action Filter 进行身份验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41307316/

相关文章:

c# - 如何在WPF中的UserControl中运行BackgroundWorker?

c# - .NET 在不同时区和不同区域设置的 SQL 中存储 DateTime

c# - 覆盖字符串属性问题

javascript - 如何在 ASP.NET MVC 中 foreach 内部脚本标记

c# - 如何将十六进制颜色转换为 RGB 颜色(24 位)

asp.net - 如何从 Jquery 调用 ActionResult

asp.net - jquery ui 选项卡在回发时重定向到 ASPX 页面

c# - 空条件运算符,在某些机器上的行为不符合预期

javascript - Sys.WebForms 在 Chrome 中未定义

asp.net 为复选框存储 cookie/ session