Saturday, September 17, 2016

Session timeout & Concurrent session control

Session timeout

An obvious mistake a user can make is forgetting to log out on a public computer, or if he’s unlucky – on a private device that is stolen at a later time. This alone is enough reason to invalidate a user session after a certain time, e.g. fifteen minutes. Another reason is that this also limits possibilities for smart hackers: especially in combination with other attacks like CSRF or click-jacking, session hijacking is a big risk. Moreover, if an account is important enough, physical break-ins to get to a device with a session that remains valid is not unimaginable. For these reasons it is also very important never to expose a session ID in a URL, but I’m getting off topic here …
Setting the timeout is easy, so this really is a quick win. In your web.xml, add the timeout to your session-config:
1<session-config>
2    <session-timeout>15</session-timeout>
3    <tracking-mode>COOKIE</tracking-mode>
4</session-config>
The tracking-mode plays no essential role here, but it is what we use in our app.

Concurrent session control

Concurrent session control for our use case amounts to controlling the number of sessions a user can have at the same time. Normally, each user has its own account, so it’s logical that a user can be logged in only once at a time. Since users might use different devices you might want to allow more than one session, but a maximum for the number of sessions is good practice.
Restricting the number of concurrent sessions will make sure accounts can no longer be shared between multiple or too many users. While not strictly security as I see it, this is also useful if you supply software with paid subscription accounts. For a security critical application, it is likely that if a user tries to log in a second time he or she forgot to log out the first time. In that case, it is a good idea to log out the user from the initial session, which is the approach we took.
We specified the timeout in the web.xml, which is handled by the servlet container (Tomcat in our case) – no Spring Security involved yet. However, to apply application logic to your sessions your application needs knowledge of the user sessions. You need to inject a session events listener in your web.xml:
1<listener>
2  <listener-class>org.springframework.security.web.session
3    .HttpSessionEventPublisher</listener-class>
4</listener>
The HttpSessionEventPublisher listens to the servlet container for sessions being created or destroyed and publishes corresponding Spring Security events. This will make sure that when a timeout triggers a session invalidation the application will know about it. We will manage session concurrency in the application, so this is critical. Also note that injecting this listener provides theSessionRegistry, which can now be @Autowired even if you have not defined it explicitly. TheSessionRegistry is a nice entry point to get information on the current logged in users, even if you’re not interested in concurrent session control.
Next is injecting a ConcurrentSessionControlAuthenticationStrategy. Using the security xml namespace makes this real easy. In your security configuration, add
1<beans:beans xmlns="http://www.springframework.org/schema/security" ... />
2<http>
3  <session-management>
4    <concurrency-control
5       max-sessions="1"
6       expired-url="/your-page-here" />
7  </session-management>
8</http>
Note that the element automatically registers a ConcurrentSessionFilter in the filter stack. Setmax-sessions="-1" in case you do not want to limit the number of sessions, but still would like a reference to the SessionRegistry as explained above.

Behaviour when Concurrent Sessions are exceeded

There are two possible ways to have your applications handle a login attempt that exceeds the allowed number. The default is that previous sessions are invalidated and if the user tries to use his initial session he will be redirected to “your-page-here”. This is probably best for most applications. The other option is to throw an exception after the login attempt and keep the former session(s) valid. To do that, add the attribute error-if-maximum-exceeded="true" to the <concurrency-control/>.

Warning: implement equals() and hashcode() on your UserDetails

Most applications implement their own user repository and UserDetails implementation. In that case, a warning is in order. Using some of the default Spring Security classes you get the following:ConcurrentSessionControlAuthenticationStrategy callsSessionRegistryImpl.getAllSessions() for the principal, which uses a Map from principal to sessions. The principal is a UserDetails instance, so if you implements UserDetails the equals() and hashcode() should be overridden. Otherwise, the strategy will not work.

Note on multi-node environments

The setup for concurrent session control up to now works perfectly for single node setups. However, if the web application is hosted on multiple servers you need to write your own implementation ofSessionRegistry to have a single session registry for all nodes. However, the current implementation of ConcurrentSessionControlAuthenticationStrategy expires the session object directly (which is a simply bean built by the registry to represent the session), instead of delegating this to the registry. So, until this is changed in Spring Security, you would also have to implement and inject your own SessionAuthenticationStrategy.

Sourcehttp://blog.trifork.com/2014/02/28/session-timeout-and-concurrent-session-control-with-spring-security-and-spring-mvc/

Monday, September 12, 2016

Adding external jar to Maven repository

I was facing problem in adding ojdbc.jar in to Maven.

Here is the solution that worked for me.
open cmd promt and execute the following command

mvn install:install-file -Dfile=C:\Users\lenovo\Downloads\ojdbc6.jar -DgroupId=com.oracle -DartifactId=ojdbc6.jar -Dversion=12 -Dpackaging=jar

Replace the path (marked in yellow with the exact path of your jar).

After the build, the jar will be added to the maven repository.

Dependency will be as below:

<dependency>
  <groupId>com.oracle</groupId>
  <artifactId>ojdbc6.jar</artifactId>
  <version>12</version>
</dependency>

Friday, September 9, 2016

-Dmaven.multiModuleProjectDirectory system propery is not set. Check $M2_HOME environment variable and mvn script match.

Solution:
Go to: Window--> Preference --> Java --> Installed JREs --> Edit In the edit Default VM arguments you need to put If you already set the maven home, for Windows machine:
-Dmaven.multiModuleProjectDirectory=M2_HOME
And for Linux and Mac OS X:
-Dmaven.multiModuleProjectDirectory=$M2_HOME
In case you are using Maven 3.x, the variable is named $MAVEN_HOME
-Dmaven.multiModuleProjectDirectory=$MAVEN_HOME

Sunday, September 4, 2016

LDAP - Apache Directory Studio: A Basic Tutorial

m2e-wtp error: /target/m2e-wtp/web-resources/META-INF/MANIFEST.MF (No such file or directory)

I have faced this error and the following details helped me in resolving the issue:

Eclipse versions earlier than Luna
I'm not certain if this is the best thing to do but I followed the instructions mentioned here with regards to getting rid of the auto generated web resources folder and this seems to also resolve the issue with the missing MANIFEST.MF:
  • on your project only : right-click on the project > Properties > Maven > WTP : check "Enable Project Specific Settings" and uncheck "Maven Archiver generates files under the build directory"
  • on the whole workspace : Window > Preferences > Maven > WTP : uncheck "Maven Archiver generates files under the build directory"
We actually generate our manifest entries as part of the maven-war-plugin when we actually want to package/build the project, but I dont think m2e-wtp uses this. In any event, the manifest file is irrelevant for us in the build that m2e-wtp creates for use within eclipse.
Eclipse Luna and later
For Eclipse Luna you have to go:
Preferences > Maven > Java EE Integration and uncheck "Maven Archiver generates files under the build directory".
Eclipse Luna does not have the path at project Properties and the WTP section.


source: http://stackoverflow.com/questions/14659891/m2e-wtp-error-path-target-m2e-wtp-web-resources-meta-inf-manifest-mf-no-such

Thursday, August 18, 2016

DriverManagerDataSource Vs BasicDataSource


When we develop a modern web application, we might have lot of REST services in a single page. Usually we face slow page loading in Local Development Environment.
But, The same page loads little faster in PRO because of its high configurations (For example its RAM size and such other things). In order to improve the
performance we have to change certain things in our local. One of the thing we found is Datasource connection pool configuration.  When we hit multiple REST service at a
time,all are handled as different request. If each request is a DB call, DriverManagerDataSource cannot perform well.
Since it can handle your multiple DB requests one by one, to load the entire page it will take comparitively much time in local env.  In spring’s documentation itself its given that
This class is not an actual connection pool; it does not actually pool Connections.  It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface,  but creating new Connections on every call
So we have to go for some other datasource which gives you Connection pooling mechanism.
One of such a datasource which gives you  a “real” connection pool outside of a JEE container is BasicDataSource.
And we did a small testcase in a heavy page page which has 4 REST calls and each have its own subsequent DAO calls.

Test Case DriverManagerDataSource(time taken to load the page ) BasicDataSource(time taken to load the page )
hit the page 128 seconds 37 seconds
Setting up Connection pool for BasicDataSource :
Lets get started with Maven dependency
1
2
3
4
5
<dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
</dependency>
  • This artifact is compatible with JAVA 6. If you are using Java 7 You have to use version 2.0 commons-dbcp
and the sample configuration in your bean.xml is
1
2
3
4
5
6
7
8
9
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
       <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
       <property name="url" value="jdbc:oracle:thin:@teoramon.bansel.it:1540:ORAMON"></property>
       <property name="username" value="SVIL_WKS"></property>
       <property name="password" value="wksc_123"></property>
       <property name="initialSize" value="25"></property>
       <property name="maxActive" value="50"></property>
       <property name="maxIdle" value="25"></property>
</bean>
Important Properties in Configuration
The following are the very basic properties
1.initialSize :
The initial number of connections that are created when the bean is initialized or the server is started. Default is zero.
2.maxActive:
The maximum number of active connections that can be handled at the same time. Default is 8. And you have to use maxTotal instead of  If you are using Java 7
3.maxIdle:
The maximum number of connections that can remain idle in the pool. Default is 8
 
Reference: https://mytechrepo.wordpress.com/2015/02/17/drivermanagerdatasource-vs-basicdatasource/

Saturday, July 25, 2015

Dirty Read,Phantom Read and Non Repeatable Read

Dirty Read:-
Dirty read occurs when one transaction is changing the record, and the other transaction can read this record before the first transaction has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid data.
Dirty Read Example:-
Transaction A begins.
UPDATE EMPLOYEE SET SALARY = 10000 WHERE EMP_ID= ‘123’;
Transaction B begins.
SELECT * FROM EMPLOYEE;
(Transaction B sees data which is updated by transaction A. But, those updates have not yet been committed.)
Non-Repeatable Read:-
Non Repeatable Reads happen when in a same transaction same query yields to a different result. This occurs when one transaction repeatedly retrieves the data, while a difference transactions alters the underlying data. This causes the different or non-repeatable results to be read by the first transaction.
Non-Repeatable Example:-
Transaction A begins.
SELECT * FROM EMPLOYEE WHERE EMP_ID= ‘123’;
Transaction B begins.
UPDATE EMPLOYEE SET SALARY = 20000 WHERE EMP_ID= ‘123’;
(Transaction B updates rows viewed by the transaction A before transaction A commits.) If Transaction A issues the same SELECT statement, the results will be different.
Phantom Read:-
Phantom read occurs where in a transaction execute same query more than once, and the second transaction result set includes rows that were not visible in the first result set. This is caused by another transaction inserting new rows between the execution of the two queries. This is similar to a non-repeatable read, except that the number of rows is changed either by insertion or by deletion.
Phantom Read Example:-
Transaction A begins.
SELECT * FROM EMPLOYEE WHERE SALARY > 10000 ;


Transaction B begins.
INSERT INTO EMPLOYEE (EMP_ID, FIRST_NAME, DEPT_ID, SALARY) VALUES (‘111′, ‘Jamie’, 10, 35000);
Transaction B inserts a row that would satisfy the query in Transaction A if it were issued again.



source: http://www.ongoinghelp.com/difference-between-dirty-read-non-repeatable-read-and-phantom-read-in-database/