3

I'm using MVC3 with Razor view engine.

I need to generate a different AntiForgeryToken for each user.

I'm thinking of generating a unique salt value and store it in users table when the users registers, and to use that salt to generate the token, but how can I bypass that salt value to the attribute ValidateAntiForgeryToken. I think I need to define a customized attribute but I don't know how would that go (with getting access to user information to use the salt value).

Thanks in advance.

Ken D
  • 5,880
  • 2
  • 36
  • 58
  • didn't you just ask a similiar question? – Mitch Wheat Jan 02 '12 at 00:43
  • You didn't really explain why you can't just use the default mechanism. – CodesInChaos Jan 02 '12 at 00:44
  • 1
    @MitchWheat No, that is a different question, read both well, I'm asking about different things. You may notice, it's not my 1st day on SO. – Ken D Jan 02 '12 at 00:46
  • looks similiar to me: http://stackoverflow.com/questions/8696520/does-it-make-sense-to-populate-an-antiforgerytoken-in-login-register-forms – Mitch Wheat Jan 02 '12 at 00:46
  • @CodeInChaos, in the default mechanism, as I understood, I am limited to use a static salt value, I want a different one for each user. – Ken D Jan 02 '12 at 00:46
  • 1
    I think the default mechanism has one token per session. And since there shouldn't be more than one user per session, I don't see the problem. – CodesInChaos Jan 02 '12 at 10:24
  • Don't use the salt. The username is automatically embedded in the token. There is no need to make a custom salt per-user. – RickAndMSFT Jan 03 '12 at 00:42

2 Answers2

5

If you want a different salt, then you'll need to roll your own off the existing code or come up with a new scheme.

However keep in mind, these tokens are already user specific. Someone logged on as user A cannot use a token from user B's session.

Also note they are not one time use tokens, so what are you trying to prevent here? Make it so user A cannot generate one for user b? again - keep in mind user a isn't logged on as user b, so the check that is currently done would fail if this is forged.

Adam Tuliper
  • 29,982
  • 4
  • 53
  • 71
1

Here's a very similar question with a great solution:
runtime loading of ValidateAntiForgeryToken Salt value

Basically, you'll just need to create an attribute that wraps the functionality of the ValidateAntiForgeryToken attribute, using a custom salt value at runtime.

Another great thing in that solution: the attribute can be applied at the Controller level, automatically applying to all POST methods.

However, as others have said, the MVC AntiForgeryToken implementation already uses the username in generating the token, so unless you have ulterior motives, doing this won't gain you anything.

Community
  • 1
  • 1
Scott Rippey
  • 15,614
  • 5
  • 70
  • 85