I've got a requirement to allow impersonation ("act as") in my API. So a user with the appropriate permission can exercise the API as another user. I'm wondering if there are some specific strategies employed in this space?
I can create an endpoint to begin and end the impersonation. Beginning the impersonation might involve getting a user and their permissions and loading them into memory for the current request, easy enough. What about subsequent requests? Is it bad practice to add an HTTP header indicating a "Impersonated-User"? If that header exists, use it to do auth on subsequent requests? What about using a cookie with that UserId? Or additional information?
Is there added benefit (assuming a .NET impl) to assigning the impersonated users to the Thread.CurrentPrincipal? The current permission and role implementation is custom, essentially using a bit array (although this is on the table for change in the future).
HTTP doesn't include any native support for delegate credentials / impersonation, so a combination of HTTP Basic Authentication with a custom header indicating which other user the client is trying to act as would be fine.
I would avoid polluting your API with the idea of "beginning and ending the impersonation", however. That implies stateful session knowledge that must be maintained between API calls, and it will make it more difficult to manage on the server side.
I would just have the client pass all the required information (their creds and the impersonation principal) with each call, and validate them each time against the resource being invoked.
Related
I would like to secure a .NET Web API service. I will be using SSL, but I also need to restrict the Web API calls that each user can call depending on the user's permissions.
From what I've read, REST/HTTP is supposed to be stateless, so technically you shouldn't be able to maintain any session state, but there are some ways around that.
One is to use basic authentication. The credentials are sent with every request. While this may be okay security-wise because they're being transmitted over SSL anyway, it really isn't practical given that it would require a lot of overhead to re-authenticate against the database every time. (A possibility might be to cache them in memory, but I doubt that's the best way.)
Another could be to use an HMAC (example implementation) to control access to API calls. There is a comment in this article that says:
Just to be clear to people that are implementing this on their HTTPS services: YOU DON'T NEED TO IMPLEMENT HMAC ON SSL!!! It's a waste of time and waste of complexity for absolutely no reason. DON'T DO IT. Use Basic Auth and be done with it.
I don't agree with this for the reasons mentioned above (it is more practical to authenticate once and control using HMAC than authenticate every time).
Is it a good and effective practice to use an HMAC to provide security to Web API calls when working over SSL, or are there any points that I am missing?
The answer depends on how much you care about security.
What is this API being used for? If security is a big concern, Basic Authentication is NOT a sufficiently good choice -- even if you're using SSL.
Even if you're using SSL, an attacker who can control or get access to your initial request can pretend to be the desired HTTPS web service, and intercept your traffic easily (then get a hold of your API credentials).
A much better solution is to do several things:
Use an API key and secret.
Generate a unique ID with each request.
Generate a timestamp with each request.
Encrypt the body of your request against your API key secret.
Put the encrypted output into the HTTP_AUTHORIZATION header in the form: API_KEY_ID:<encrypted_output>
On the server side, decrypt the payload.
Compare the timestamp -- if the request was sent more than a second before -- drop it (this prevents timing attacks).
Compare the unique id -- if this request was already executed -- drop it (this prevents replay attacks).
The above strategies make it impossible for attackers to gain access to your API credentials, even if they are able to successfully man-in-the-middle your API calls.
I'm trying to implement antiforgerytokens to an angular application's ajax requests.
Is there a lifetime attached with the antiforgerytoken? If I have the app open for a long while in a web browser whithout touching it, say for a month. Will the ajax requests fail due to a stale token?
Can the token be reused for multiple calls? Can I keep one token somewhere in the page and retrieve it for all ajax calls?
Indeed API are supposed to be consumed by 3rd parties, but what's regarding Single Page interfaces with AFT?
I'm concerned they still require AFT in order to prevent CSRF atacks. And here is a good way to use them in Ajax requests.
Antiforgery token is generated per Session, and remains in session data till it's expired. For new session new token will be generated. And yes, single token can be reused multiple times within the same session.
Please check the link I've added, there is example of how token might be obtained for Ajax requests.
Will the ajax requests fail due to a stale token? Yes
Can the token be reused for multiple calls? No
However, the better question to ask yourself is why are you using antiforgery tokens with AJAX in the first place. If you're using AJAX, you're using an API, even if you haven't formalized it as such (just a collection of actions/controllers that are using for AJAX/other headless communication). Antiforgery tokens don't work well with APIs because 1) APIs typically allow third-party access and 2) even if they don't, there's better ways to secure them.
If you want to ensure that only your site can access your "API", then implement HTTP authentication or some other scheme to authenticate your requests to your "API". That is how you allow long running sessions that will not fail.
I want to create a authorization mechanism for an application based on WebAPI and AngularJs.
I've seen some articles, which use BasicHttpAuthentication, but i really don't like the whole idea of sending username, and password on every request. The more it doesn't fit for me is because i want to use OpenId authentication, where you don't have username/password pair.
I'm thinking about a solution, but I don't really know how to implement it. The concept is that user is authenticated as in an usual Web application - posts a form with user / password or selects an OpenId provider. If the user is authenticated succesfully, it is placed in a static object, which stores the User object for a certain ammount of time. Next a usertoken is generated and passed to the Client Application. The client passes the token on each request to the server, if the user exists in the above mentioned static object with the appropriate authentication token it is authorized to get the data.
Firstly - Do you think this is a good approach to the problem?
Secondly - How should I pass the authentication token, WITHOUT using cookies? I guess it should sit in the request headers, like in BasicHttpAuthentication but, I really dont' know how to handle it.
BasicHttpAuthentication
I'm with you on feeling dirty about caching the username and password on the client and forever transferring it with every request. Another aspect of Basic authentication that might work against you is the lack of sign-off. Other than changing the password, you can't "invalidate" a basic authentication session. Tokens on the other hand, will typically offer an expiration date, and if you want server-side invalidation you can check the issue date and say "any tokens older than issue date xyz are invalid".
Server State
You mention "If the user is authenticated successfully, it is placed in a static object". But this is independent of the token? This sounds like you're wanting to implement server state management of authentication sessions, but this isn't strictly necessary. The token itself should be sufficient for user authentication, managing server state is another potential obstacle. Server state can become difficult to manage when you factor app-pool recycles or web-farm environments (what if you want two services to share the same authentication token, but not require communication with a central "authentication server" for storing the state / session?)
Passing Authentication Token
Headers is definitely a good place for it. Really, where else is there? Cookies, Headers, Message. Other than a browser client, cookies don't make a lot of sense, and including it in the message can muddy your message formatting a bit, so headers is the only remaining option that makes much sense in my view.
Client Implementation
You've not specified, but I suspect you're interested in calling the service from .NET? In which case System.Net.Http.HttpClient could be your friend. In particular, the DefaultRequestHeaders collection. You can use this to add a custom header to store your authentication token.
Server Implementation
When researching ASP.NET authentication recently, I learned a lot about customisation by examining the Mixed Authentication Disposition ASP.NET Module (MADAM). I wasn't interested in using MADAM as-is, but learning about it from that article and examining the source code gave me a lot of ideas of how I could insert my own authentication module into the web stack.
I'm using a login form to authenticate users.
FormsAuthentication is right out as it stores sensitive user/role membership in either client-side in a cookie or within the URL. Within the URL is a huge security risk, so I won't even get into that. With the
FormsAuthentication cookie, this creates problems with a) security where the client is in the position of dictating it's own roles; and b) way too much data stored in cookies. Since I'm gaining nothing through security and loosing out big time on the size of user data storage, I'd rather just work with Sessions.
I'd like to reuse something like FormsAuthentication for all its basic login form-handling features. But i would rather have it store user data server-side in perhaps Session rather than client-side all stuffed into a single cookie. I'd rather just authenticate against a Session token of some sort.
I have no database and local disk storage of user data is forbidden. I rely on a 3rd party authentication service provider, and a requirement is that I must reduce chatter with this service. Thus, sessions for temporary storage of user info. Sucks, but that's not necessarily the problem I'm asking about. Also, a requirement is that I must set/use HttpContext.user and likely Thread.CurrentPrincipal for use later on in such things as AuthorizeAttribute, for displaying user info in views, etc.
So FormsAuthentication stores all user data client-side in a cookie. Whereas Session stores all data server-side and just relies on a simple client-side token cookie. However, Session is not available anywhere during the asp.net startup and authentication steps. Is there an equivalent forms "membership" provider that stores all data in Session server-side instead of client-side?
If there is no Session equivalent...
Where do I set HttpContext.user and Thread.CurrentPrincipal to make both values available throughout the rest of both MVC apps without interfering or messing up other MVC components?
Hinging on #1, is Session available at that entry point? If not, how do I make it available so I can create the Principle/Identity object using the data stored in Session?
This can't possibly be a unique requirement. Are there libraries already available which handle this?
Session stores information in a client-side cookie too! (or in the URL if cookieless).
If you want to authenticate a client, he'll have to provide some kind of credentials - usually an encrypted token in a cookie once he has logged on. If not a cookie, then what do you propose?
You should use FormsAuthentication. The sensitive information stored in a client-side cookie is encrypted using a key that should only be known to the web server. "the encryption methods being public knowledge" doesn't mean that you can decrypt the data without access to the appropriate cryptographic key.
You mention "roles" and a "third-party authentication provider". If your third party is also providing roles (i.e. an "authorization provider" as well as an "authentication provider"), then it would be reasonable to cache roles obtained from the provider on the server. Session is not available when a request is being authorized, so the best solution is to use the Cache (System.Web.Caching.Cache).
Personally I would encapsulate this in a custom RoleProvider. The custom RoleProvider would implement GetRolesForUser by getting roles from the third party on the first call, then caching them in Cache.
Not sure if I like what I'm about to suggest, but you could do the following:
Leverage the Application State or System.Cache as a global storage for user credentials.
Use an InMemory database (like RavenDb) which can also have encryption (in memory, I believe).
Using the Application state as a place to storage relatively common / frequent stuff I think is not a great place because of
Scaling / locking issues? <-- just a gut feeling.
Permenant data? so you have users in the website's memory .. then the website crashes or recycles, etc... what happens now to that data?
RavenDb is awesomeballs - go.use.it.now.
I understand that you are not storing anything locally, so whenever a user hits your system, you need to refresh your inmemory cache, etc. Fine. A pain in the f'ing butt , but fine none-the-less. (EDIT: unless the data has been cached in memory .. that is)
Anywys, two suggestions.
ProTip:
Oh! move away from role based shiz and start using Claims based identity stuff. Yes, it still works with IPrincipal and HttpContext.User, etc. So all previous code is NOT busted. But now it's baked into .NET 4.5
Awesome Video on this for you, me, everyone!
Finally - bonus suggestion
A nice package that auth's with either Facebook/Google/Twitter. You said you're keeping the user cred's on another site (good move!). If you're using other providers, then stick with DNOA or SS.
GL!
I'm implementing a rest api to using the new web api framework. This api will be consumed by other companies so we'll be adding an authentication method.
In relation to authentication, I'm thinking to implement something based on tokens. Something like this
client provide credentials to login method
system authenticate client and send a token
client uses this token on following api calls
I wonder if this schema is useful for my scenario. Operations will be mainly atomic, basically clients will periodically ping this api to get some specific data, so not sure if make sense having a session token (at some point the token should expire and not sure how to manage this).
How would you recommend to implement authentication schema for this scenario?
When you generate a token I would store it in a database with a foreign key back to the authenticated login's primary key. I would also (with the token) store the date and time it was established, and a timeout period (you could set this per token, or store it in a config). Check the token/time everytime the service is pinged by that user, then force them to reauthenticate after that time expires (by checking it against the created date stored with the token).
This would make sure that the login information is only getting transmitted after the token expires, when a new token is generated it would delete the old token record.
Am I understanding your requirements right?
Making a token based authentication scheme like this is not easy.
I don't really have an answer for how you could implement it in a good and secure way. But will offer some thoughts off the top of my head about issues you will have to deal with:
The token generation need to be well randomized and the tokens need to be "sufficiently" (for some definition of sufficient) long in order to prevent someone from simply sending a bunch of different tokens to see if he "gets a hit"
The above issues should not be too difficult to implement. But the more tricky thing to figure out is:
How you can you reliably verify that the token has not been "kidnapped".
If the token is simply some random string, then anyone who happens to "see" it in tranfer (use SSL) will be able to assume the identity of the use for which the token was generated.
The token, when received by your service will let you know that:
Your application issued the token to user/application/entity X
The token is intact (has not been changed)
Any other thing you store with the token (is it expired etc)
But it will not without further effort let you know for sure that it was sent by user/application/entity X. It could be Y who has managed to get hold of the token.
That is the case for many authentication schemes of course, so depending on just how sensitive your data is, and also on what kind of operations can be done via you service, it may not be a huge issue for you.