Roles & SecurityConfig

Hello so i have 3 roles
public enum Role {
ADMIN,
STAFF,
USER;
}
public enum Role {
ADMIN,
STAFF,
USER;
}
and i'm trying to write the authorities etc and here is my config
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(request -> request
.requestMatchers("/api/v1/auth/**", "/ws/**").permitAll()

.requestMatchers("/api/v1/admin/**").hasAuthority("ADMIN")

.requestMatchers("/api/v1/staff/**").hasAuthority("STAFF")

.requestMatchers("/api/v1/user/**").hasAuthority("USER")

.requestMatchers("/api/v1/adminuser/**").hasAnyAuthority("ADMIN", "USER")

.requestMatchers("/api/v1/logs/**").hasAnyAuthority("STAFF", "ADMIN")

.anyRequest().authenticated()
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
)
.authenticationProvider(authenticationProvider)
.addFilterBefore(new SessionAuthenticationFilter(userSessionService), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutService)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
);

return http.build();
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeHttpRequests(request -> request
.requestMatchers("/api/v1/auth/**", "/ws/**").permitAll()

.requestMatchers("/api/v1/admin/**").hasAuthority("ADMIN")

.requestMatchers("/api/v1/staff/**").hasAuthority("STAFF")

.requestMatchers("/api/v1/user/**").hasAuthority("USER")

.requestMatchers("/api/v1/adminuser/**").hasAnyAuthority("ADMIN", "USER")

.requestMatchers("/api/v1/logs/**").hasAnyAuthority("STAFF", "ADMIN")

.anyRequest().authenticated()
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
)
.authenticationProvider(authenticationProvider)
.addFilterBefore(new SessionAuthenticationFilter(userSessionService), UsernamePasswordAuthenticationFilter.class)
.logout(logout -> logout
.logoutUrl("/api/v1/auth/logout")
.addLogoutHandler(logoutService)
.logoutSuccessHandler((request, response, authentication) -> SecurityContextHolder.clearContext())
);

return http.build();
}
but for some reason when i hit this endpoint that requries it to be ADMIN such as this endpoint
@RestController
@RequestMapping("/api/v1/admin")
@RequiredArgsConstructor
public class AdminController {

private final InvitationService invitationService;

@PostMapping("/invite")
@PreAuthorize("hasAuthority('ADMIN')")
public ResponseEntity<String> createInvitation(@RequestParam String email) throws MessagingException {
String response = invitationService.createInvitation(email);
return ResponseEntity.ok(response);
}
@RestController
@RequestMapping("/api/v1/admin")
@RequiredArgsConstructor
public class AdminController {

private final InvitationService invitationService;

@PostMapping("/invite")
@PreAuthorize("hasAuthority('ADMIN')")
public ResponseEntity<String> createInvitation(@RequestParam String email) throws MessagingException {
String response = invitationService.createInvitation(email);
return ResponseEntity.ok(response);
}
it doesnt let me even when i'm authenticated and have a session. But when i change the securityconfig
.requestMatchers("/api/v1/admin/**").hasAuthority("ADMIN")
.requestMatchers("/api/v1/admin/**").hasAuthority("ADMIN")
to
.requestMatchers("/api/v1/admin/**").permitAll()
.requestMatchers("/api/v1/admin/**").permitAll()
then it works
23 Replies
JavaBot
JavaBotā€¢11h ago
āŒ› This post has been reserved for your question.
Hey @Itsurran! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
ayylmao123xdd
ayylmao123xddā€¢11h ago
for testing purposes get rid of the pre authorize annotation
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
and use this and check if it works
Itsurran
ItsurranOPā€¢11h ago
so i should remove the
@PreAuthorize("hasAuthority('ADMIN')")
@PreAuthorize("hasAuthority('ADMIN')")
from controller and let this code still be in config
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
.requestMatchers("/api/v1/admin/**").hasRole("ADMIN")
?
ayylmao123xdd
ayylmao123xddā€¢11h ago
yea
Itsurran
ItsurranOPā€¢11h ago
if so i still get 403 in postman
ayylmao123xdd
ayylmao123xddā€¢11h ago
try that
Itsurran
ItsurranOPā€¢11h ago
its either not checking that ihave a session when i hit that endpoint or something that reconize the users session aka role or something wrong with securityconfig but i'm getting a cookie automatiaclly in postman when i authenticate
ayylmao123xdd
ayylmao123xddā€¢11h ago
show the code for user authentication like how it checks if a user is authenticated
Itsurran
ItsurranOPā€¢11h ago
@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(@RequestBody AuthenticationRequest request, HttpServletResponse response) {
return authenticationService.authenticate(request, response);
}
@PostMapping("/authenticate")
public ResponseEntity<AuthenticationResponse> authenticate(@RequestBody AuthenticationRequest request, HttpServletResponse response) {
return authenticationService.authenticate(request, response);
}
public ResponseEntity<AuthenticationResponse> authenticate(AuthenticationRequest request, HttpServletResponse response) {
User user = userRepository.findByEmail(request.getEmail())
.orElseThrow(() -> new ValidationException("Invalid email or password"));

if (user.getRegistrationStatus() != RegistrationStatus.APPROVED) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new AuthenticationResponse("Your account is not approved yet"));
}

authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);

setSessionCookie(response, user);

return ResponseEntity.ok(new AuthenticationResponse("User authenticated successfully"));
}
public ResponseEntity<AuthenticationResponse> authenticate(AuthenticationRequest request, HttpServletResponse response) {
User user = userRepository.findByEmail(request.getEmail())
.orElseThrow(() -> new ValidationException("Invalid email or password"));

if (user.getRegistrationStatus() != RegistrationStatus.APPROVED) {
return ResponseEntity.status(HttpStatus.FORBIDDEN)
.body(new AuthenticationResponse("Your account is not approved yet"));
}

authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword())
);

setSessionCookie(response, user);

return ResponseEntity.ok(new AuthenticationResponse("User authenticated successfully"));
}
and im getting a session
Itsurran
ItsurranOPā€¢11h ago
when i auth
No description
Itsurran
ItsurranOPā€¢11h ago
but as i said i think its either not reconizing the session aka role to send that invite post or some bullshit in config right? ahaaa i think iknow it l0l i don't have anything about invite in my adminservice lmfao wait
ayylmao123xdd
ayylmao123xddā€¢11h ago
so u dont have any code to check if the user from the cookie has role or some other disaster šŸ˜±
Itsurran
ItsurranOPā€¢11h ago
i have a /me that gets the currentuser and by that you need a cookie hmmm not working think we need backup danial
ayylmao123xdd
ayylmao123xddā€¢11h ago
can you try with a test user details try this
@Bean
public UserDetailsService users() {
User.UserBuilder users = User.builder();
UserDetails admin = users
.username("admin")
.password("admin")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
@Bean
public UserDetailsService users() {
User.UserBuilder users = User.builder();
UserDetails admin = users
.username("admin")
.password("admin")
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(admin);
}
and try to login with credentials
Itsurran
ItsurranOPā€¢11h ago
i already have and i can authenticate
ayylmao123xdd
ayylmao123xddā€¢11h ago
if it works its the fault of ur cookie auth so show how the cookie stuff works
Itsurran
ItsurranOPā€¢11h ago
User admin = User.builder() .username(adminUsername) .firstname("Admin") .lastname("User") .email("[email protected]") .password(passwordEncoder.encode("Admin123!")) .socialSecurityNumber("0000000000") .phoneNumber("+46123456789") .street("Default Street 123") .city("Default City") .role(Role.ADMIN) .registrationStatus(RegistrationStatus.APPROVED) .createdAt(LocalDateTime.now()) .build();
ayylmao123xdd
ayylmao123xddā€¢11h ago
so the cookie thing seems to not work
Itsurran
ItsurranOPā€¢11h ago
HMM
ayylmao123xdd
ayylmao123xddā€¢11h ago
do u have custom user details
Itsurran
ItsurranOPā€¢10h ago
No
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.userdetails;

import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;

public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();

String getPassword();

String getUsername();

default boolean isAccountNonExpired() {
return true;
}

default boolean isAccountNonLocked() {
return true;
}

default boolean isCredentialsNonExpired() {
return true;
}

default boolean isEnabled() {
return true;
}
}
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.springframework.security.core.userdetails;

import java.io.Serializable;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;

public interface UserDetails extends Serializable {
Collection<? extends GrantedAuthority> getAuthorities();

String getPassword();

String getUsername();

default boolean isAccountNonExpired() {
return true;
}

default boolean isAccountNonLocked() {
return true;
}

default boolean isCredentialsNonExpired() {
return true;
}

default boolean isEnabled() {
return true;
}
}
got it working followed Bouali Ali video on youtube where he explained everything and i just followed but did my own way like my own roles etc but i think the biggest problem was this
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}
i changed it to
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return role.getAuthorities();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return role.getAuthorities();
}
in my user entity
ayylmao123xdd
ayylmao123xddā€¢10h ago
yea probably it couldnt grab the authorities if u just returned an empty list
JavaBot
JavaBotā€¢5h ago
šŸ’¤ Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?