c# - 在 asp net mvc 5 中使用 session 变量进行授权

标签 c# asp.net asp.net-mvc asp.net-mvc-4

所以我的项目需求发生了变化,现在我认为我需要构建自己的操作过滤器。

所以,这是我当前的登录 Controller :

 public class LoginController : Controller
{
    // GET: Login
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]

    public ActionResult Login(LoginViewModel model)
    {  
        string userName = AuthenticateUser(model.UserName, model.Password);
        if (!(String.IsNullOrEmpty(userName)))
        {
            Session["UserName"] = userName;
            return View("~/Views/Home/Default.cshtml");
        }

        else
        {
            ModelState.AddModelError("", "Invalid Login");
            return View("~/Views/Home/Login.cshtml");
        }
    }

    public string AuthenticateUser(string username, string password)
    {
        if(password.Equals("123")
            return "Super"
        else
            return null;
    }

    public ActionResult LogOff()
    {
        Session["UserName"] = null;
        //AuthenticationManager.SignOut();
        return View("~/Views/Home/Login.cshtml");
    }
}

这是我的操作过滤器尝试:

public class AuthorizationFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (HttpContext.Current.Session["UserName"] != null)
        {
            filterContext.Result = new RedirectToRouteResult(
                   new RouteValueDictionary{{ "controller", "MainPage" },
                                      { "action", "Default" }

                                     });
        }
        base.OnActionExecuting(filterContext);
    }
}

我已经将它添加到 FilterConfig,但是当我登录时它不会加载 Default.cshtml,它只是不断循环操作过滤器。它的操作结果如下所示:

//这位于MainPage Controller 中

 [AuthorizationFilter]
    public ActionResult Default()
    {
        return View("~/Views/Home/Default.cshtml");
    }

那么,我需要添加什么才能授予授权,以便只有经过身份验证的用户才能查看应用程序的页面?我应该使用 session 变量还是有另一种/更好的方法来使用?我几乎被 AuthenticateUser() 困住了,因为现在发生的只是一个简单的比较,就像我们现在的比较一样。

感谢您的宝贵时间。

最佳答案

用你的逻辑创建一个AuthorizeAttribute:

public class AuthorizationFilter : AuthorizeAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
            || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
        {
            // Don't check for authorization as AllowAnonymous filter is applied to the action or controller
            return;
        }

        // Check for authorization
        if (HttpContext.Current.Session["UserName"] == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

只要您在 Startup.Auth.cs 文件中配置了登录 URL,它就会为您处理到登录页面的重定向。如果您创建一个新的 MVC 项目,它会为您配置:

public partial class Startup
{
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCookieAuthentication(
            new CookieAuthenticationOptions {

                    // YOUR LOGIN PATH
                    LoginPath = new PathString("/Account/Login")
            }
        );
    }
}

使用它,您可以使用 [AuthorizationFilter][AllowAnonymous] 属性来装饰您的 Controller ,如果您想要防止检查某些 Controller 或操作的授权。

您可能想在不同的场景中检查它以确保它提供足够严格的安全性。 ASP.NET MVC 提供了开箱即用的机制来保护您的应用程序,我建议您尽可能在任何情况下使用这些机制。我记得有人对我说,如果你想为自己做身份验证/安全,你可能做错了。

关于c# - 在 asp net mvc 5 中使用 session 变量进行授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30372022/

相关文章:

c# - 如何判断一个C#控件是否正在被卸载?

c# - Clickonce - 在 DVD 上部署,使用离线安装程序

asp.net - 在 Azure 网站上使用 Azure 缓存服务(预览版)时出现问题

c# - 我如何使用 radsearchbox 的 AutoPostback 功能?

c# - 如何在 HttpWebRequest POST 中将对象作为参数传递?

c# - 通过扩展 DefaultControllerFactory 实现 DI 与实现 IDependencyResolver 之间的区别

jquery - 如何在 asp.net mvc 中将 ID 属性添加到 Html.BeginForm()?

c# - 有没有办法在不将其放入 div 的情况下制作可滚动的 gridview?

c# - WCF - 接收对 http ://xxxxx/Service/的 HTTP 响应时出错

c# - 将域模型类型转换为 ViewModel