Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass data from an AuthorizeAttribute to the Controller?

I have created a custom AuthorizeAttribute which verifies some OAuth credentials that are sent inside the HTTP header. I am using some of these credentials to identify who is making the request. Once I parse this information in the AuthorizeAttribute is there any way to pass it over so that the data can be assigned to an instance variable of the Controller? Then anywhere in my Controller I will have the ID of the requesting party.

like image 373
MetaGuru Avatar asked Jul 12 '11 18:07

MetaGuru


1 Answers

Original answer

You should be able to do this in your filter

filterContext.HttpContext.Items["test"] = "foo";

And then this in your action

_yourVariable = HttpContext.Items["test"];

You'd probably want to use a more unique key than "test", but that's the idea.

EDIT There are two reasons we do this in the action rather than the constructor:

  1. A Controller's constructor fires before OnAuthorization, so the item will not yet be set.
  2. The HttpContext is not yet set in the Controller's constructor.

Alternative solution

  1. Create a new OAuthController : Controller
  2. Override OnAuthorization
  3. Move the logic from your filter into OAuthController.OnAuthorization
  4. Set a protected field (i.e., protected object myAuthData) in OAuthController
  5. Have your other controllers inherit from OAuthController instead of Controller
  6. Your other controllers can access myAuthData.
like image 186
David Ruttka Avatar answered Oct 08 '22 21:10

David Ruttka