Spring Security ignore URL for filter

Viewed 170

I have a custom filter that extends AbstractAuthenticationProcessingFilter and dont want to call it on all pages. For example I want to ignore /login. I added it to my web.ignoring but it is not ignoring anything. Here I have read that the security system does execute the filter but ignores if the request is blocked. But my filter gets called and blocks all requests.

SecurityConfig

@Configuration
@EnableWebSecurity

public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Autowired
private JwtAuthenticationProvider authenticationProvider;

@Autowired
protected JwtAccessDeniedHandler accessDeniedHandler;

@Autowired
protected JwtAuthenticationFailureHandler authenticationFailureHandler;

@Bean
@Override
public AuthenticationManager authenticationManager() throws Exception {
    return new ProviderManager(Arrays.asList(authenticationProvider));
}

@Override
public void configure(WebSecurity web) {
    web.ignoring()
            .antMatchers("/")
            .antMatchers("/api/login")
            .antMatchers("/api/register")
            .antMatchers("/api/contacts/**");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .csrf().disable()
            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
            .and()
            .exceptionHandling().accessDeniedHandler(accessDeniedHandler)
            .and()
            .authorizeRequests().anyRequest().hasRole("ADMIN")
            .and()

            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); 
    http
            .addFilterBefore(getNewFilter(), UsernamePasswordAuthenticationFilter.class);


}
public JwtAuthenticationFilter getNewFilter() throws Exception {
    JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter();
    authenticationTokenFilter.setAuthenticationManager(authenticationManager());
    authenticationTokenFilter.setAuthenticationSuccessHandler(new JwtAuthenticationSuccessHandler());
    authenticationTokenFilter.setAuthenticationFailureHandler(authenticationFailureHandler);
    return authenticationTokenFilter;
}
}

JwtAuthenticationFilter

public class JwtAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
public JwtAuthenticationFilter() {
    super("/**"); // I tried changing this but I don't see a difference
}

@Override
protected boolean requiresAuthentication(HttpServletRequest request, HttpServletResponse response) {
    return true;
}

@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    System.out.println("Attempt Authentication");
    Cookie cookie = WebUtils.getCookie(request, "auth");
    if (cookie == null || cookie.getValue() == null) {
        System.out.println("No Jwt Token existing");
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = cookie.getValue();
    JwtAuthenticationToken authRequest = new JwtAuthenticationToken(authToken);
    System.out.println("AuthRequest Created");
    return getAuthenticationManager().authenticate(authRequest);
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult)
        throws IOException, ServletException {
    super.successfulAuthentication(request, response, chain, authResult);
    System.out.println("successful authentication");
    chain.doFilter(request, response);
}
}

JwtAuthenticationProvider

@Component
public class JwtAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {

@Autowired
AccountToContactService accountToContactService;

public static final String schoolAbbreviation = "stg";

@Override
public boolean supports(Class<?> authentication) {
    return (JwtAuthenticationToken.class.isAssignableFrom(authentication));
}

@Override
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    System.out.println("AdditionalChecks");
}

@Override
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
    JwtAuthenticationToken jwtAuthenticationToken = (JwtAuthenticationToken) authentication;
    String tokenString = jwtAuthenticationToken.getToken();
    System.out.println("retrieveUser");
    JwtToken token = JwtToken.readToken(tokenString);

    if (token == null) {
        throw new JwtInvalidTokenException("Token could not be parsed.");
    }
    JwtClaims<?> claims = token.getClaims();

    ZonedDateTime expiration = claims.getExpiration();

    Long accountId = claims.getAid();
    String roles = claims.getRole();

    if (expiration.isAfter(ZonedDateTime.now())) {
        throw new JwtTokenExpiredException("Given JWT Token is expired. Login to get a new one");
    }

    boolean isTeacher;
    Long contactId;

    ContactInformation contactInformation = claims.getContactInformation(schoolAbbreviation);
    if (contactInformation == null) {
        AccountToContact accountToContact = accountToContactService.findByAccountId(accountId).orElseThrow(NoContactForAccountException::new);
        isTeacher = accountToContact.getContact().isTeacher();
        contactId = accountToContact.getId().getContactId();
        System.out.println("Contactinformation is null");
    } else {
        isTeacher = contactInformation.isTch();
        contactId = contactInformation.getId();
        System.out.println("Contactinformation is not null");
    }
    if (isTeacher) {
        roles = roles + ",ROLE_TEACHER";
    }

    List<GrantedAuthority> authorityList = AuthorityUtils.commaSeparatedStringToAuthorityList(roles);

    for (GrantedAuthority auth : authorityList) {
        System.out.println("Authority: " + auth.getAuthority());
    }
    AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN"));
    return new AuthenticatedUser(contactId, "USERNAME", authorityList);
}

protected void updateJwtToken(String schoolAbbreviation, ContactInformation info, JwtToken token, HttpServletResponse response) {
    token.getClaims().setContactInformation(schoolAbbreviation, info);

    ZonedDateTime currentTime = ZonedDateTime.now().withZoneSameInstant(ZoneId.of("UTC"));
    token.getClaims().setIssuedAt(currentTime).setExpiration(currentTime.plusMinutes(120));

    String tokenString = token.build();

    //Own Cookie
    Cookie cookie = new Cookie();
    cookie.setToken(tokenString);
    cookie.setMaxAge(120*60);

    response.setHeader("Set-Cookie", cookie.toString());
}
}

I am not really confident with the security system and got a lot from this website. Hopefully somebody can tell me how to ignore URLs in the filter. Thanks in advance!

1 Answers

Try adding this in security config class :

    @Override
    public void configure(final WebSecurity webSecurity) {
    webSecurity.ignoring().antMatchers("{endpoint}");
    }
Related