ExtJs:How to get Session variable - extjs4

In my Java web application,when a user gets logged in,i store the user name and other details in session as follows,
session.setAttribute("userName",username);
I am using ExtJs4 for UI.How to get the session variables in extJs?
Thanks

I can second #Geronimo approach. You need to get user Id and/or permissions when you authenticate the user. However...
You can't rely just on the username/permissions that you store somewhere in your JS code because it can't be easily spoofed. If you present user with some information that can be different for different levels of access you still need to do server side validation of the user identity.

You can't get session variables off the server web container using javascript only.
I do the same thing (storing userId as a session variable in java). I use Ext.Request to perform an Ajax request to a java servlet to get it (along with other data about the user like permission settings for the webapp to enable or disable features they wouldn't be able to use).
EDIT:
I second sha's answer also, the only reason I pass the authentication information back to the client is for cosmetic reasons - so that user doesn't think he can use a feature in javascript that would be denied by my server side authentication. If he were to spoof the userId or permissions and try to use the feature, the real authentication on the server side would stop him.

I understand that the question has been asked for a long time ago, but despite the large number of views and the absence of an plain answer, I decided to offer this answer:
Assume that the session variable is registered like /index.php?PHPSESSID=9ebca8bd62c830d3e79272b4f585ff8f
In this case, you can get the variable PHPSESSID through JS object "location" and transform it through Ext.Object.fromQueryString()
So:
console.log( Ext.Object.fromQueryString( location.search ) );
will prepare PHPSESSID variable for your needs.

Related

Shopify app access token - how to make it more secure?

When store owner installs my app I save access tokens into database for later use. Having access tokens from store is huge security responsibility because anybody with these tokens can modify stores from any domain/address, there is no ip or domain lock.
What method could I use to make this more secure? I was thinking to save tokens offline and then upload it only when needed (in case I need to make some global updates for all stores), then delete it again. In case when merchant access app configuration within admin, I would just save it into session. Is there any better method?
Good question.
I save them in a database as well but I encode them with a separate key from the Shopify App password. That way even if someone have access to the database because of some backdoor entrance he won't be able to use them. That said if someone have access to the code he will be able to figure out how to decrypt it since he will have access to the key.
That said I make sure that each and every request is authenticated before I show any response from the server. Since I'm using NodeJS as the back-end I make sure that there are no global variables that can be accessed or modified from different stores. Everything is neatly scoped in separated functions so that the session is scoped for the current store and no other ones will be able to dirty the other store session.
In addition I make sure that there is a webhook that fires when the client uninstall his app in order to clear my database from any information regrading his store.
I know some people are using sessions for this ( online method ) but they pose other problems that I didn't like so I stuck with a database ( offline ) since that is the quicker way to access the App instead of multiply redirects in order to save the session.
As for proposals I can give you a few tips that I learn on my way while building a few basic Apps. ( I'm not an expert on the subject by any means )
don't rely on any cookies when it comes to sensible information
authenticate every request that comes from the front-end
don't trust the user and validate any input that comes from the front-end
don't over-complicate your setup, while it's good to have high security it's bad if it makes your app slow for the user and you lose customers
look to other ready to use popular solutions that can guide you to the correct path
don't get greedy with the App scopes, only request the scopes that you need for you app
remember to clean up after yourself when it's possible but don't over do it ( too many Apps modify the code of customers and break it only to prevent any way to clean it afterwards ) Example use the ScriptTag API instead of a liquid snippet using the Asset API. If you have to use the Asset API add only the parts that you know that won't break a site. Creating a variable is ok if you are using var if the site supports IE11 creating a variable using const or let is not OK or using vanilla JS is OK but using jQuery without knowing for sure that the site has it installed globally is not OK.
More insights on the matter can be seen here:
https://help.shopify.com/en/api/getting-started/authentication/oauth/api-access-modes
https://community.shopify.com/c/Shopify-APIs-SDKs/Best-way-to-store-shops-that-have-installed-my-app-and-their/m-p/402972

How are logged-in users remembered? (Using Pyramid and in general)

Main question:
Take your typical web application with login. Does it use a database to keep track of what users are currently logged in? (As opposed to remembering all users. I'm sure you need a database for that.)
I'm just starting to learn web development, and was wondering about the real-world way to remember users as logged in, as compared to simulated examples as on this Pyramid cookbook page. I could not yet find anything about the Pyramid-way of doing this, not by searching nor in the authentication-specific tutorials. Some tutorial compare the userid against a hard-coded list, others against a not-further-specified database. The question above is my guess after reading this post on correct practices of user authentication:
If you are unfamiliar with session data, here's how it works: A single randomly-generated string is stored in an expiring cookie and used to reference a collection of data - the session data - which is stored on the server. If you are using an MVC framework, this is undoubtedly handled already.
It would be cool if someone could clear this up!
Somewhat related: This question, about the same Pyramid example - it asks how secure the method is, while my question is about understanding the method.
...and was wondering about the real-world way to remember users as
logged in.
It's not the server (or not only the server) who needs to "remember the user as logged in", it's also the client who needs to remember.
Conceptually, it works like this: upon verifying the login credentials the server returns something which the client remembers. The client then needs to send that something with every request to the server. The server, on every request, checks that the provided value is correct, matches a user in the database, etc.
In a web application, the usual mechanism to store and automatically send that "key" to the server is via HTTP Cookies - basically, the server sends a Set-Cookie header and the browser stores the cookie and sends it back in the Cookie header on every request.
Regarding the actual payload of the cookie, there are two common approaches. One option is that upon login the server starts a "session" (which may be a row in some database table). The server then returns the ID of the session, which is a random unguessable string, to the client. To check that the particular session is active the server would need to consult the database on every request.
Another option, commonly used in Pyramid tutorials, is auth_tkt authentication: the server returns a cookie containing the actual user ID, cryptographically signed with a server-side secret. When the client sends the cookie back, the server can verify the signature and be sure the cookie hasn't been tampered with. In this case, there's nothing on the server side to keep track of "all logged in users" and no need to consult the session database.

SailsJS secure authentication

I am building app using SailsJS as backend and angular as frontend. On many websites I have found that auth is done by setting req.session.userID to som value but then in policy it only performs basic check like if(req.session.userID) but I am not sure that this is secure. What if I put some random string to my cookie named userID will system consider this as valid login?
For example my correct userID is ABCDEF but what if some attacker come by and he sets his cookie userID to DEFGH. Will system consider this as valid login? I don't think that there is some background validation against database going on. Wouldn't it be better to create model called Sessions which will store randomly generated session ID and associated userID? Then the system at user login would generate random sessionID which will be stored in DB and in policy system will check if currently set req.session.sessionID is valid.
I am asking this because I don't have very deep understanding of sails but from my point of view solution proposed in documentation doesn't seem secure.
I recommend that you take a look at JWT and how it solves some problems. Then another problem will be "how to store this token". And that you can solve with cookies, local storage, etc. all depending on your needs and possibilities. Usually a local storage + middleware in the client side with reddis on the server side (advanced session behavior) is enough.

Is session a good choice?

We are building ASP.NET MVC app that is supposed to manage sport objects reservations (tennis courts, squash courts etc).
Users are not supposed to act only in scope of one club at the moment of interaction with app.
Navigation to the app should be like:
appname.com/clubName or
clubName.appname.com
Questions:
1. What would be the best way to persist the data about selected club. We have implemented storing in session (injecting information about the club durint app opening), but we read that using session is rather deprecated solution. We are using ApiController so in order to get the session we had to hack the routing (registering custom RouteHandler). Is session mechanism applicable for this problem?
var session = HttpContext.Current.Session;
if (session != null)
{
service.ClubName = session[CustomSessionKeys.ClubName.ToString()].ToString();
}
Is it good idea to use subdomains for our problem?
Many thanks in advance :)
Generally a web api works differently than a normal mvc app.
In an MVC application you would use a session cookie to make the internet act like a state machine. However, this is not what is generally done for web api's. In a web api, you provide some form of authentication (e.g. via the header authentication field).
But within a request you ofcourse want to to keep track of the current user, or in asp.net terms, the current principal.
We set the principle though a Delegation handler
HttpContext.Current.User = user;
If you want some more code on how this whole authentication is done, just let me know.
This was all serverside ofcourse, on the client side, you can keep any information you want in a session store. Although you might want to consider using the local storage in stead (depending on what semantics you want to give it). They both work in the same way.
You can consult W3C webstorage specification for the complete information on both of these.
Well you have many choices I guess!
Go with the route thing as you suggested, where you keep the club Id or name as part of the URL. I would go for this if I need the link to give more meaning to the user.
Cookie! yes, if the information is not sensitive store it in a cookie. In case this cookie is only to be accessed from server side, then don't forget to make it HttpOnly
Session. I agree with you, I wouldn't choose session unless the data was very sensitive and I needed to make it secure.

GWT: Authentication for some part of application using GWT login page

My application has some features that are accessible to all users, and some other features to which access should be restricted to authenticated users only. All these restricted features exists within some set of GWT Places, thus, all Places available in application can be divided into two groups: "accessible for all", and "restricted". In my opinion, places with restricted access, could implement some interface (let's say it would be RestrictedAccess), and if user proceeds to one of them, and it has not been authenticated yet, it will be redirected to the login screen - it's more OO-approach than applying filters basis on URL.
What I'm trying to achieve is:
Information about if user has been
authenticated or not should be
stored on server (it's not something
that could be stored in a cookie...)
Login page is a standard GWT place+view+activity (!)
User name & password validation is done on the server side.
So far, I've introduced RestrictedAccess interface, which is implemented by some set of places. My FilteredActivityMapper.Filter implementation, which is passed to the FilteredActivityMapper wrapping application activity mapper has the following logic:
Place filter(Place place) {
if (place instanceof RestrictedAccess && !userHasBeenAuthenticated()) {
return new LoginPlace();
}
// return the original place - user has been already authenticated or
// place is accesible for all users
return place;
}
private boolean userHasBeenAuthenticated() {
// remote call - how to do ???
}
The problem is with userHasBeenAuthenticated() method (user should not be redirected to the LoginPlace, if it has been already authenticated). If I want to store this information on the server-side, I have to do GWT RPC/request factory call here, but both are asynchronous, so I cannot work on its result in the filter method.
I know that I can use web.xml filters or some external framework (e.g. spring security), but none of this approach allows me to have login page as a standard GWT - based form, or indicating in the more OO way that access to some place should be restricted.
Thanks in advance for any hints
EDIT: I've started to wondering if places filtering (restricted/not restricted) should take place on the client side at all. If, as it was suggested, there is a possibility to hack code indicating if user has been authenticated or not, there is also possibility to hack places filtering code, so that it will be possible to access restricted places without signing in.
Piotrek,
I think there is a security issue with calling userHasBeenAuthenticated() - it would be possible to hack the client side code to return true every time this function is called.
The solution I've implemented is to simply return SC_UNAUTHORIZED if an unauthenticated user attempts to access any remote service. I've overridden the RequestFactory onResponseReceived function which redirects to a login page if the response is SC_UNAUTHORIZED. Idea taken from:
http://code.google.com/p/google-web-toolkit/source/browse/trunk/samples/expenses/src/main/java/com/google/gwt/sample/gaerequest/client/GaeAuthRequestTransport.java
This works for our situation where the Activities and Places are all data-centric - each place change retrieves data from the server. If a user isn't authenticated they simply don't get the data and get redirected to a login page.
I realize your situation is slightly different in that some places are accessible to everyone, in which case you could configure only the restricted services to return SC_UNAUTHORIZED.
I have a similar application with the same requirements. As yet I have not got round to to the implementation but I was thinking along the same lines.
What I was planning on doing is storing the authentication state client side in an AuthenticationManager class. When the app starts I was going to request the login info from the server (I was thinking of running on app engine so I would get the authentication state and also get the open id login/logout URLs) and store this in the AuthenticationManager. Acegi/Spring Security works in a simlar way so this info is available server side if you use those too.
When the user logs in/out they will be redirected by the server and the new state will be retrieved. This should keep the client authentication state in line with the server. Each RPC request on the server has to be checked for authentication too. I was using the gwt-dispacth library and this has some rudimentary authentication checking and cross site script protection in in too (although I think latest GWT has this for generic RPC).
One issue is session timeouts. Again the gwt-dispath library has some code that detects this and returns session expired exceptions to the client which can be intercepted and the auth manager updated.
Hope that makes some sense.