2

So I'm working on a webfrom project in mvc4 and Razor,I need to store accounts information in session, and only the Account Manager Module is permitted to modify them.I wrote a class to try to implement it.

my code

public static class AccountProvider
{
    public static bool Login(this HttpContextBase ctx
        , string userName, string password)
    {
        var account = new AccountBase{UserName = userName};
        ctx.Session["Account"] = account;
        return true;
    }

    public static string GetName(this HttpContextBase ctx)
    {
        var account = ctx.Session["Account"] as AccountBase;
        return account.UserName;
    }

    private class AccountBase
    {
        public string UserName { get; set; }
    }
}

and I can login with this:

HttpContext.Login("Admin","1234567");

then show the account information on the view:

Hello @(Context.GetName())!

It seems very simple, the outer codes can't modify the account information which in session indeed, excepting using Reflection.

I can easily use the following code in view pages to change account information:

Hello @(Context.GetName())! //print "Hello Admin!"
@{
    var account = Session["Account"];
    var type = account.GetType();
    var item = Activator.CreateInstance(type);
    var p = type.GetProperty("UserName");
    p.SetValue(item, "aaaaa");
    Session["Account"] = item;
}
Hello @(Context.GetName())! // print "Hello aaaaa!"
  • Is there any way to really prevent outer code modifying the private data in mvc c#?
  • How can I store the security information (like account info) more safely?

Appreciated for any suggestion.

tereško
  • 58,060
  • 25
  • 98
  • 150
Chris
  • 339
  • 4
  • 17

1 Answers1

0

You can't prevent outer code modifying the private data. But as long as it is your code you won't have any problem because you won't do bad things.

If you need to use plugins, you can sandbox them and deny reflection permission. Read How to deny reflection using ReflectionPermission for more information

Community
  • 1
  • 1
meziantou
  • 20,589
  • 7
  • 64
  • 83