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.
What you will learn
- Store a Role enum on the Account as a readable word with @Enumerated(EnumType.STRING)
- Explain how .roles("ADMIN") becomes the authority ROLE_ADMIN
- Give each logged-in user the role from their own row
- Lock /admin with hasRole and order the rules so the first match decides
Before you start
- Spring Security 7 Form Login, BCrypt and a UserDetailsService
Until now everyone who logs in is the same, because .roles("USER") is typed into the login code. The blog needs an admin who can see every account. Today the badge comes from the account itself: Chaand is ADMIN, Emma and Noah are USER. Same login, different badges, and the admin page opens only for one of them.
A role becomes an authority
Two words need care. A role is a name for a group of people; here, the ROLE column says ADMIN. At login, .roles("ADMIN") makes Spring put ROLE_ in front, so the logged-in user carries the string ROLE_ADMIN in a list called authorities. Authorities are plain strings. The rule hasRole("ADMIN") adds the same prefix and looks for exactly ROLE_ADMIN.
Account: now with a role
public enum Role {
USER,
ADMIN
}
@Enumerated(EnumType.STRING)
private Role role;
public Account(String name, String email, String password, Role role) {
this.name = name;
this.email = email;
this.password = password;
this.role = role;
}
public Role getRole() { return role; }
An enum means Java makes exactly two objects, Role.USER and Role.ADMIN. EnumType.STRING makes Hibernate store the readable word ADMIN instead of a number, and turn the word back into the enum when it reads the row.
AccountService: who gets which role
public Account register(String name, String email, String password) {
return create(name, email, password, Role.USER);
}
public Account create(String name, String email, String password, Role role) {
return accountRepository.save(new Account(name, email, passwordEncoder.encode(password), role));
}
public List<Account> getAll() {
return accountRepository.findAll();
}
register is what the sign-up form calls, and it always makes a USER: the form has no way to pick a role. create takes the role too, and SeedData uses it to make the admin. getAll feeds the admin page.
The role joins the login
return User.withUsername(account.getEmail())
.password(account.getPassword())
.roles(account.getRole().name())
.build();
That's the only new line in AccountUserDetailsService: the stored role instead of a fixed USER.
One rule for /admin
.authorizeHttpRequests(auth -> auth
.requestMatchers("/", "/posts/**", "/about", "/authors/**").permitAll()
.requestMatchers("/register", "/css/**", "/error").permitAll()
.requestMatchers("/h2-console/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated())
Rules are read from the top and the first one that matches decides, which is why the admin rule sits above anyRequest().authenticated(). AdminController puts accountService.getAll() into the Model, and admin.html lists each account's name, email, role and stored hash.
One rule, three visitors
Chaand logs in, loadUserByUsername reads his row with the role ADMIN, and the user it builds holds ROLE_ADMIN. He asks for /admin, the rule matches, and the admin controller answers 200. Emma is logged in too, but her authority is ROLE_USER, so she gets 403. A visitor with no login gets 302 to the login page.
In the H2 console, the three seeded accounts show ADMIN, USER and USER. Mia then signs up through the form, and her new row says USER, because register always makes a USER.
Common mistakes
- Writing
hasRole("ROLE_ADMIN").hasRoleadds the prefix itself; usehasAuthority("ROLE_ADMIN")if you want to write the full string. - Storing the enum with the default ordinal. Reorder the enum and every row means something else.
- Putting the admin rule below
anyRequest(). The first match wins, so it would never be reached.
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.
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.
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.
