Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring security 401 Unauthorized on unsecured endpoint

I'm 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 unauthorizedHandler is:

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, the REST controller for /subscribers is:

@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 endpoints and when I do a POST to "localhost:8080/subscribers", I get:

Postman result

I want to have opened endpoints (/subscribers) without any security control or credentials check, endpoints for singup and login and secured endpoints for authenticated users.

Thanks! :)

like image 635
Samuel Fraga Mateos Avatar asked Dec 11 '16 12:12

Samuel Fraga Mateos


2 Answers

Spring Boot was not applying the configuration because couldn't find it. On Application.java config package was not included with @ComponentScan anotation.

like image 147
Samuel Fraga Mateos Avatar answered Oct 05 '22 06:10

Samuel Fraga Mateos


After some researching, here is solution:

@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);
    }
}

Main line is @SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) it tells not use Spring Boot Security AutoConfiguration configuration. It is not full answer, because now you have to tell Spring user your Spring Security configuration class. Also i advice you to create Initializer class with init Root Config Classes, ApplicationConfiguration using and refuse to use SpringBoot applications. Something like this:

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);
    }
}
like image 35
dikkini Avatar answered Oct 05 '22 05:10

dikkini