Responsive Ad Area

Share This Post

test

WebSecurityConfigurer returns 401 on POST request, but works on GET Request Spring boot JWT

I’m new on spring boot and i’m trying to create a stateless spring boot application. When i make a GET Request to an endpoint, everything seems to work with authentication. But when i make a POST request the application doesn’t go into the filter.
Here’s my WebSecurityConfigurerAdapter:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  ...

  @Bean
  public AutenticationTokenFilter jwtAuthenticationTokenFilter() {
    return new AutenticationTokenFilter();
  }

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity.csrf().ignoringAntMatchers(EnumRotasEntrada.getAuthenticationUrls())
        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
        .exceptionHandling().authenticationEntryPoint(entryPoint).and()
        .authorizeRequests().anyRequest().authenticated().and()
        .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class)
        .formLogin().loginPage(EnumRotasEntrada.ROTA_LOGIN.getRota())
        .successHandler(authenticationSuccessHandler).failureHandler(authenticationFailureHandler)
        .and().logout()
        .logoutRequestMatcher(new AntPathRequestMatcher(EnumRotasEntrada.ROTA_DESLOGAR.getRota()))
        .logoutSuccessHandler(logoutSuccessfullyHandler).deleteCookies(tokenHelper.getAuthCookie());
    super.configure(httpSecurity);
  }
}

It was supposed to post request pass thru the jwtAuthenticationTokenFilter() instead it fall into authenticationEntryPoint
Here’s the AuthenticationTokenFilter:

public class AutenticationTokenFilter extends OncePerRequestFilter {
  private final Log logger = LogFactory.getLog(this.getClass());

  @Autowired
  TokenHelper tokenHelper;

  @Autowired
  UserDetailsService userDetailsService;

  public static final String ROOT_MATCHER = "/";
  public static final String FAVICON_MATCHER = "/favicon.ico";
  public static final String HTML_MATCHER = "/**/*.html";
  public static final String CSS_MATCHER = "/**/*.css";
  public static final String JS_MATCHER = "/**/*.js";
  public static final String IMG_MATCHER = "/images/*";
  public static final String LOGIN_MATCHER = "/auth/login";
  public static final String LOGOUT_MATCHER = "/auth/logout";

  private List<String> rotasParaEsquivar = Arrays.asList(ROOT_MATCHER, HTML_MATCHER,
      FAVICON_MATCHER, CSS_MATCHER, JS_MATCHER, IMG_MATCHER, LOGIN_MATCHER, LOGOUT_MATCHER);

  @Override
  public void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                               FilterChain chain) throws IOException, ServletException {

    Optional<String> tokenDeAutorizacao = tokenHelper.getToken(request);
    if (tokenDeAutorizacao.isPresent() && !rotasParaEsquivar(request, rotasParaEsquivar)) {
      // retorna o usuário do token
      try {
        final String token = tokenDeAutorizacao.get();
        Optional<String> usuario = tokenHelper.getUsuarioDoToken(token);
        if (usuario.isPresent()) {
          UserDetails detalhesDoUsuario = userDetailsService.loadUserByUsername(usuario.get());
          TokenBasedAuthentication autenticacao = new TokenBasedAuthentication(detalhesDoUsuario);
          autenticacao.setToken(token);
          SecurityContextHolder.getContext().setAuthentication(autenticacao);
        }
      } catch (Exception e) {
        SecurityContextHolder.getContext().setAuthentication(new SecurityAnonymousAuthentication());
      }
    } else {
      SecurityContextHolder.getContext().setAuthentication(new SecurityAnonymousAuthentication());
    }

    chain.doFilter(request, response);
  }

  private boolean rotasParaEsquivar(HttpServletRequest requisicao, List<String> rotasParaEsquivar) {
    Assert.notNull(rotasParaEsquivar, "rota não pode ser nula;");
    List<RequestMatcher> rotasParaSeremEsquivadas = rotasParaEsquivar.stream()
        .map(path -> new AntPathRequestMatcher(path)).collect(Collectors.toList());
    OrRequestMatcher matchers = new OrRequestMatcher(rotasParaSeremEsquivadas);
    return matchers.matches(requisicao);
  }
}

Here’s the EntryPoint:

@Component
public class EntryPoint implements AuthenticationEntryPoint {
  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse response,
                       AuthenticationException authException) throws IOException, ServletException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage());
  }
}

And here’s an example of Get and POST method:

@RestController
@RequestMapping(value = "/api/", produces = MediaType.APPLICATION_JSON_VALUE)
public class PublicController {
  @RequestMapping(method = GET, value = "/foo")
  public Map<String, String> getFoo() {
    Map<String, String> fooObj = new HashMap<>();
    fooObj.put("foo", "bar");
    return fooObj;
  }
  @RequestMapping(method = POST, value = "/foo")
  public Map<String, String> getFooPost() {
    Map<String, String> fooObj = new HashMap<>();
    fooObj.put("foo", "bar");
    return fooObj;
  }
}

What would cause this? Thanks!


WebSecurityConfigurer returns 401 on POST request, but works on GET Request Spring boot JWT
WebSecurityConfigurer returns 401 on POST request, but works on GET Request Spring boot JWT
test
{$excerpt:n}

Share This Post

Leave a Reply

Your email address will not be Publishedd. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Skip to toolbar