Extjs 4 Session Management - session

I am having web based application in which user session has to be managed management.
In app.js I have used launch config as :
launch: function(){
Ext.create('myproject.view.LoginForm')
}
LoginForm : will show log in dialog and invoke login controller for communicating with server for authenticating the credentials provided by the user.
So when ever user refreshes the page Extjs is asking for log in that is because of I am not checking the session in here, How should be the session details stored in Extjs client and check to avoid prompting the log in unless user has log-out ? and How to manage user session ?

User identity and session information must be stored server side. Typically a cookie is set once the user authenticates successfully so as not to prompt the user again. This cookie is sent from the server and is stored in the browser automatically and sent back to the server for inspection on page refresh. Server should validate the cookie if OK allow user to proceed.
Per #existdissolve comments below
In your launch method, simply run a a session check before you create the login form. Whether this is cookie checking or a request directly to the server, the result of the session check can then trigger the creation of the login form, or whatever other logic you have for creating the rest of the application

Session Management can be done using
Inside login controller
// Storing user details in session / cookies
Ext.util.Cookies.set("key", value);
On logout button
// remove user details from cookies
Ext.util.Cookies.set("key", value);
In App.js
autoCreateViewport: false,
launch: function(){
var key= Ext.util.Cookies.get("key");
if (key=== undefined || key== 'null' || key== null || key.length <= 0){
// load login UI as user is not logged in
Ext.create('app.view.LoginForm');
}
else {
// load main UI as user is already logged in
Ext.create("app.view.Viewport");
}
}

Related

Is it safe for a client to ask the server if the user is logged in using AJAX?

I want my system to display a "session expired" message if the user was idle.
What security risks am I facing if I make an AJAX call each T seconds/minutes to an API endpoint which checks if the user is authenticated or not?
/// <summary>
/// Used to check if the user was idle and the session expired.
/// </summary>
[Authorize]
public class IdleController : ApiController
{
/// <summary>
/// Used by the system to check if the session expired while the user was idle.
/// If the user is not logged in anymore because of a terminated session, the AuthorizeAttribute will not pass the request to this method.
/// An HTTP 401 response will be returned, indicating the expiration of the session.
/// If the session is still active an HTTP 200 will be returned with a null value response.
/// </summary>
/// <returns>Always null.</returns>
public object GetCheck()
{
return null;
}
}
var idleTimeout;
function StartIdleCheckTimeout()
{
idleTimeout = setTimeout(CheckIdle, 60000);
}
function CheckIdle()
{
$.ajax("Api/Idle/Check", {
statusCode: {
200: ResetIdleCheckTimeout,
401: OnUserIdle
}
});
}
function ResetIdleCheckTimeout()
{
clearTimeout(idleTimeout);
StartIdleCheckTimeout();
}
function OnUserIdle()
{
alert("Su sesiĆ³n ha expirado. Por favor ingresa nuevamente.");
RedirectTo("/");
}
Thanks in advance,
Shy.
I don't think you have any security risks except usual ones for web. But you will have a lot of headache with async requests in js, it's a bit tricky to handle correctly such requests when you have to use them instead of permanent connections.
There is no serious security risk about that. One of the most important things about those kind of stuff is storing sensitive information on server-side session. When you need to access one of those information, such as logged-in timestamp, you need to access this through session ID.
The risk is that your AJAX request will act as a "keep alive", so the session will never expire if your site is open in the browser and internet connectivity is active.
This could mean that the security timeout of your application would no-longer protect against local attackers accessing a user's unlocked machine (whether this is a problem in your target environments is for you to decide).
You could time the session client-side though, and call your logout handler should the user not move the mouse or press the keyboard on your app for a certain amount of time. This however increases complexity, which tends to reduce security.
Note that Forms Authentication by default does not expire session server-side upon logout.
Calling the SignOut method only removes the forms authentication cookie. The Web server does not store valid and expired authentication tickets for later comparison. This makes your site vulnerable to a replay attack if a malicious user obtains a valid forms authentication cookie. To improve security when using a forms authentication cookie, you should do the following:
Use absolute expiration for forms authentication cookies by setting the SlidingExpiration property to false. This limits the window in which a hijacked cookie can be replayed.
Only issue and accept authentication cookies over Secure Sockets Layer (SSL), by setting the RequireSSL property to true and by running the entire Web site under SSL. Setting the RequireSSL property to true ensures that ASP.NET will never send an authentication cookie to the browser over a non-SSL connection; however, the client might not honor the secure setting on the cookie. This means the client might send the forms authentication cookie over a non-SSL connection, thus leaving it vulnerable to hijack. You can prevent a client from sending the forms authentication cookie in the clear by running the entire Web site under SSL.
Use persistent storage on the server to record when a user logs out of the Web site, and then use an application event such as PostAuthenticateRequest event to determine whether the current user was authenticated with forms authentication. If the user was authenticated with forms authentication, and if the information in persistent storage indicates the user is logged out, immediately clear the authentication cookie and redirect the browser back to the login page. After a successful login, update storage to reflect that the user is logged in. When you use this method, your application must track the logged-in status of the user, and must force idle users to log out.
Therefore you should implement these recommendations in order to increase security.

Oracle authentication not working?

I implemented a LogOut button which logouts user from webpage. Server is Oracle HTTP server.
When clicked on LogOut it executes below procedure
PROCEDURE log_me_off IS
BEGIN
-- Open the HTTP header
owa_util.mime_header('text/html', FALSE, NULL);
-- Send a cookie to logout
owa_cookie.send('WDB_GATEWAY_LOGOUT', 'YES', path=>'/');
-- Close the HTTP header
owa_util.http_header_close;
-- Generate the page
htp.p('
<head>
<script type = "text/javascript" >
history.pushState(null, null, ''xna_hpms_ui.log_me_off'');
window.addEventListener(''popstate'', function(event) {
history.pushState(null, null, ''xna_hpms_ui.log_me_off'');
});
</script>
</head>
You have been logged off from the WEBSITE');
htp.anchor( 'http://www.google.com', 'click here to login a');
htp.p('<BR>bye');
END;
END;
/
Document I referred: https://docs.oracle.com/cd/B13789_01/server.101/b12303/secure.htm
Problem:
In Chrome, when i click on the Log Off button it Log Outs the user and after that when user try to refresh or try to open webpage in new tab a prompt appears asking for the login credentials, if the user clicks Cancel and Refresh the tab he automatically gets logged in. While this behavior is not in IE.
When there are many tabs open and user clicks Log Off button he gets logout from the current page while when navigate to other tab if he clicks anywhere he again asked by webpage to enter credentials while if he clicks Cancel and Refreshes the page he again got logged on without entering credentials.
Kindly Help
I recommend using Custom OWA and your own cookie as a means of authenticating users. Set up the DAD to authorize the schema using custom_owa. Then create the custom_owa.authorize package/function in your schema.
The custom_owa.authorize function will be called before each page is accessed. If it returns true the request is granted. If false, the request is denied.
This give you complete control over who can access what. So what you do is set your own cookie when someone logs into your website. Then in custom_owa.authorize check the cookie and return true or false accordingly.
When someone logs off, destroy the cookie or expire it.

Why doesn't the login session "stick" when login in using "ionic serve" window but works when I point the browser to the www folder?

I am using Ionic to build a login system on top of Codeigniter/Ion_Auth/codeigniter-restclient and when I try to login from "ionic server" the login works but the next api request to the logged_in() method returns false.
The same thing works properly when I point the browser to the www folder.
So here is the problem step by step:
run ionic serve
you see the login form (http://localhost:8100/#/app/login)
enter email and pass
the rest api returns "login successful"
$state.go('app.profile') works and redirects to http://localhost:8100/#/app/profile
REST get api/logged_in returns false and I redirect to the login page
If I do the same in a regular browser, step 1 becomes: open browser and go to http://localhost:8888/App/www/#/app/login, at step 6 REST get api/logged_in returns true and I don't get redirected to the login page, I stay on the profile page.
The code is the same. So my guess is that maybe ion_auth doesn't get the cookies it wants or the session is reseted. I am not sure at this point what the problem is. This is my first Ionic/App project so I might be missing something about the proper way to authenticate from a mobile app using code that works in browsers
Thank you
UPDATE:
It seems that when using the 'ionic server' window every request to the API triggers a new session. The new session is stored in the database and ion_auth tests the logged_in against that last one, which doesn't contain the login details.
you were taking about REST api and cookies and sessions. Cookies and sessions don't go with REST philosophy. Here is why.
Let me tell you how we accomplish this problem in our project. Basic way of knowing which user is requesting and if it has the access rights is by the 'Authorization' header value. You can use Basic Authentication, Barer or any other.
We generally prefer token based authorisation system. When a login is successful, server sends a token. In ionic app, we save it using a factory called SessionService. So whenever user logs in, token is stored and is used for every request. But token would be lost if user closes the app. So we can store it in local storage. User can then be directly redirected to dashboard until user logs out.
app.factory("SessionService", function($window){
var user={};
if ($window.localStorage['user']!=undefined){
user=JSON.parse($window.localStorage['user']);
console.log(user);
}
return{
isLoggedIn:function(){
return !isEmpty(user);
},
logout:function(){
console.log("logout")
user={};
$window.localStorage.clear();
},
setUser:function(data){
user=data;
$window.localStorage['user']= JSON.stringify(user);
},
getUser:function(){
return user;
}
}
})
Now in every web request, you can call SessionService.getUser().token when setting value Authorization header.
UPDATE:
Despite using cookies is not recommended, you can use it in your application easily.
If you are sending request with CORS, angular doesn't sends cookies with request.
One of the way address this issue is to send withCredentials: true with every request:
$http({withCredentials: true, ...}).get(...)
Read further about this here.
Hope this helps!

How are sessions maintained after login authentication?

After the username password login form is submitted (presumably with some kind of encryption through https) how does the server maintain the information that the user is logged in?
The user submits the login form and the server authenticates the user and returns a page. But when the user clicks on a link on that page how does the server know the request it is receiving is coming from someone who is authenticated and therefore the server knows its safe to send the html for that new page.
The act of logging on will usually result in the browser getting a session cookie passed back. It's this cookie that the server uses to identify which session (if any) belongs to the user.
If cookies are disabled on the clients browser, most web programming frameworks will cope by sticking a session ID onto the URL.
the username and some flag like is_logged are stored in the session.
on any page you should check those variables from the current session.
on logout you clean the session or destroy it, thus your protected page is in accessible.
good luck
Arman

Ajax Authentication Response

I have a login form that I am considering if it should be 'ajax'ed or not.
The reason I am contemplating this is because if the response of the ajax call is fixed (like 0 for invalid and 1 for valid) I can redirect the ajax request through the javascript console and log into the system maliciously.
Is there a way to solve this security issue?
Is that why all login forms I've seen so far (including here on stackoverflow) are non-ajax?
You need to make sure that all content which should be displayed only to logged-in users should only be transferred after the login process. The server-side should check on every request whether the user is logged in or not. This could be done by traditional methods (like session ids in cookie or post/get).
So in short: don't transfer fixed values but transfer a normal session id which vary from user to user.
You perform your login with ajax.
Server side validates the login and starts a session.
Even if the client ignores the response from the ajax call, it's important that any ajax calls check if the session was properly created when login, and refuse to do what's asked if the session wasn't properly opened at login time.
In PHP (example):
Login:
<?php
header('Content-type: text/json');
session_start();
if ( check_password() ) {
// send ok response
}
else {
// send not ok response
}
// if that session variable exists, then we logged in successfully
$_SESSION['user'] = $user;
other ajax calls :
<?php
header('Content-type: text/json');
session_start();
if ( ! isset($_SESSION['user'] )) {
// send not ok response
// on the client, this will redirect to the login page
exit;
}
$user=$_SESSION['user'];
... rest of the code here
For every ajax call, when the response arrives, you should first check if the response is ok -- up to you to determine how you want this represented.
As an example, a response might look in JSON like
not logged : { "ok":"N","error":"not logged in"}
logged : { "ok":"Y","data":[{"name":"xxxx","age":19},{"name":"yyy","age":91}]}
or { "ok":"Y","data":"Some text"}
etc, etc...
If it's ok, you proceed to handle the response. If not, you can for example redirect to the login page.
Note that with PHP, every ajax call you make includes the session ID automatically (it's a cookie), so PHP knows which session is associated with a particular request.

Resources