Home > Software design >  Spring Security does not skip the url
Spring Security does not skip the url

Time:06-18

I go to the url /admin/users/refreshToken and get forbidden. Although I added a pass in the filter and it works fine. What's the trouble?

protected void configure(HttpSecurity http) throws Exception {
           http.csrf().disable();
           http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
           http.authorizeRequests().antMatchers(
                   "/admin/**").authenticated()
                   .anyRequest().permitAll();
           http.addFilter(new CustomAuthenticationFilter(authenticationManagerBean()));
           http.addFilterBefore(new CustomAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class);
        }

public class CustomAuthorizationFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getServletPath().equals("/login") || request.getServletPath().equals("/admin/users/refreshToken")) {
            filterChain.doFilter(request, response);
        } else {
            String authorizationHeader = request.getHeader(AUTHORIZATION);
            ............
        }
    }

CodePudding user response:

You need to add http.authorizeRequests().antMatchers("/admin/users/refreshToken").permitAll()

CodePudding user response:

Grekier already provided a solution for your Problem but i will explain it further so you understand whats going on.

  1. Wenn configuring url paths you want to allow or authenticate with HttpSecurity you have to imagine it as a long chain of if Statements. What you have is " if any request matches admin/** url it needs to be authenticated ". As soon as one of theses "if statements" evaluates to true all following ones are ignored. So as far as Spring knows you want "/admin/users/refreshToken" to be an authenticated route. So you have to do as Grekier already suggested and add a more specifc "if statement" before your "authorizeRequests().antMatchers( "/admin/**").authenticated()"

  2. The second thing i would recommend to change is removing the Hardcoded Urls in the Filter. Instead of checking for the Url you can check if an Authorization header is present and if not continue the Filter Chain.

  • Related