Spring Security 401 Unauthorized access to an insecure endpoint

I am trying to configure Spring Security on a Spring boot application as follows:

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

@Autowired
private RestAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
    JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter();
    authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
    return authenticationTokenFilter;
}

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

    //@formatter:off
     httpSecurity
      .csrf()
        .disable()
      .exceptionHandling()
        .authenticationEntryPoint(this.unauthorizedHandler)
        .and()
      .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
      .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .antMatchers("/login", "/singup", "/subscribers").permitAll()
        .anyRequest().authenticated();

        // Custom JWT based security filter 
    httpSecurity            
        .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);   

    //@formatter:on

}
}

My unauthorized Handler:

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {

private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

}

Finally, a REST controller for / subscribers:

@RestController
public class SubscriberRestController {

@Autowired
ISubscribersService subscribersService;

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.GET)
@ResponseBody
public Number subscriberCount() {

    return subscribersService.subscribersCount();
}

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.POST)
public String subscriberPost(@RequestBody SubscriberDocument subscriberDocument) {

    return subscribersService.subscribersInsert(subscriberDocument);
}

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test() {

    return "This is a test";
}

}

I use postman to test the endpoints, and when I do POST for "localhost: 8080 / subscribers", I get:

Postman result

I want open endpoints (/ subscribers) without security checks or credentials, login and logon endpoints, and secure endpoints for authenticated users.

Thank!:)

+4
source share
2 answers

Spring Boot , . Application.java @ComponentScan.

0

:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
@ComponentScan(basePackages = { PackageConstants.PACKAGE_CONTROLLERS_REST, PackageConstants.PACKAGE_SERVICES,
        PackageConstants.PACKAGE_SERVICES_IMPL, PackageConstants.PACKAGE_MONGO_REPOSITORIES,
        PackageConstants.PACKAGE_MONGO_REPOSITORIES_IMPL, PackageConstants.PACKAGE_UTILS })
public class Application {

    // Clase principal que se ejecuta en el bootrun

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) , Spring AutoConfiguration Boot Security. , Spring Spring Security. , Initializer Root Config, ApplicationConfiguration SpringBoot. - :

ApplicationConfig:

@Configuration
@EnableWebMvc
@ComponentScan("com.trueport.*")
@PropertySource("classpath:app.properties")
public class ApplicationConfig extends WebMvcConfigurerAdapter {
    ....
}

ApplicationSecurityConfig:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter {
    ....
}

Initializer:

public class Initializer implements WebApplicationInitializer {

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher";

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        ....
        DispatcherServlet dispatcherServlet = new DispatcherServlet(ctx);
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
        ctx.register(ApplicationConfig.class);
        ServletRegistration.Dynamic servlet =     servletContext.addServlet(DISPATCHER_SERVLET_NAME,
            dispatcherServlet);
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        servlet.setAsyncSupported(true);
    }
}
-1

Source: https://habr.com/ru/post/1663443/


All Articles