Spring Method Security with @PreAuthorize and @Secured

Spring framework has made securing your application so much easy that you only need to use some basic configurations CORRECTLY, and that’s it !! This security can be applied to multiple levels in your web application. Spring’s basic support is for these levels:

  • URL level security
  • Method level security
  • Entity or Object level security

In this Spring security tutorial, learn to apply method security using annotations such as @PreAuthorize and @Secured.

Enable @Secured and @PreAuthorize

In the core of method level security is the configuration element “<global-method-security/>“. This needs to be defined inside your spring’s configuration file. This element is used to enable annotation-based security in your application (by setting the appropriate attributes on the element). You should only declare one <global-method-security/> element. e.g.

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

Above configuration will enable the @PreAuthorize and @PostAuthorize annotations in your code.


Another variation of above configuration is:

<global-method-security secured-annotations="enabled" />

This will enable the @Secured annotation in your code.

These annotations take one string parameter which is either is role-name or expression, and which one to use depends on your configuration for <http> element’s use-expression value.

If use-expression is set to true, then you should use expressions inside the annotation otherwise role name should be used directly.

Expression-based annotations are a good choice if you need to define simple rules that go beyond checking the role names against the user’s list of authorities. You can enable more than one type of annotation in the same application, but you should avoid mixing annotations types in the same interface or class to avoid confusion.

Test Security Annotations

To test above annotations in running application, I am using the code base of previous tutorial related to login form based security.

This application is already secured for URL level security. Now, we will add support for method level security also.

Modify application-security.xml configuration

To enable support for method level security, I will update the application-security.xml file with <global -method-security> tag as below:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
	<global-method-security pre-post-annotations="enabled" />
	<http auto-config="false"  use-expressions="true">
		<intercept-url pattern="/login" access="permitAll" />
		<intercept-url pattern="/logout" access="permitAll" />
		<intercept-url pattern="/accessdenied" access="permitAll" />
		<intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
		<form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
		<logout logout-success-url="/logout" />

	<authentication-manager alias="authenticationManager">
                <user name="lokesh" password="password" authorities="ROLE_USER" />
                <user name="admin" password="password" authorities="ROLE_USER,ROLE_ADMIN" />
    <beans:bean id="employeeDAO" class="com.howtodoinjava.dao.EmployeeDaoImpl" />
    <beans:bean id="employeeManager" class="com.howtodoinjava.service.EmployeeManagerImpl" />

Rest all the code is same as previous tutorial.

Annotate methods to be secured

In this tutorial, I want that user with role admin can only add an employee to employees collection. Rest other operations are allowed as before. To do so, I will annotate add method in EmployeeDaoImpl.java as below:

package com.howtodoinjava.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Repository;

import com.howtodoinjava.entity.EmployeeEntity;

public class EmployeeDaoImpl implements EmployeeDAO  {

    private SessionFactory sessionFactory;

	public void addEmployee(EmployeeEntity employee) {

	public List&lt;EmployeeEntity&gt; getAllEmployees() {
		return this.sessionFactory.getCurrentSession().createQuery("from Employee").list();

	public void deleteEmployee(Integer employeeId) {
		EmployeeEntity employee = (EmployeeEntity) sessionFactory.getCurrentSession().load(
				EmployeeEntity.class, employeeId);
        if (null != employee) {

@PreAuthorize annotation will test that if logged in used has the ‘ROLE_ADMIN‘ authority or not. If user has not this authority, an access denied exception will be thrown.


Our application is configured and is ready to be deployed. So, lets do it !!

1) Hit the URL “http://localhost:8080/Spring3HibernateIntegration/login” in browser window

Login window

A login window will appear because all the URLs are protected.

2) Login with username “lokesh” and password “password” and try to add an employee

Access denied message

A access denied exception will be thrown as lokesh does not have admin permission.

3) Login with username “admin” and password “password” and try to add an employee

Employee management screen

Admin will be able to add employee because he has ‘ROLE_ADMIN‘ assigned to him.

Let me know if you have any issue in running the application.

Happy Learning !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

15 thoughts on “Spring Method Security with @PreAuthorize and @Secured”

  1. Hello Lokesh,
    I have a requirement to implement Spring ACL security with these steps
    1. Annotate methods
    2. Load user security context with ACL information
    3. Use custom LookupStrategy to read ACL information from user security
    context and perform ACL validation
    Moreover I want to use user and useraccess(with fields UserId,AllowRead,AllowWrite,AllowExecute,Denied,Project,Client,Environment) table of my database instead of using spring ACLS table.

    I am stuck in this and not getting any help anywhere .Is this possible/relevant to do ?

  2. For people with with the downloaded source code who want to set up the database, here is the SQL:

    use dbo;
    CREATE TABLE `employee` (
    `FIRSTNAME` varchar(30) DEFAULT NULL,
    `LASTNAME` varchar(30) DEFAULT NULL,
    `TELEPHONE` varchar(15) DEFAULT NULL,
    `EMAIL` varchar(30) DEFAULT NULL,

    Also jdbc.properties may need the “com.mysql.jdbc.Driver” half uncommented. And you need “jdbc.databaseurl=jdbc:mysql://” (Delete “EmployeeDatabase”).

    • You can use pointcut expressions inside your <global-method-security> tag in your XML configuration. This will also let you match multiple methods with a regex, if you need to.

      <protect-pointcut expression=”execution(* com.yourpackage.IHelloController.welcome(..))” access=”ROLE_ADMIN”/>


Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.