MVC Security problems in my application - Best str

2019-06-03 10:16发布

问题:

I feel like the biggest idiot - I thought only ActionResults were sent back to the client. For this reason, I had a load of "helper" methods in my controller.

I just tried accessing them via a URL and I swear I almost went crazy when I saw they can be reached! ... Luckily, no one else has discovered this yet.

One such method I have, that I call over and over again is :

public User GetCurrentUser()
{    
    User user = db.Users.SingleOrDefault(x => x.UserName == User.Identity.Name);
    return user;
}

I have just created a folder called "Logic" inside my Models folder and I am attempting to separate the code - I was just wondering what the best strategy is for calling code, namespaces and more?

In the above example, I am using User.Identity.Name which only inherits from Controller. If I add this, I am back to stage one!

Thanks to Darin Dimitrov, I now know about the [NonAction] Attribute - which, adding to these methods does exactly what I need/fixes the security problem, however, many of these Methods are used in different controllers and I know it would be best if I can separate the logic from the controllers. I am just not sure what the best way to go about it is.

Can anyone point me in the right direction before I start pulling all my hair out!?

回答1:

You may take a look at the [Authorize] attribute.


UPDATE:

Or you could use the [NonAction] attribute or make the method private. But the best practice in this case would be to simply move this logic out of your controller. A controller should contain only controller actions. Other logic should be placed in its respective layers.