Andrew
Andrew

Reputation:

Securing controllers in ASP.NET MVC to the correct user

I am building an application in ASP.Net MVC to log tasks.

A user can delete only their own tasks. Is there a standard way to prevent a different logged in user, from simply typing in the delete controller url, with an [id] parameter of a task that belongs to another user, thus deleting another users task?

Example:

User A has a task with an id of 13. When User A views the task, there is a link to /tasks/delete/13 to delete the task record. User B can view task 13 and then decides to enter /tasks/delete/13 into the address bar and therefore deletes User A's task.

Do you have to write your own code within the controller to prevent this, or is there a standard way this is usually handled?

Many thanks!

Upvotes: 0

Views: 259

Answers (2)

Todd Smith
Todd Smith

Reputation: 17282

When it comes to security in ASP.NET MVC you have Authentication and Authorization.

Authentication is the process of validating a user's identity and usually involves checking a username and password against a database and then assigning some kind of user ID to that user.

Authorization is the process of restricting access to system resources and is often done via Roles (RBAC). However, Roles don't often cover ownership which is what you're after.

In your case you will need to write your own code to perform an ownership check on the task such as:

if (!task.IsOwnedBy(userID))
{
  throw new HttpException ((int)HttpStatusCode.Unauthorized, 
                           "You are not authorized.");
}

I asked a similar question here How do you weave Authentication, Roles and Security into your DDD? and have yet to decide how I'm going to integrate this into my business layer.

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180948

The NerdDinner application has just such an example in its Dinners controller.

http://nerddinner.codeplex.com/

The instructions on how to do this are here:
http://nerddinnerbook.s3.amazonaws.com/Part9.htm

Go about halfway down the page until you see the headings: Using the User.Identity.Name property when Creating Dinners and Using the User.Identity.Name property when Editing Dinners.

Upvotes: 1

Related Questions