Fixing the Access Bugs: a Rule per Role and an Ownership Check in Spring Security
The Edit button was hidden but /posts/1/edit still opened for a visitor and for Noah. A hasAnyRole rule above /posts/** and a getForEdit check in PostService (owner or admin, else AccessDeniedException) turn each request into a 302, a 403 or a 200.
What you will learn
- Find why a hidden Edit button still lets the wrong people in
- Add a /posts/*/edit rule above /posts/** because the first match wins
- Check ownership in the service and throw AccessDeniedException for a 403
- Check again on the save, since a form can be skipped
Before you start
- Menus per Role With Thymeleaf Security Tags
The blog hides the Edit button from the wrong people, but a hidden button is not a lock. Today we put two real locks on the server: one rule says who may reach the edit page, and one check says whose post it is. When either says no, the answer is a 403.
Two doors still open
First hole: a visitor who isn't logged in types /posts/1/edit. That address matches the rule for /posts/**, which lets everyone in, so the edit page opens. Second hole: Noah is logged in and types the same address for Emma's post. It opens for him too. The button was hidden, but the address still worked.
Lock 1: a rule per role, at the top
Spring Security reads its rules from the top and the first rule that matches decides. Nothing in the old list was about the edit address, so /posts/** matched first and said permitAll. The fix is a new rule above it:
.requestMatchers("/posts/*/edit").hasAnyRole("USER", "ADMIN")
.requestMatchers("/", "/posts/**", "/about", "/authors/**").permitAll()
.requestMatchers("/register", "/css/**", "/error").permitAll()
.requestMatchers("/h2-console/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
The star stands for the post id. A visitor stopped by this rule is sent to the login page. Put it one line lower and it would never be reached.
Lock 2: ownership, in the service
A building's front desk checks that you have a staff badge; that's the rule above. Inside, every office door checks that your name is on it; that's PostService.getForEdit.
public Post getForEdit(Long id, Authentication user) {
Post post = getById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
boolean owner = post.getAuthor().getEmail().equals(user.getName());
boolean admin = user.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_ADMIN"));
if (!owner && !admin) {
throw new AccessDeniedException("You can only edit your own posts");
}
return post;
}
No such id is a 404. Owner means the author's email equals the logged-in name. Admin means ROLE_ADMIN is among the user's authorities. Neither: throw AccessDeniedException, and Spring Security turns it into a 403. For post 1, written by Emma: Emma is the owner, so yes; Chaand isn't the owner but is an admin, so yes; Noah is neither, so 403.
The controller asks twice
@Controller
public class PostController {
private final PostService postService;
public PostController(PostService postService) {
this.postService = postService;
}
@GetMapping("/posts/{id}/edit")
public String editForm(@PathVariable Long id, Authentication user, Model model) {
model.addAttribute("post", postService.getForEdit(id, user));
return "edit";
}
@PostMapping("/posts/{id}/edit")
public String edit(@PathVariable Long id, Authentication user,
@RequestParam String title, @RequestParam String excerpt) {
postService.update(postService.getForEdit(id, user), title, excerpt);
return "redirect:/posts/" + id;
}
}
Both methods take the Authentication, which Spring passes in. The form page loads the post through getForEdit, not a plain find. And the save asks again before it updates, because anyone can send the POST without ever opening the form.
Same address, different answers
A visitor gets 302 and is sent to log in. Noah on Emma's post gets the 403 page, and if he sends the save anyway it's refused with a 403 too, so post 1 keeps its title. Emma gets 200 and, after saving, a 302 back to the post. Chaand, the admin, gets 200. Noah on his own post 2 gets 200, because for that post he is the owner.
So three things keep an edit page safe: the hidden button keeps it out of sight, the rule per role gates the address, and the ownership check in the service decides. Hide it, gate it, check it. For the same idea with method security and @PreAuthorize, see roles, authorities and method security.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
A Registration Form With Bean Validation in Spring Boot: @Valid, BindingResult and th:errors
A RegisterForm record with three annotations checks the name, email and password at the door. Bad data goes back to the form with a message under each field; good data becomes an Account row. And the password is still stored as plain text, which the next step fixes.
Spring Security 7 Form Login, BCrypt and a UserDetailsService on the Account Table
A guard at the gate and a hash in the table. A SecurityFilterChain lists the open pages and sends everything else to /login, a BCrypt PasswordEncoder bean hashes every password, and a UserDetailsService answers 'who is this email?' from the ACCOUNT table.
Roles and Authorities at Login in Spring Security: From a ROLE Column to hasRole("ADMIN")
Until now every login got .roles("USER") typed into the code. A Role enum on Account, one changed line in the UserDetailsService and one hasRole rule let Chaand open /admin while Emma gets a 403 and a visitor is sent to log in.
Menus per Role With Thymeleaf Security Tags: sec:authorize, sec:authentication and an Edit Button for the Author
One header file, three menus: a visitor sees Register and Login, Emma sees her email and Logout, Chaand also gets Admin. Then each post knows its author through @ManyToOne, and the Edit button shows only for the author or an admin.
