@PreAuthorize annotation – hasPermission example in Spring Security


In this tutorial I will show you an example on @PreAuthorize annotation – hasPermission example in Spring Security. The most useful annotation @PreAuthorize, which decides whether a method can actually be invoked or not based on user’s role and permission. hasRole() method returns true if the current principal has the specified role and hasPermission() method returns true if the current user’s role has the specific permission such as READ, WRITE, UPDATE or DELETE. By default if the supplied role does not start with ROLE_, then it will be added. This can be customized by modifying the defaultRolePrefix on DefaultWebSecurityExpressionHandler.

You can check my previous tutorial on hasRole @PreAuthorize annotation – hasRole example in Spring Security

Where is @PreAuthorize applicable?

This @PreAuthorize annotation is applicable on the method as a Method Security Expression. For example,

@PreAuthorize("hasRole('ADMIN') and hasPermission('hasAccess','WRITE')")
public void create(Contact contact);

which means that access will only be allowed for users with the role ROLE_ADMIN and has WRITE permission. Obviously the same thing could easily be achieved using a traditional configuration and a simple configuration attribute for the required role.


Eclipse, Java 1.8, Gradle 4.10.2, Spring Boot 2.1.5

Example with Source Code

Let’s see the working example below…

Creating Project

Create a gradle project in Eclipse, the project structure looks similar to the below image:

preauthorize haspermission

Updating Build Script

We will add the required dependencies for our Spring Security PreAuthorize hasRole example.

We have added dependencies for spring security.

buildscript {
	ext {
		springBootVersion = '2.1.5.RELEASE'
    repositories {
    dependencies {

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {

dependencies {

Creating Permission Evaluator

We need to use hasPermission() method in @PreAuthorize annotation in order to evaluate permission of a user. The use of the hasPermission() expression has different look.

hasPermission() expressions are delegated to an instance of PermissionEvaluator. It is intended to bridge between the expression system and Spring Security’s ACL system, allowing you to specify authorization constraints on domain objects, based on abstract permissions. It has no explicit dependencies on the ACL module, so you could swap that out for an alternative implementation if required. The interface has two methods:

boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission);

boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission);

which map directly to the available versions of the expression, with the exception that the first argument (the Authentication object) is not supplied. The first is used in situations where the domain object, to which access is being controlled, is already loaded. Then expression will return true if the current user has the given permission for that object. The second version is used in cases where the object is not loaded, but its identifier is known. An abstract “type” specifier for the domain object is also required, allowing the correct ACL permissions to be loaded.

To use hasPermission() expressions, you have to explicitly configure a PermissionEvaluator in your application context.

The custom permission evaluator is given below:

package com.jeejava.spring.security.preauth.permission;

import java.io.Serializable;

import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

public class CustomPermissionEvaluator implements PermissionEvaluator {

	public boolean hasPermission(Authentication authentication, Object accessType, Object permission) {
		if (authentication != null && accessType instanceof String) {
			if ("hasAccess".equalsIgnoreCase(String.valueOf(accessType))) {
				boolean hasAccess = validateAccess(String.valueOf(permission));
				return hasAccess;
			return false;
		return false;

	private boolean validateAccess(String permission) {
		// ideally should be checked with user role, permission in database
		if ("READ".equalsIgnoreCase(permission)) {
			return true;
		return false;

	public boolean hasPermission(Authentication authentication, Serializable serializable, String targetType,
			Object permission) {
		return false;


Creating Configuration Class

The below class configures Spring Security.

We need below security configuration using Java annotation in order to use authorization.

Enable Web Security using below class. Configure global-method-security pre-post-annotation using Java configuration.

Here, the in-memory authentication has been provided. Ideally in the application, the authentication should happen through database or LDAP or any other third party API etc.

We have used PasswordEncoder because plain text password is not acceptable in current version of Spring Security and you will get below exception if you do not use PasswordEncoder.

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
	at org.springframework.security.crypto.password.DelegatingPasswordEncoder$UnmappedIdPasswordEncoder.matches(DelegatingPasswordEncoder.java:244) ~[spring-security-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]

As the passwords are in encrypted format in the below class, so you won’t find it easier until I tell you. The password for user is user and for admin is admin.

Source code of the configuration class is given below:

package com.jeejava.spring.security.preauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.jeejava.spring.security.preauth.permission.CustomPermissionEvaluator;

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringPreAuthorizeSecurityConfig extends WebSecurityConfigurerAdapter {

	private CustomPermissionEvaluator permissionEvaluator;

	public void registerGlobal(AuthenticationManagerBuilder auth) throws Exception {
		// Ideally database authentication is required
				.password("$2a$10$dl8TemMlPH7Z/mpBurCX8O4lu0FoWbXnhsHTYXVsmgXyzagn..8rK").roles("USER", "ADMIN");

	public MethodSecurityExpressionHandler methodSecurityExpressionHandler() {
		DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
		return handler;

	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();


Here in the above class, admin has USER as well as ADMIN roles but user has only one role USER. Therefore admin can access its own URL as well as user’s URL but user can access only its own URL but not admin’s URL.

Creating REST Controller

Now create below REST Controller class to test the user’s access to a particular URL based on role using @PreAuthorize annotation.

We have defined three end-points with roles and one with role and read permission.

package com.jeejava.spring.security.preauth.rest.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

public class PreAuthorizeRestController {

	public String userRole() {
		return "You have USER role";

	public String adminRole() {
		return "You have ADMIN role";

	@PreAuthorize("hasRole('ADMIN') and hasPermission('hasAccess','READ')")
	public String adminAccess() {
		return "You have ADMIN role and READ access";


Creating Main Class

Spring Boot application created as standalone application and can be easily deployed into embedded Tomcat server using main class.

You need to exclude WebMvcAutoConfiguration class to avoid below exception because it does auto configuration for WebMvc too:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'resourceHandlerMapping' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration
package com.jeejava.spring.security.preauth;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;

@SpringBootApplication(scanBasePackages = "com.jeejava.spring.security.preauth", exclude = {
		WebMvcAutoConfiguration.class })
public class SpringPreAuthorize {

	public static void main(String[] args) {
		SpringApplication.run(SpringPreAuthorize.class, args);


Testing the Application

Run the main class to deploy your application into Tomcat server.

Now access the URL – http://localhost:8080/admin/access using credentials admin/admin then you will see the output You have ADMIN role and READ access. The output is shown in the below image:

@PreAuthorize annotation - hasPermission example in Spring Security

Now if you change the permission as hasPermission(‘hasAccess’,’WRITE’) then you will get HTTP Status 403 – Access is denied because admin does not have the WRITE permission.

Source Code

You can download source code.

Thanks for reading.

@PreAuthorize annotation – hasPermission example in Spring Security

Leave a Reply

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

Scroll to top