Asp.net web api Session - javascript

I'm not getting the concept web api and session.
I've created asp.net web api project and integrated angularjs in it.Every time I'm gonna call web api.
I have read the articles which state its not good to use session in Web api. I do understand that web api is stateless approach. I do agree. stil there is a way to use session.
First question: If, after login, i want to show user name on every page what should i do with web api approach????
second question: they say don't use session in webapi. then what is the other way/approach to store client information safely.
If I use HTML5 local storage, it can be editable.
If cookie is used, it can be deleted.
What and how should I do it for user till application is in running mode?

This is where semantics often clouds the discussion. People confuse the Session object with statelessness. And often say: 'don't use session because it isn't stateless!'.
However they really mean that you should strive to have your the restful calls to be idempotent, meaning they don't change their behavior depending on whatever it is you do in the background.
Session, or the runtime-cache, or whatever it is you use to cache data, has no effect on your stateless design, because really, what's next? Your database is statefull too? And you shouldn't read data from that? Nonsense obviously; your underlying storage, if it's in-memory or on disk has no reflection on your state to the client.
Although I feel #MajoB makes other valid points about not using the session object, there is really no harm using some kind of cache in the web api, session or something else. But never let the fact if something is IN session return a different result then when something is OUT of session.

I would recommend you to avoid asp.session because it may cause performance issues and can expire anytime regardless of your application state, does not scale on cloud, it will block concurrent ajax requests). Better approach would be to use HTML 5 storage mechanism especially in conjunction with AngularJs (you can use ng-storage https://github.com/gsklee/ngStorage).

I would recommend you use asp.net identity and render user information on server.

Related

What is Stored in Stateless JSON Web Tokens

I have been reading up on JWT recently, and feel I have a pretty decent grasp of how they are made and how the could be used for authentication.
If I understand correctly, a challenge with stateful applications occur when I need several web services (APIs), one for each type of device using the app (web, mobile, etc.). Then, the web services must somehow synchronize the session states, which is hard.
Instead, we store state client-side (preferably in cookies) within encrypted and signed JWTs.
Have I understood it correctly so far?
Then, my main question: What exactly is stored in the JWT, for let's say an online store? Does it completely replace all user info stored in a database? So, profile information, images, shopping cart, saved content (articles, repos, etc. if applicable), and more. Is all this, and all other imaginable content differing from one user to the next, saved inside the JWT?
In conclusion, I am trying to get at what is meant by stateless in JWT use cases? Do we store all user info in the token?
[..] when I need several web services (APIs), one for each type of device using the app (web, mobile, etc.).
I would argue that it's bad architecture to separate your server backend by the type of client. Ideally the backend will offer the exact same API to web clients and mobile clients (and any other clients). Otherwise you have a huge duplication and overhead for every supported feature.
So instead, let's just concentrate generically on the case where you have several servers. Any serious large scale web site, think Amazon.com, has way more than a single server serving their web site. They have individual server instances coming online automatically as demand increases and dropping back offline as traffic ebbs. Load balancers direct traffic to individual servers as necessary.
In that kind of scenario, especially with a shopping site, you have several ways to handle state then, each of which has certain pros and cons:
Use sticky sessions, which means web servers are stateful and store session information, and the load balancer is aware of the used cookies and will direct traffic from the same client to the same server so only one server needs to hold on to the session info. This makes the server implementation relatively simple, but has certain drawbacks in operation:
The load balancer needs to be able to handle sticky sessions.
The server needs to stay online while the client exists, otherwise the session information is discarded.
If the client moves geographically to another load balancer, they may get disconnected from their session.
Use a shared session storage backend, so each server essentially shares the same information. That negates the drawbacks from using sticky sessions, but obviously re-introduces the bottleneck of a single shared resource and impacts scalability. That can be mitigated to some extent by using good caching strategies, but writing to shared storage still requires an enormous backend.
Keep everything stateless and handle as much as possible on the client itself. The client remembers its own history and/or basket contents. All the server needs to do is provide the product information, which is non-client specific and therefore extremely scalable. Of course, when it comes time to checkout or do other client-specific things, the server will need to do client-specific actions and use a session of some sort or another, but that is just a fraction of the traffic compared to casual browsing and much less of a problem.
In this kind of scenario, JWTs serve to carry information which needs to be validated, like who a user is, i.e. authentication. For authentication purposes, you can either:
Have the client authenticate themselves with every request, i.e. send their username and password with every request. That is obviously a bad idea, since you don't want to send the password back and forth constantly. It would also require a query to a central database on the backend each and every time, which undermines scalability again.
Give the user a token of some sort which authenticates them. The drawback here is that is requires a shared token store, see #2 above.
JWTs let you have it both ways: the user essentially claims on every request that they're user X (without sending their password), and because the JWT is signed by the server, it allows the server to actually trust that claim. Each server can verify the signature independently, and hence trust the claim independently on each request, and thus remain stateless and also not require any sort of shared storage.
A drawback of storing information in JWTs is that they only exist on one client, so any information you store there ceases to exist once the user moves to another client or clears cookies; so synchronising a shopping basket between devices for a user account is not possible with just JWTs alone.
In practice, you'll probably use at least two, probably all three approaches together. You'll have some shared storage somewhere to store account information (including the shopping basket), but you reduce the need to contact that storage as much as possible by also caching that data in sticky sessions and/or JWTs. Stateless authentication via JWTs is something of a no-brainer. For everything else, you decide on the right tradeoff between imparting load on a shared storage, how up-to-date any shared/cached state will be, and the end user experience.

Meteor and Session/Common Data

Progressing along with my isomorphic javascript crusade, I put Meteor on a hold while I played a bit more with the MEAN stack. To ward off any further procastination, I've decided to finish my original prototype community application. Now, my biggest issue with Meteor isn't reactivity, it's session/common data.
I know Meteor's native session system is based off of the reactive concept, and cookies don't "exist" because Meteor operates on "the wire". Though let's say I were building an application on the LAMP or mean STACK, and I was creating a user interface. I'd use cookies/sessions to control user activity. If Meteor operates off of reactivity, how do I maintain persistence?
I have searched through atmosphere for packages that fit my criteria, and I ran into a couple of packages that store "presistent sessions". Though these interfaces operate off of the client, not the server; hence my code would be exposed client, therefor setting the application up for exploitaton.
All that being stated, I know Meteor has it's standard user interface. What I'm trying to do here is understand Meteor, and gain experience for future endevours.
Meteor has a built-in login system that keeps track of the logged-in user, which is one of the main reasons people use cookies. If you want to store other data on the client in a persistent way, you can use the HTML5 localStorage API.
I think what you're referring to is that something like PHP lets you store data in a "SESSION" variable that is actually stored on the server, but persisted between different requests from the same client.
If this is what you are looking for, there are several approaches that will give you similar functionality:
Store data associated with a particular user, and use the userId that Meteor gives you to only publish it for that user (using Meteor.publish)
Have a randomly generated client ID that is stored in localStorage, and pass that in when calling subscriptions or methods to authenticate as that client. This will work in the case where the user is not logged in, and will give you a very similar result to cookies/session in PHP. You will still store the actual data in the database on the server, but you will know which data is associated with a particular client by the unique ID.
It's true that Meteor's Session variable is named in a way that can be confusing if you are coming from PHP where SESSION means something totally different.
Does this answer your question?

How to make a web API private

I have an API that I would like to restrict access to. I can provide access keys and check them with each request, but I'm not sure how far this is really going to go.
The API is used by applications, but it is also used by a web app which someone can just view the source of. If they did, they would have the key and could easily make API calls.
Is there a more reliable way to secure access? I'm not sure what the standard practice here is.
Edit: After thinking about it, I could use a two-prong approach. The web app can use POST with CSRF, and applications can use API keys. Any other ideas, or is this a generally accepted solution? (Note, this still wouldn't work for third-party web apps.)
Your API is never private since it's used by a web app which I am assuming is available to the general public. If this is the case, there really is no impetus to secure it since anyone and everyone would have access to the API.
If on the other hand, this web app is only available to registered users, you can use a token system to check for authorization. When the user successfully logs in, you pass back a token (usually something 20 to 30 characters long). Every API request would require a valid token. Tokens can be set to expire automatically (using a database job) X hours after creation if your application requires higher security thresholds. If security isn't a big issue, they can be renewed automatically every time a request is made.
This is essentially a two tiered approach. Temporary tokens are generated for users to directly connect to your API so that permanent credentials are never sent to the client. Predefined keys are given to third party developers who build applications on top of your API and have their own back-end.
If it's your API you can simply do this.
1) Insert the following code into your API file(s)
$authToken = "APItoken"; //variables
if( !isset($_REQUEST["authToken"]) || $_REQUEST["authToken"] != $authToken )
die("Need auth token");
2) You will now need to GET/POST/PUT the URL like this:
http://www.yoursite.com/api1.php?authToken=APItoken&nextParam=&paramAfterThat=
If this helped please mark it as the answer
EDIT:
Nevermind, read it wrong. Updating answer in a few minutes.

oAuth2 authentication on a JavaScript app

I'm planning to refactor a legacy Rails 2 app by splitting the logic into a RESTful API, and the view into a separate Javascript client. The API itself will be protected by oAuth2. This is basically the second option explained on this question:
Separate REST JSON API server and client?
There's a lot of questions out there concerning the security of using oAuth with a JS app, the main concern seems to be that storing the access token on the client is a bad idea since it acts as a password and someone that has physical access to the computer can hijack the user's identity. A possible solution I've read is to expire the access token every 1h or so and use the refresh token stored on Yahoo's YQL to request a new token when necessary. This doesn't looks to me like a good solution since at the end you'll need again a token to access the YQL service.
But at the end, aren't we facing the same problem as when using persistent sessions? I mean, AFAIK, the common method to keep the session alive across browser opening/closing (when you tick "remember me") is to generate a token associated to a user and store it both on the DB and on a long-living cookie. So again, anyone with access to this cookie has the "key" to your session. AFAIK this is the method all the "big guys" use.
I am right? And if I am, aren't we worrying too much about something that we cannot control at all? Of course I'm talking about those applications where an intrusion is not too harmful for the user like social networks, blogs, forums, etc.

JavaScript - Storing data during user interaction

I'm working on a web based form builder that uses a mix of Jquery and PHP server side interaction. While the user is building the form I'm trying to determine the best method to store each of one of the form items before all the data is sent to the server. I've looked at the following methods
Javascript arrays
XML document
Send each form item to the server side to be stored in a session
The good, the bad and the ugly
Depends on your application functionality and requirements, but Javascript would probably be the best way. You can use either arrays or objects or whatever in javascript. It's server independent and it will preserve data over a long period of time as long as client session stays present (browser window doesn't close for whatever reason) but this can be quite easily avoided (check my last paragraph).
Using XML documents would be the worst solution because XML is not as well supported on the client side as you might think.
Server side sessions are good and bad. They are fine if you store intermediate results from time to time, so if client session ends because of whatever reason, user doesn't loose all data. But the problem is that it may as well expire on the server.
If I was you, I'd use Javascript storage and if needed occasionally send JSON serialized results to server and persist them there as well (based on business process storig this data somewhere else than session could be a better solution). I'd do the second part (with sever side combination) only if I would know that user will most probably build forms in multiple stages over a longer period of time and multiple client sessions. but can be used for failure preventions as well. Anyway. Javascript is your best bet with possible server-side interaction.
Preserving data between pages on the client
Be aware that it's also possible to preseve data between pages on the client side. Check sessvars library for this. So even if the page gets refreshed or redirected and then returned all this can be stored on the client side between these events like magic. Marvelous any rather tiny library that made my life several times. And lessened application complexity considerably that would otherwise have to be implemented with something more complex.
I used TaffyDB to store data, and it's just wonderfully easy to implement.
Hope this helps you
You may want to check out PersistJS, which exposes a cross-browser persistent storage object. Of course, being persistent, data stored with this library survives sessions, not just page changes.
The latest version (0.2.0) is here – note the version in the above linked post is 0.1.0.
A combination of #1 (although I'd use objects, not arrays necessarily) and #3 would seem like a good approach. Storing the data locally in the browser (#1) makes it immediately accessible. Backing that up with session-based server-side storage defends you from the page being refreshed; you can magically restore the page just as it was.

Categories

Resources