October 1, 2025
Spring Security Role-Based Authorization1

Complete Application with Spring Boot – Part 7 (Role-Based Authorization – 1)

In this lesson we would setup the role based authorization and be able to restrict resources based on users role.

We would cover the following in this tutorial:

  1. Setup the Security Packages
  2. Create the Role Class
  3. Modify the User Model to Include Roles
  4. Create the Role Repository and Service
  5. Write the AssignRole() and UnassignRole() Methods
  6. Write the GetUserRoles() and GetUserNotRoles() Methods

Watch the video tutorial hereWatch the video tutorial here

1. Setup the Security Packages

We would need to place all the security-related files in the same package. So go ahead to create a package called security. Also four sub-packages as shown below:

  • Security
    • controllers
    • models
    • repositories
    • services

 

2. Create the Role class

Inside the models package, create a class called Role. This class would be as follows:

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Role extends Auditable<String> {
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Id
    private Integer id;

    private String description;
    private String details;
}

I have used Auditable. You can review how to use it here. JPA Auditing video here.

 

3. Modify the User Model to include Roles

You need to modify the User model to include a new filed, roles. This would be a Set of all the roles assigned to the user.

So, open the User.java file and add the following:

@ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
        @JoinTable(
                name = "user_role",
                joinColumns = {@JoinColumn(name = "user_id")},
                inverseJoinColumns = {@JoinColumn(name = "role_id")}
        )
Set<Role> roles = new HashSet<>();

 

4. Create the Role Repository and Service

We need create the RoleRepository interface in the repositories package. Then we also create the RoleService in the services package.

Now, in the RoleService, take the following steps:

Step 1 – Autowire the UserRepository and RoleRepository

Step 2 – Write the findAll(), findById(), save() and delete() methods

 

5. Write the Assign() and Unassign() Methods

These two methods would be used to assign a role to a user or unassign a role to a user. You’ll write them in the service a well. You can find the two method below:

For assignUserRole()

//Assign Role to User
public void assignUserRole(Integer userId, Integer roleId){
    User user  = userRepository.findById(userId).orElse(null);
    Role role = roleRepository.findById(roleId).orElse(null);
   Set<Role> userRoles = user.getRoles();
   userRoles.add(role);
   user.setRoles(userRoles);
   userRepository.save(user);
}

 

For unassignUserRole()

//Unassign Role to User
public void unassignUserRole(Integer userId, Integer roleId){
    User user  = userRepository.findById(userId).orElse(null);
    user.getRoles().removeIf(x -> x.getId()==roleId);
    userRepository.save(user);
}

 

6. GetUserRoles() and GetUserNotRoles()

As you might have thought, these methods are used to return list of a particular user’s roles and list of roles not assigned to a user.

GetUserRoles(user) is quite simple. Just return user.getRoles() as shown below:

public Set<Role> getUserRoles(User user){
    return user.getRoles();
}

 

GetUserNotRoles is not that simple. We actually need to use an SQL statement.  So we have to extend the RoleRepository to include this:

@Query(
        value = "SELECT * FROM role WHERE id NOT IN (SELECT role_id FROM user_role WHERE user_id = ?1)", 
        nativeQuery = true
)
List<Role> getUserNotRoles(Integer userId);

 

You can then write the method in the UserService like shown below:

public List<Role> getUserNotRoles(User user){
   return roleRepository.getUserNotRoles(user.getId());
}

 

This completes Part 1 of Role Base Authorization. In part two, we would setup the controller methods and then create the HTML pages to manage the roles.

Video Tutorial Video Tutorial 

5 1 vote
Article Rating
Subscribe
Notify of
guest

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback

[…] is Role-Based Authorization 2 and Part 8 of out complete spring boot application. In Part 1, we setup the Role model, repository and […]

trackback

[…] This seven steps are detailed here in Part 1 of Role-Based Authorization […]