Secure your business layer with Spring Security Annotation

In the last post we secured our business layer with JSR-250 annotation. Spring Security provides similar functionality. In this tutorial we will use @PreAuthorize annotation to secure our business model built earlier.

First change is in our where we move from @RolesAllowed to @PreAuthorize, one reason why you would need Spring Security annotation is JSR-250 doesn’t support expression language but Spring does, so if you want to add say a username comparison check it cannot be done using @RolesAllowed but with @PreAuthorize and @PostAuthorize you can.



 * The Class BusinessModel.
 * @author prabhat.jha
public class BusinessModel {
	 * Gets the business latest news.
	 * @return the business latest news
	public String getBusinessLatestNews(){
		return "Business is doing great!";

Next change is in jsfspring-sec-security-config.xml where instead of

<sec:global-method-security jsr250-annotations="enabled"></sec:global-method-security>

we will use

<sec:global-method-security pre-post-annotations="enabled"/>

<?xml version="1.0" encoding="UTF-8"?>
	 <sec:http auto-config="true" use-expressions="true">
		<sec:intercept-url pattern="/pages/secure/**" access="hasRole('ROLE_USER')" />
		<sec:intercept-url pattern="/pages/unsecure/**" access="permitAll"/>
		<sec:intercept-url pattern="/pages/common/**" access="permitAll"/>
		<sec:intercept-url pattern="/**" access="permitAll"/>
		<sec:form-login login-page="/pages/common/login.jsf"/>
		<sec:remember-me key="jsfspring-sec" services-ref="rememberMeServices"/>
	<sec:authentication-manager alias="authenticationManager">
		<sec:authentication-provider ref="rememberMeAuthenticationProvider"></sec:authentication-provider>
		<sec:authentication-provider user-service-ref="customjdbcUserService">
			<sec:password-encoder ref="passwordEncoder">
	<sec:global-method-security pre-post-annotations="enabled"/>

That’s the only change we have to do in order to move from JSR-250 to Spring Annotation.

There is one comment

  1. Spyros Non Serviam

    Why am I getting a NullPointerException when I check the remember me button?
    Also I am getting an access denied when I try logout after I was logged in as Guest.
    Can you please help me fix them?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s