title: Adding custom filter that add request headers in spring security
body: <p>I was using spring security to handle authentication via jwt that is passed in the request`s header:</p>
  <pre><code>public class JwtAuthConfig extends WebSecurityConfigurerAdapter {
  
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http.sessionManagement()
                  .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                  .authorizeRequests()
                  .anyRequest().authenticated().and()
                  .oauth2ResourceServer().jwt();
      }
  
  }
  </code></pre>
  <p>Now the JWT token is passed to my application in a cookie. I wrote a filter that takes the jwt from the cookie and adds it to the request`s header :</p>
  <pre><code>@Component
  public class JwtCookieFilter implements Filter {
      
      @Override
      public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
          HttpServletRequest request = (HttpServletRequest) req;
          HttpServletResponse response = (HttpServletResponse)res;
          Cookie[] cookies = request.getCookies();
          String jwt = this.getTokenFromCookie(cookies); // Inner method 
          if(jwt == null)
          {
              response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
              return;
          }
          HttpRequestWithHeaders requestWithHeaders = new HttpRequestWithHeaders (request);
          HttpRequestWithHeaders .addHeader(&quot;Authorization&quot;,jwt);
          chain.doFilter(requestWithHeaders, response);
      }
  </code></pre>
  <p>Now I'm not sure after what step my filter should run (configure method in springSecurity). I tried using the following but I keep getting 401 error (Unathorized) :</p>
  <pre><code>http.addFilterBefore(new JwtCookieFilter(), UsernamePasswordAuthenticationFilter.class);
  </code></pre>