October 1, 2025
Spring Security Role-Based Authorization

Complete Application with Spring Boot – Part 8 (Role-Based Authorization – 2)

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

In this part, we would set up the controller and then create the pages. Let’s get to work!

    1. Create the RoleController
    2. Create the UserEdit Page
    3. Write the Controller Method to Show the userEdit page
    4. Write the AssignRole/UnassignRole Controller Methods
    5. Restrict Access to  Page
    6. Update the Authorities Collection
    7. Configure Access Denied Page

Watch the video tutorial Watch the video tutorial 

1. Create the RoleController

So we would have to create the RoleController as well as a roles page for LIST/ADD/EDIT/DELETE role. Follow the steps:

Step 1 – Create the RoleController based on existing controllers

Step 2 – Create the roles.html page inside the templates folder. Write the markup to display list of roles or just copy, paste and modify from existing page.

Step 3 – Create the js file

Step 5(Optional) – You could also add a navigation link to the roles page.

Step 5 – Test the page. Add a few roles: USER, ADMIN and SUPER-ADMIN

 

2. Create the UserEdit Page

This is a page that would be used for assigning and unassigning roles to users. So follow the steps below:

Step 1 – Create a page called userEdit in the templates folder

This page would contain three sections:

  • User data
  • Roles currently assigned to the user
  • Roles not assigned to user (assignable roles)

The layout of this page is given below:

UserEdit Page Layout
UserEdit Page Layout

See the video for  the actual markup of this page.

Step 2 – You need to link this page. So open the existing user.html page and add one more column to the users table. The markup for this column is given below:

<a  th:href="@{'/security/user/Edit/'+${user.id}}"
   class="btn btn-primary"><i class="icon_pencil-edit"></i>Manage Roles</a>

 

3. Write the Controller Methods to Load the Edit Page

You now need to write the controller method to show the Edit page. I would be written in the RoleController file. This is given below:

@GetMapping("/security/user/Edit/{id}")
public String editEmployee(@PathVariable Integer id, Model model){
    User user = userService.findById(id);
    model.addAttribute("user", user);
    model.addAttribute("userRoles", roleService.getUserRoles(user));
    model.addAttribute("userNotRoles", roleService.getUserNotRoles(user));
    return "/userEdit";
}

 

4. Write the Controller Methods for (Assign/Unassign) Roles

In the RoleController, we need to write two more methods for assigning and unassigning roles to users.

The assignRole() method is given below

@RequestMapping("/security/role/assign/{userId}/{roleId}")
public String assignRole(@PathVariable Integer userId, 
                         @PathVariable Integer roleId){
    roleService.assignUserRole(userId, roleId);
    return "redirect:/user/Edit/"+userId;
}

 

The unassignRole() method is given below;

@RequestMapping("/security/role/unassign/{userId}/{roleId}")
public String unassignRole(@PathVariable Integer userId,
                           @PathVariable Integer roleId){
    roleService.unassignUserRole(userId, roleId);
    return "redirect:/user/Edit/"+userId;
}

 

Now you can fire up the application and assign and unassign some roles!

 

5. Restrict Page Access (HasAuthority and HasAnyAuthority)

Now we want to restrict a page access based on the user’s role. So now we would like to restrict access to the userEdit page to only users with the ‘ADMIN’ role.

To achieve this, open the applicationSecurityConfig file and include this line in the configure section:

.antMatchers("/security/user/Edit/**").hasAuthority("ADMIN")

Note: To specify multiple authorities, you can use hasAnyAuthority(), then provide multiple authorities separated by comma.

The code means that any route matching the pattern provided will only be accessible to users with role specified in the .hasRoles() part. In this case, ADMIN.

 

6. Update the Authorities Collection

You remember that in the UserPrincipal class, we had a getAuthorities() method that returns a singleton collection of new SimpleGrantedAuthority(“USER”). Now we have to adjust that.

We would use the list of roles we stored in our database to create list of authorities, and then return the list.

The new code is shown below, with the previous code commented out.

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
	List<GrantedAuthority> authorities = new ArrayList<>();
	for(Role role: user.getRoles()){
		authorities.add(new SimpleGrantedAuthority(role.getDescription()));
	}
	//return Collections.singleton(new SimpleGrantedAuthority("USER"));
	return authorities;
}

Also remember to autowire the RoleRepository

With this code, when a user want to access a resource, his roles would be checked to determine if he has the permission.

 

7. Configure Access Denied Page

We would need a page that would be displayed if a user requests for an unauthorized resource.

Step 1 – Create an access denied page. I call it accessDenied.html

Step 2 – Create a controller route to serve this page. Here, I use “/accessDenied”

Step 3 – In the configure method of the ApplicationSecurityConfig file, include the line below:

.and()
.exceptionHandling().accessDeniedPage("/accessDenied")

 

We are done here! And please do watch the video. And please do watch the video for any clarification. You can also leave me a comment to let me know if you have any challenges.

On to Part 2

3.3 4 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments