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.

Categories: All

5 Comments

Cindy · July 24, 2012 at 12:28 pm

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.

Abdel · September 4, 2012 at 4:14 am

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.

    Supal Dubey · September 4, 2012 at 4:22 am

    Hi Abdel –
    You can download the Jar from this link . I am using Java 7, I believe java 7 has the class in API.
    Also, please do not forget to set up the database, before you run.
    Regards,
    Supal

Manish Kumar · May 9, 2013 at 5:29 am

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.

    Supal Dubey · May 14, 2013 at 3:37 am

    Sure, would write a new post on Spring Security soon and will mail you the link! 🙂

Leave a Reply to Manish Kumar Cancel reply

Avatar placeholder

Your email address will not be published.