Issue
I am new and learning spring-boot and spring security and here I am trying to create a EmployeeManagement App which can perform CRUD operations on Employees.In this Admin should be able to add Users dynamically to db and admin should have permission to all API's while User should have permission to view employees only I created everything required and my project was working well before adding spring security but after adding it ,My User and Admin are able to login but not able access any of the API's. its showing error 403 forbidden and I am not able to get why spring security is not giving permission to access the Urls as per mentioned roles in the configure(http security) method (In this project I have used MySQl database,spring-boot, spring security and swagger-ui)
This is my Security configuration
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(encodePWD());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/secure/**").hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/save", "/employees/updateEmployee/{id}", "/employees/deleteEmployee/{id}")
.hasRole("ADMIN").and().authorizeRequests()
.antMatchers("/", "/employees/list", "/employees/getEmployee/{id}",
"/employees/getAllEmployeesWithTheseName/{firstname}",
"/employees/getEmployeesCustomSortedByName/{direction}")
.hasAnyRole("ADMIN", "USER")
.and()
.httpBasic().and().formLogin().loginProcessingUrl("/login")
.defaultSuccessUrl("/swagger-ui.html", true).and().cors().and().csrf().disable();
}
@Bean
public BCryptPasswordEncoder encodePWD() {
return new BCryptPasswordEncoder();
}
}
This is the error I am getting
{
"timestamp": "2022-11-07T15:59:26.930+00:00",
"status": 403,
"error": "Forbidden",
"message": "Forbidden",
"path": "/EmployeeManagement/employees/list"
}
Solution
You cannot use a PathVariable
in antMatchers(....)
From the documentation AntPathMatcher
The mapping matches URLs using the following rules:
- ? matches one character
- * matches zero or more characters
- ** matches zero or more directories in a path
- {spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
So use:
"/employees/getEmployee/{id:[0-9]+}"
or"/employees/getEmployee/*
"/employees/getAllEmployeesWithTheseName/{firstname:[A-Za-z]+}"
or"/employees/getAllEmployeesWithTheseName/*
Answered By - Dirk Deyne
Answer Checked By - Mildred Charles (JavaFixing Admin)