Sunday, October 11, 2015

Spring Security Expression: Secure URL Dynamically According to Users and Permissions.


Today's we discuss about for securing URL using Spring-Security-Expression at Run Time in Application. Using ACL security we can set URL and permissions like read-write permissions per user but some time we just secure URL, there is no issue with Read and Write permission. That time, there is no need for using ACL security, because ACL have some complexity for implementation. But with the Spring-Security-Expression handler, we can easily secure urls by calling custom functions.

Step 1:

Create tables for User and UserPermssion as below: 
CREATE TABLE `users` (
  `id` bigint(20) NOT NULL,
  `name` varchar(45) DEFAULT NULL,
  `role` varchar(45) DEFAULT NULL,
  `email` varchar(256) DEFAULT NULL,
  `password` varchar(256) DEFAULT NULL,
  PRIMARY KEY (`id`)

CREATE TABLE `users_permissions` (
  `id` varchar(100) NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `url` varchar(300) NOT NULL,
  `permission` enum('ACCESS','DENIED') NOT NULL,
  PRIMARY KEY (`user_id`,`url`),
  KEY `fk_users_permissions_1_idx` (`user_id`),
  CONSTRAINT `fk_users_permissions_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE

You can also import sample data from SQL script using this link.

Step 2:

We are using Spring Java Based configuration. Our first requirement is to enable Spring-Security-Expression in our Application using following code in our security configuration file:


Step 3:

 Create your custom bean for checking user security permission using database. This can contain method for validate permission and this method is used for Spring-Security-Expression. Following is our bean code:
public class SecruityServiceImpl {

 private UserPermissionRepo userPermissionRepo;
 public boolean userHasPermissionForURL(final Authentication auth, String url) {
  User user = (User) auth.getPrincipal();
  List permissions = userPermissionRepo.findByUserAndUrlAndPermission(user, url, CommonEnum.PERMSSION.ACCESS.getPermission());
  return (permissions != null && !permissions.isEmpty())? true: false;

Step 4:

Secure our Spring-MVC controller methods using Spring-Security-Expression.  In the following code, we are using @PreAuthorize annotation for validate our expression.

@RequestMapping(value="/section-one", method=RequestMethod.GET)
@PreAuthorize(value="@securityService.userHasPermissionForURL(authentication, '/section-one')")
public String sectionOne() {"In sectionOne Controller method");
 return "user/section-one";

Step 5:

 We can also secure our URL in user interface. The Spring-Security-Expression hide the link if user have not permission to access the URL. We are using thymeleaf for Spring-Security so, thymeleaf also provide some attribute. We can also use Spring-Security JSTL tag in JSP. For Thymeleaf following is the code.

sec:authorize="@securityService.userHasPermissionForURL(authentication, '/section-one')"

For download a complete code of sample application  access this link.



Monday, May 25, 2015

Scala Oauth 2.0 using Play-Framework 2.3.x with ReactiveMongo

In this post, we are using Oauth2.0 for creating API with Play-Framework 2.3.x , ReactiveMongo-Extensions, Cake-Pattern and Scala-Oauth2-Provider. We are using Oauth-2.0 just for secure my web-serivces using token based Authentication. This sample Oauth application similar behave like Spring-Security-Oauth2.0 for token based authentication. Click here for more detail...

Play-Framework 2.3.x Dynamic Authorization Using Deadbolt-2

In this post, we are using Deadbolt-2 for maintaining dynamic Authorization using Play-Framework 2.3.x, H2 Database and ReactiveMongo-Extensions. We are using Deadbolt-2 for secure our controllers with dynamic authorization. The Deadbolt-2.3.2 version not supported reactivemongo, so we maintain permission using JDBC and rest of data maintain in Mongodb using ReactiveMongo. Our RDBMS tables structure and sample data are declared in conf/evolutions/default director. Click on this link, for more detail....

Saturday, January 24, 2015

Depedencies Injection In Play-Framework 2.2.x Version Using Spring


Hello Friends, today we discuss about "How we use Dependencies Injection With Play-Framework Using JAVA". There are so many languages who have its own framework for developing web application easily and effectively like PHP have Cake-PHP, Zend etc or Python have its DJango etc. These web framework build a good web application easily and quickly, because the major thing is that there is not need to configure application manually, these frameworks are help the developers to create a basic web application struture with couple of seconds and easily customizable. These are Open-Source framework. But still java had not any open-source web framework for build reliable and scalable web-application. 


Now the day's Typesafe launches a Play-Framework for build a "Reactive" application using Java or Scala. Play 1.x build using Java but 2.x build with Scala, The Scala is a hybrid lanugage which have so features and Play uses these features for better performance. For more information about Play click on this link.
Now the day's Reactive Programming is the part of developement. Play is a reactive and follow reacive principles as below: 
  • Responsive
  • Resilient
  • Elastic
  • Message Driven
For basics understanding of reactive go to Reactive Manifesto

Play-Framework have so many features for build a reliable, scalable web applications easily, But the main limitation i feel in the Play-Framework is, the Play does not have its own dependency injection management. Most of the Java developers are habitual with Dependencies Injection because using new in our code is a bad practices. Play-Framework is a scalable, we easily scale our web application with play framework and for dependencies injection we are using third party plug-ins for Dependency Management like Spring, Google Guice etc.

We are trying to integrate Spring Dependency Injection with Play-Framework as below. Our requirements as below:                                                       

  • Download Play Framework
  • Install Java 1.6 or above
  • Eclipse IDE or other Rich Editor

Step 1:

Download the project from Github . Still Play have support for IDE, but some of the Java web developers found the different way for deploy application with play framework. Because for spring we are using tomcat and integrate tomcat with IDE easily and run the application. Play have its own server and we are using command line for run the server and create the application. With IDE we are write our code with rich environment and also debug the application. But still there is dependency of command line. 

NOTE: We are using Play-Framework 2.2 version and we hope in Play-Framework 3.x have its own dependency injection management module.

Step 2:

Download spring depedencies as below: 

 "org.springframework" % "spring-context" % "4.1.3.RELEASE"

NOTE: Play using Scala-Built Tool for build the application and dependencies management. 

Step 3:

For add spring dependencies configuration, we need to create a Global class at the root package and Inherit GlobalSettings class for override some default configurations settings for application. The Global class define some global configurations for application.

NOTE: One application have one Global Class. If we change the class name Global class to another name or change the Package of Global class, the application pick its default configuration because application search global settings class with Global name and on root package.

public class Global extends GlobalSettings{

	private Logger logger = null;	
	private final AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
	public Global() {
		logger = Logger.getLogger("GlobalConfiguration");
	public void onStart(Application app) {
		super.onStart(app);"ON START");
		// This will construct the beans and call any construction lifecycle methods e.g. @PostConstruct
	public void onStop(Application app) {
	public  A getControllerInstance(Class clazz) throws Exception {"getControllerInstance");
		return applicationContext.getBean(clazz);