授权与ASP净MVC 5 Session变量 [英] Authorization with Session variables in asp net mvc 5

查看:119
本文介绍了授权与ASP净MVC 5 Session变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的项目要求改变,现在我想我需要建立自己的行为过滤器。

So my project requirements changed and now I think I need to build my own action filter.

所以,这是我目前登录控制器:

So, this is my current login 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");
    }
}

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

And this is my action filter attempt:

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它只是不断循环的动作过滤器。它的作用的结果是这样的:

I have already added it to FilterConfig, but when I login it does not load Default.cshtml it just keeps looping the action filter. The action result for it looks like this:

//这是位于控制器的MainPage

//this is located in the MainPage controller

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

所以,我会需要什么,以便给予授权加那么只有通过认证的用户都可以查看application's页面?我应该使用Session变量或者是有其他/更好的做这个用的方法是什么?我是pretty太多套牢的authenticateUser(),因为现在会发生什么也就像一个我们现在有一个简单的比较。

So, what would I need to add in order to give authorization so only authenticated users can view the application´s pages? Should I use Session variables or is there another/better way of doing this using? I am pretty much stuck with AuthenticateUser(), since what happens there now is just a simple comparison like the one we have there now.

感谢您的时间。

推荐答案

创建一个 AuthorizeAttribute 用你的逻辑在那里:

Create an AuthorizeAttribute with your logic in there:

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 = filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

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

As long as you have the Login URL Configured in your Startup.Auth.cs file, it will handle the redirection to the login page for you. If you create a new MVC project it configures this for you:

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

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

使用这个你可以用 [AuthorizationFilter] [使用AllowAnonymous] 属性,如果你想装饰你的控制器prevent被检查某些控制器或动作的授权。

Using this you can decorate your controllers with [AuthorizationFilter] and also [AllowAnonymous] attributes if you want to prevent the authorization from being checked for certain Controllers or Actions.

您可能要在不同的场景来检查是为了确保它提供了足够严密的安全措施。 ASP.NET MVC提供了可使用现成的保护您的应用程序的机制,我建议你使用这些如果可能,在任何情况下。我记得有人对我说,如果你试图做认证/安全为自己,你可能就错了。

You might want to check this in different scenarios to ensure it provides tight enough security. ASP.NET MVC provides mechanisms that you can use out of the box for protecting your applications, I'd recommend using those if possible in any situation. I remember someone saying to me, if you're trying to do authentication/security for yourself, you're probably doing it wrong.

这篇关于授权与ASP净MVC 5 Session变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆