AllSpring

Spring MVC + Spring Security + Hibernate Project

In this post, we would be creating a project with Spring MVC, Spring Security & hibernate. This can be very handy in case you need to jump start new development / PoC.
Download and place all these Jars in your library.


Lets quickly look at Spring security & Spring hibernate configuration –

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.roadtobe.supaldubey.examples.spring.domain</value>
</list>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>

Here is our Security configuration –

<!-- To allow standards-based @Secured annotation, enable secured-annotations
See Spring Security 3.1 Reference 2.4 Method Security
- http://static.springsource.org/spring-security/site/docs/3.1.x/reference/ns-config.html#ns-protect-pointcut
- http://static.springsource.org/spring-security/site/docs/3.1.x/reference/appendix-namespace.html#d0e8651
See Spring Security 3.1 Referecne 15.1.1 Common Built-In Expressions
- http://static.springsource.org/spring-security/site/docs/3.1.x/reference/el-access.html -->
<security:global-method-security jsr250-annotations="enabled" />
<!-- This is where we configure Spring-Security  -->
<security:http auto-config="true" use-expressions="true"  >
</security:http>
<bean id="sampleAuthenticationProvider"  class="com.roadtobe.supaldubey.examples.spring.security.SampleAuthProvider"  />
<!-- Declare an authentication-manager  -->
<security:authentication-manager>
<security:authentication-provider ref="sampleAuthenticationProvider" />
</security:authentication-manager>
</beans>

Below is our SampleAuthProvider for authentication as configured in our security configuration above

public class SampleAuthProvider implements AuthenticationProvider
{
@Override
public boolean supports(Class<? extends Object> authentication)
{
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
private static Map<String, String> SIMPLE_USERS = new HashMap<String, String>(2);
private static List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
static
{
SIMPLE_USERS.put("supaldubey", "roadtobe");
SIMPLE_USERS.put("supal", "roadtobe");
AUTHORITIES.add(new SimpleGrantedAuthority("ROLE_ADD"));
}
@Override
public Authentication authenticate(Authentication auth)
{
if (SIMPLE_USERS.containsKey(auth.getPrincipal())
&& SIMPLE_USERS.get(auth.getPrincipal()).equals(auth.getCredentials()))
{
return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(),
AUTHORITIES);
}
throw new BadCredentialsException("Username/Password does not match for "
+ auth.getPrincipal());
}
}

To use Spring security, annotate your controller as below –

@RequestMapping("/hi")
@RolesAllowed("ROLE_ADD")
public ModelAndView hi(Model model)
{
model.addAttribute("test", "Supal Dubey");
EntityImpl im = new EntityImpl();
im.setFirstname("Supal Dubey");
im.setStatus("ACTIVE");
entityService.save(im);
return new ModelAndView("index");
}

This will only allow users having the role ROLE_ADD to execute the method or access the URL. In case user is not logged in he will be redirected to Spring controller Login page and will be prompted for authentication.
Roles can be granted to users by using SimpleGrantedAuthority(“ROLE_ADD”) class, it is implementation of GrantedAuthority interface, its previous kin GrantedAuthorityImpl is now deprecated by Spring.
To use hibernate code in your project simply use the prototype service

@Override
@Transactional
public void save(EntityImpl imp)
{
sessionFactory.getCurrentSession().save(imp);
}

The transactional annotation makes the method a transaction. While, SessionFactory is injected into the service via Spring.
Rest of the code is self explanatory and is in line with my previous posts on Spring configurations.
Download the project from here .
Do post a comment in case you face any issues or have any questions.

5 thoughts on “Spring MVC + Spring Security + Hibernate Project

  1. You can definitely see your enthusiasm in the paintings you write. The sector hopes for even more passionate writers like you who aren’t afraid to say how they believe. All the time go after your heart.

  2. Hi,
    I imported this project to eclipse, in BaseController.java there is an error in this line :
    import javax.annotation.security.RolesAllowed;
    the error says :
    The import javax.annotation.security cannot be resolved
    Please your help is appreciated.

  3. Hi i am a new in Spring Security, so can you please explain the why all these classes are used individually, so that we can learn more about it.

Leave a Reply

Your email address will not be published. Required fields are marked *