I have the following controller that creates a user based on the request body.
@PostMapping
public void registerNewUser(@RequestBody User user) {
userService.addNewUser(user);
}
However I have also implemented a filter chain to validate the request's cookie, but since I am creating a user no cookies need to be validated. Therefore I have made the following if statement
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if(request.getCookies() == null) {
filterChain.doFilter(request, response);
return;
}
....
But this is where the issue occurs. It does not reach its end destination (the controller) and create my user. In fact it gives me a 403 Forbidden status code. What am I missing?
I suspect that my authentication filter might cause the issue. I believe it is trying to authenticate all incoming requests which I don't want for the registration endpoint.
public class JwtUsernameAndPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
try {
UsernameAndPasswordAuthenticationRequest authenticationRequest = new ObjectMapper().readValue(request.getInputStream(), UsernameAndPasswordAuthenticationRequest.class);
Authentication authentication = new UsernamePasswordAuthenticationToken(authenticationRequest.getUsername(), authenticationRequest.getPassword());
Authentication authenticate = authenticationManager.authenticate(authentication);
return authenticate;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
String token = Jwts.builder()
.setSubject(authResult.getName())
.claim("authorities", authResult.getAuthorities())
.setIssuedAt(new Date())
.setExpiration(java.sql.Date.valueOf(LocalDate.now().plusDays(jwtConfig.getTokenExpirationAfterDays())))
.signWith(secretKey)
.compact();
response.resetBuffer();
response.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
response.getOutputStream().print(new ObjectMapper().writeValueAsString("Authenticated!"));
Cookie sessionCookie = new Cookie("JSESSIONID", token);
response.addCookie(sessionCookie);
response.flushBuffer();
}
}
My configuration
protected void configure(HttpSecurity http) throws Exception {
http.cors().configurationSource(corsConfigurationSource()).and().csrf().disable().formLogin().disable().httpBasic().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().addFilter(new JwtUsernameAndPasswordAuthenticationFilter(authenticationManager(), jwtConfig, secretKey))
.addFilterAfter(new JwtTokenVerifier(secretKey, jwtConfig), JwtUsernameAndPasswordAuthenticationFilter.class)
.authorizeRequests().antMatchers("/", "index", "/css/*", "/js/*").permitAll().antMatchers("/api/**")
.hasRole(ApplicationUserRole.USER.name()).anyRequest().authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
configuration.setAllowedMethods(Arrays.asList("GET","POST", "OPTIONS", "PUT", "DELETE"));
configuration.addAllowedHeader("Access-Control-Allow-Origin");
configuration.addAllowedHeader("Content-Type");
configuration.setAllowCredentials(true);
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder);
provider.setUserDetailsService(applicationUserService);
return provider;
}
@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer{
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("http://localhost:3000").allowCredentials(true).allowedMethods("GET", "POST","PUT", "DELETE", "OPTIONS");
}
};
}
}
Just an update:
I have implemented a shouldnotfilter method to avoid filtering on registering, but the problem still persist. I still receive 403 Forbidden but it seems like it does not filter on the registration endpoint
@Override
protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
String path = request.getRequestURI();
return "/management/api/v1/users/register".equals(path);
}
So the issue was actually in the configure method. I was actually allowing the specific endpoint to only role-specific users as following:
.antMatchers("/api/**").hasRole(ApplicationUserRole.USER.name()).anyRequest().authenticated()
I missed this, as I was actually using /management/api/ but did not know this was applied and thought there was something wrong with my filter, but it was a security configuration issue.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.