Spring安全性401未经安全的端点

时间:2016-12-11 12:07:46

标签: java spring spring-boot spring-security postman

我正在尝试在Spring Boot应用程序上配置Spring Security,如下所示:

@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

}
}

我的unknownHandler是:

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

}

最后,/ subscriber的REST控制器是:

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

}

我使用postman来测试端点,当我对“localhost:8080 / subscriber”进行POST时,我得到:

Postman result

我希望在没有任何安全控制或凭据检查的情况下打开端点(/订阅者),为已认证用户打开单点和登录端点以及安全端点。

谢谢! :)

3 个答案:

答案 0 :(得分:1)

您需要在配置方法中添加以下内容/ error是由于任何异常导致应用程序发生错误时的默认回退,并且默认情况下受保护。

protected void configure(HttpSecurity httpSecurity) throws Exception {
//disable CRSF
httpSecurity
        //no authentication needed for these context paths
        .authorizeRequests()
        .antMatchers("/error").permitAll()
        .antMatchers("/error/**").permitAll()
        .antMatchers("/your Urls that dosen't need security/**").permitAll()

下面的代码段

     @Override
       public void configure(WebSecurity webSecurity) throws Exception
         {
          webSecurity
          .ignoring()
           // All of Spring Security will ignore the requests
           .antMatchers("/error/**")
          }  

现在,当allowAll Urls发生异常时,您将不会获得401并获得500异常的详细信息

答案 1 :(得分:0)

Spring Boot没有应用配置,因为找不到它。在 Application.java 配置包中未包含@ComponentScan anotation。

答案 2 :(得分:-1)

经过一番研究,这里有解决方案:

@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 Boot Security AutoConfiguration配置。它不是完整的答案,因为现在你必须告诉Spring用户你的Spring Security配置类。另外,我建议您使用init Root Config Classes创建Initializer类,使用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 {
    ....
}

初​​始化器:

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