@PreAuthorize annotation – hasPermission Example In Spring Security

Spring Security Has Permission

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.

I will authenticate user using in-memory credentials as well as database credentials. I will use here MySQL database to authenticate role based authentication by implementing Spring’s built-in service UserDetailsService.

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.


Java 19, Maven 3.8.5, Spring Boot 3.1.4, MySQL 8.1.0

Project Setup

I will add the required dependencies for our Spring Security PreAuthorize hasRole() and hasPermission() example.

For a maven based project you can use below pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">









Permission Evaluator

You 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:

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;


MySQL Tables

I am going to authenticate user using database, so I am going to create two tables in the MySQL database – user and user_role.

  `user_name` varchar(30) NOT NULL,
  `user_pass` varchar(255) NOT NULL,
  `enable` tinyint NOT NULL DEFAULT '1',
  PRIMARY KEY (`user_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

  `user_name` varchar(30) NOT NULL,
  `user_role` varchar(15) NOT NULL,
  KEY `user_name` (`user_name`),
  CONSTRAINT `user_role_ibfk_1` FOREIGN KEY (`user_name`) REFERENCES `user` (`user_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

You need to dump some users and their roles to test our application. Note that you need to put ROLE_ as a prefix when you insert data for role of a user.

INSERT INTO `user` (`user_name`, `user_pass`, `enable`) VALUES
	('admin', '$2a$10$dl8TemMlPH7Z/mpBurCX8O4lu0FoWbXnhsHTYXVsmgXyzagn..8rK', 1),
	('user', '$2a$10$9Xn39aPf4LhDpRGNWvDFqu.T5ZPHbyh8iNQDSb4aNSnLqE2u2efIu', 1);

INSERT INTO `user_role` (`user_name`, `user_role`) VALUES
	('user', 'ROLE_USER'),
	('admin', 'ROLE_USER'),
	('admin', 'ROLE_ADMIN');

Application Properties

The classpath file src/main/resources/application.properties file is used to declare the database settings.


Model Class

I will create model classes to represent table data as an object. There are two tables – one for user and another one for user role.

public class User {

	private String username;
	private String userpwd;

	//getters and setters

public class Role {

	private String role;

	//getter and setter


Row Mapper Class

I need to map the fetched rows from database table to Java object. Therefore I need to implement Spring RowMapper interface to map rows into java object.

public class UserRowMapper implements RowMapper<User> {

	public User mapRow(ResultSet rs, int rowNum) throws SQLException {
		User user = new User();
		return user;


DAO Class

I will create a Spring Repository class to fetch data from database.

public class UserDao {

	private JdbcTemplate jdbcTemplate;

	public User getUser(String username) {
		return jdbcTemplate.queryForObject("select user_name, user_pass from user where user_name = ?",
				new Object[] { username }, new UserRowMapper());

	public List<Role> getRoles(String username) {
		List<Map<String, Object>> results = jdbcTemplate
				.queryForList("select user_role from user_role where user_name = ?", new Object[] { username });
		List<Role> roles = results.stream().map(m -> {
			Role role = new Role();
			return role;
		return roles;


In the above class I am using Spring JDBC template API to fetch data.

In the getRoles() method the query object returns a list of map of objects and from map of objects I am fetching list of roles using Java’s Stream API.

Spring User Details Service

I will use Spring’s UserDetailsService to authenticate user with his/her role(s) from database.

public class UserAuthService implements UserDetailsService {

	private UserDao userDao;

	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		User user = userDao.getUser(username);

		if (user == null) {
			throw new UsernameNotFoundException("User '" + username + "' not found.");

		List<Role> roles = userDao.getRoles(username);

		List<GrantedAuthority> grantedAuthorities = roles.stream().map(r -> {
			return new SimpleGrantedAuthority(r.getRole());

		org.springframework.security.core.userdetails.User usr = new org.springframework.security.core.userdetails.User(
				user.getUsername(), user.getUserpwd(), grantedAuthorities);

		return usr;


Security Configuration Class

The below class configures Spring Security.

I need the following 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.

I 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)

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.

The below example shows both ways to authenticate the user – in-memory authentication as well as database authentication.

Source code of the configuration class is given below:

public class SpringPreAuthorizeSecurityConfig {

	private CustomPermissionEvaluator permissionEvaluator;
	private UserAuthService userAuthService;
	private PasswordEncoder passwordEncoder;

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

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


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.

You need to configure PasswordEncoder in a separate class otherwise you will see the following exception:

Requested bean is currently in creation: Is there an unresolvable circular reference?

Password encoder config class:

public class PasswordConfig {

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


REST Controller

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

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

public class PreAuthorizeRestController {

	public ResponseEntity<String> userRole() {
		return new ResponseEntity<String>("You have USER role", HttpStatus.OK);

	public ResponseEntity<String> adminRole() {
		return new ResponseEntity<String>("You have ADMIN role", HttpStatus.OK);

	@PreAuthorize("hasRole('ADMIN') and hasPermission('hasAccess','READ')")
	public ResponseEntity<String> adminAccess() {
		return new ResponseEntity<String>("You have ADMIN role and READ access", HttpStatus.OK);


Spring Boot Main Class

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

public class SpringSecurityPreauthHasPermissionApp {

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


Testing the Has Permission 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 has permission

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


Leave a Reply

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