I am using the latest spring security, I want to access an admin endpoint however everytime i request I got forbidden here’s my code:
Security filter chain:
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.securityMatcher(MatchersConstant.BASE_PATTERN).authorizeHttpRequests(auth ->
auth
.requestMatchers(MatchersConstant.ADMIN_PATTERN).hasRole(String.valueOf(RoleType.ADMIN))
.requestMatchers(HttpMethod.POST, MatchersConstant.ANONYMOUS_PATTERN).anonymous()
.requestMatchers(MatchersConstant.AUTH_PATTERN).permitAll()
.requestMatchers(MatchersConstant.USER_PATTERN).authenticated())
.httpBasic(hbc -> hbc.authenticationEntryPoint(authenticationEntryPoint))
.sessionManagement(smc -> smc.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authenticationProvider(authenticationProvider)
.csrf(AbstractHttpConfigurer::disable)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.addFilterBefore(corsFilter(), SecurityContextPersistenceFilter.class);
return http.build();
}
User:
@Data
@Builder
@AllArgsConstructor
@RequiredArgsConstructor
@Table(name="users")
@Entity
public class User implements UserDetails {
//esisting code here
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "userId"),
inverseJoinColumns = @JoinColumn(name = "roleId")
)
private Set<Role> roleList = new HashSet<>();
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return roleList.stream()
.map(role -> new SimpleGrantedAuthority(role.getRoleType().toString()))
.collect(Collectors.toList());
}
}
Role:
@Data
@Builder
@AllArgsConstructor
@RequiredArgsConstructor
@Table(name="roles")
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long roleId;
private RoleType roleType;
@ManyToMany(mappedBy = "roleList")
private Set<User> users = new HashSet<>();
}
RoleTypes:
public enum RoleType {
ADMIN,
USER,
PREMIUM_USER
}
I want to fix that so user with admin role can send request to this endpoint public static String ADMIN_PATTERN =”/api/v1/admin/**”;