K
K
Kirill Batalin2017-08-11 13:12:31
Java
Kirill Batalin, 2017-08-11 13:12:31

Spring Security: How to allow access to unauthorized clients?

On REST, only a few methods require the user to be authorized. The remaining methods should be available to everyone .
For authorization, I wrote a custom filter inherited from AbstractAuthenticationProcessingFilter. The filter processes all requests coming to REST. If there is no token in the request, then attemptAuthenticationreturns

SecurityContextHolder.getContext().getAuthentication();

To be precise, AnonymousAuthenticationToken
how should HttpSecurity be configured so that all users have access to all REST methods? Other than methods marked with @Secured
The implementation of attemptAuthentication in my filter is:
@Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response)
            throws AuthenticationException, IOException, ServletException {
        String token = request.getHeader(HEADER_TOKEN);
        if (token == null) {
            return SecurityContextHolder.getContext().getAuthentication();
        }

        TokenAuthentication authentication = new TokenAuthentication(token);
        return getAuthenticationManager().authenticate(authentication);
    }

Current setup that doesn't work:
@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .anyRequest()
                    .permitAll()
            .and()
                .httpBasic()
                .authenticationEntryPoint(entryPoint);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Batalin, 2017-08-11
@kir55rus

I solved the problem by setting the filter flag continueChainBeforeSuccessfulAuthentication = true

V
Vladimir Rozhkov, 2017-08-11
@r0zh0k

Write a matcher for everything and allow it to everyone. Close the necessary endpoints, for example:

@Override
    protected void configure(final HttpSecurity http) throws Exception {
        http
            .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .csrf().disable()
            .exceptionHandling().and()
            .anonymous().and()
            .servletApi().and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/api/**").permitAll()
            .antMatchers(HttpMethod.POST, "/api/**").permitAll()
            .anyRequest().authenticated().and()
            .addFilterBefore(
                    new AuthFilter(),
                    UsernamePasswordAuthenticationFilter.class
            );
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question