如何获取控制器中所有操作的当前用户?

时间:2014-07-01 16:47:33

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

这是一个双人

问题1(真正的问题)

我有一个与模型无关的DashboardController。必须先登录User才能访问信息中心。如何在执行每个操作之前运行检查以查看用户是否已通过身份验证,如果没有,则将其重定向到登录视图?我认为OnActionExecuted是我想要的,但我不确定具体的实现应该是什么。我在这里走在正确的轨道上吗?

public class DashboardController : Controller
{
    private ApplicationContext db = new ApplicationContext();

    //
    // GET: /Admin/
    public ActionResult Index()
    {
        var categories = db.Categories.ToList();
        return View(categories);
    }

    public ActionResult Product(int id)
    {
        var product = db.Products.Find(id);
        return View(product);
    }

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if(Session["current_user"] == null)
        {
            // This (obviously) doesn't work - what should go here?
            return RedirectToAction("Create", "Session"); 
        }
        base.OnActionExecuted(filterContext);
    }
}

问题2

如果用户已登录,那么正确的方法是什么使用户可以在所有这些视图中访问?我被告知ViewBag通常是一个坏主意 - 我应该使用什么?

6 个答案:

答案 0 :(得分:2)

我可以通过以下链接授权控制器和操作: 它最初是巴西葡萄牙语,但下面的链接被翻译成英语。

https://translate.google.com.br/translate?sl=pt&tl=en&js=y&prev=_t&hl=pt-BR&ie=UTF-8&u=http%3A%2F%2Fdevbrasil.net%2Fprofiles%2Fblogs%2Fautentica-o-e-permiss-es-de-usu-rios-em-asp-net-mvc-4&edit-text=&act=url

您可以通过

在视图中获取已登录的用户
@HttpContext.Current.User.Identity.Name

PS:对不起,我的英文不好

答案 1 :(得分:1)

使用[Authorize] atrribute。 例如:

    [AcceptVerbs(HttpVerbs.Get)]
    [Authorize]
    public ActionResult add()
    {

    }

然后在web.config

<authentication mode="Forms">
  <forms name="my_cookie_name" loginUrl="~/login" defaultUrl="~/" timeout="2880"/>
</authentication>

如果用户未经过身份验证,则会自动将其重定向到登录页面。

如果您想要一些简单的方法来控制用户的身份,请在此处查看评分最高的答案:ASP.NET MVC - Set custom IIdentity or IPrincipal。这是一个很好的例子。我在所有项目中都使用类似的东西。

在我的登录操作

var user = _userService.system_login(systemlogin_model_post.email, systemlogin_model_post.password); // my user model 

//... doing all sorts of validations
// once everyone is happy I create a cookie

Response.Cookies.Add(UserCookie.GetCookie(user));

使用上面链接中的代码,我创建了cookie:

 public static class UserCookie
    {
        public static HttpCookie GetCookie(User user)
        {
            CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel { user_id = user.UserId, username = user.Username, roles = user.Roles ,session_token =  GUIDGenerator.ToAlphaNumerical() };
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string userData = serializer.Serialize(serializeModel);
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
               user.UserId.ToString(),
               DateTime.Now,
               DateTime.Now.AddMinutes(30),
               false,
               userData);

            string encTicket = FormsAuthentication.Encrypt(authTicket);
            return  new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        }
    }

[Authorize]被解雇时,此代码会处理它:

Global.asax中

protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);

                CustomPrincipal newUser = new CustomPrincipal(authTicket.Name);
                newUser.user_id = serializeModel.user_id;
                newUser.username = serializeModel.username;
                newUser.roles = serializeModel.roles;
                newUser.form_token = serializeModel.form_token;

                HttpContext.Current.User = newUser;
            }
        }

答案 2 :(得分:0)

1)ASP.NET MVC的授权属性完全集中在你的第一个问题上。您甚至可以进行自定义,但在大多数情况下都不建议。

2)要分配当前登录的用户并在所有视图中可见,您可以使用ViewBag / ViewModel属性将用户名绑定到Layout(_Layout.cshtml),以便它显示在布局所在的每个页面的顶部。使用

注意:如果要执行任何预操作调用逻辑,则在输入该操作方法之前,OnActionExecuting过滤器是正确的位置。

答案 3 :(得分:0)

确切地说,您必须创建一个类,该类继承Controller类。

public class MyAuthentication : Controller
{
  public MyAuthentication()
    {
        isAuthenticated();
    }  

    private void isAuthenticated()
    {
      // do your authentication


      //if user authenticated keep user details within a cookie, so that 
      // when the next request, program logic will search for cookie, 
      //if it is found then assume user was authenticated else redirect to login page.

    }
}

然后在项目中为所有控制器继承此MyAuthentication类

public class DashboardController : MyAuthentication  
{

    public ActionResult Index()
    {
        var categories = db.Categories.ToList();
        return View(categories);
    }

    // rest of the codes
}

这样身份验证仍然保持在一个位置。您可以随时随地继承。

答案 4 :(得分:0)

如果您需要控制器/操作中的任何位置的当前用户,则更好的方法是在执行授权时设置用户数据。

在授权过滤器中,您可以使用

System.Web.HttpContext.Current.Items["userdata"]=userDataObject;

对于身份验证,本文可以提供帮助。

http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html

答案 5 :(得分:0)

首先在用户登录时输入表单身份验证Cookie,例如

[HttpPost]
public ActionResult Login(Acccount obj){
// check whether the user login is valid or not
    if(UseIsValid){
        FormsAuthentication.SetAuthCookie(obj.username, obj.RememberMe);
        return redirectToAction("Index","DashBoard");
    }
    return View(obj);
}

*     并使用[授权]属性。像*

[Authorize]
public class DashboardController : Controller
{
    private ApplicationContext db = new ApplicationContext();

    public ActionResult Index()
    {
        var categories = db.Categories.ToList();
        return View(categories);
    }
}