Daniel Hilgarth
Daniel Hilgarth

Reputation: 174299

Authorization in ASP.NET Web API: Return data specific to authorized user

Let's assume I implemented token based authorization with a custom filter attribute as described here.

Let's also assume, I have a controller that returns tasks:

public IEnumerable<Task> Get()
{
    // return tasks for authorized user
}

Now, how would I go about returning only the tasks for the authorized user? Passing the user ID as a query parameter is not an option - it is forbidden to request the tasks of a different user.

Upvotes: 0

Views: 395

Answers (2)

Matt Johnson-Pint
Matt Johnson-Pint

Reputation: 241450

In the code in the sample you linked to, they are encrypting the user's name in the token. In the filter they are getting this token from an http header, decrypting it back to the username, and querying it against an AuthorizedUserRepository.

AuthorizedUserRepository.GetUsers().First(x => x.Name == RSAClass.Decrypt(token));

You can certainly use a userid instead of the name, and work against a real repository instead of this sample one. You could either do all of this over again in the controller action or constructor, or you could pass it along the route data or some ThreadStatic property. If you want to get really fancy, you could implement claims based security and set a claim on the current thread's principal. Really it doesn't matter how you pass it along.

Ultimately you would just use this value in a where clause of a query or linq statement to filter down to the data you want the user to be allowed to access.

Upvotes: 1

Robert Slaney
Robert Slaney

Reputation: 3722

you could enrich the HttpRouteData from your action filter and read it in the controller action. actionContext.ControllerContext.RouteData.Values.Add("UserId", someVaue );

You could also use the System.Runtime.Remoting.Messaging.CallContext class ( GetData and SetData )

Upvotes: 1

Related Questions