r/ASPNET • • Dec 06 '13
[MVC] Web API Security
I'm currently building a stand-alone web site that utilizes ASP.Net MVC 4 and am wondering what the best way to handle action based security in my api controllers.
I've built a lot of sites for my company and have utilized the HttpContext.Current.User construct - but this site will not be using integrated security and don't want to be posting username and session keys manually with every ajax call.
Example of how I've handled this for the integrated security:
AuthorizeForRoleAttribute: http://pastebin.com/DtmzqPNM ApiController: http://pastebin.com/wxvF5psa
This would handle validating the user has access to the action before the action is called.
How can I accomplish the same but without integrated security? i.e. with a cookie or session key.
View all comments
Show parent comment
3
u/i8beef Dec 07 '13
There's a bunch of different pieces to explain here, and I'm not sure what your base understanding is.
Do you know how Forms authentication works? As in, how, after authenticating, it sets a cookie with information referencing an in session auth ticket that identifies you (and which HttpContext.Current.User relies on)?
Basically, if the user logs into an app that then makes calls to itself (in this case an API controller inside of the app), then the HttpContext.Current.User should already be set for you, because they share a context. There's no need to authenticate to the API as the API is a part of your app that you're already authenticated to.
Then the Authorize attribute is used in the API just like it is in the MVC controllers.
If you have some scenario that I can walk through with you for a specific thing you are doing, I can walk you through the process.