带有Jersey基本身份验证的Spring Boot始终为404

时间:2015-10-02 08:50:35

标签: java spring spring-security spring-boot jersey-2.0

我尝试使用jersey和spring security创建一个SpringBoot应用程序。 我想使用基本身份验证来保护我的整个应用程序。 我的安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true,    prePostEnabled = true)
public class WebSerucityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic();
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.debug(true);
    }

    @Autowired(required = false)
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
            .withUser("user").password("password").roles("USER").and()
            .withUser("admin").password("password").roles("USER", "ADMIN");
    }
}

我的泽西控制器:

@Component
@Path("/")
public class Home {

    @GET
    @Produces("application/json")
    public String list() {
        String email = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return email;
    }
}

没有Spring安全性(如果我允许所有请求)应用程序控制器运行,但如果我启用httpBasic身份验证,我总是得到http 404。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

这是因为Jersey和Spring MVC映射到同一个地方 - 根目录" /"。

检查你的日志:Spring的Dispatcher Servlet在Jersey Servlet之后注册(在你的日志中检查ServletRegistrationBean短语)。

情景是:

  1. 您使用curl
  2. 发送了示例请求
  3. 泽西岛试图处理您的请求,但HTTP错误401未经授权出现
  4. 现在,Spring MVC试图处理您的请求
  5. 但是你还没有在Spring MVC中配置这个特定的上下文,所以没有找到Http Error 404
  6. 这就是为什么你总是这个404。

    最简单的解决方案是在application.properties

    中添加属性
    server.servlet-path=/some_context_for_spring_mvc
    

    这使泽西岛​​将被映射到root" /"但是Spring MVC到some_context_for_spring_mvc - 现在Jersey和Spring MVC之间的冲突消失了。

    有关Spring Boot中Spring MVC的更多详细信息,请访问:

    http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-switch-off-the-spring-mvc-dispatcherservlet

      

    Spring Boot希望提供来自应用程序根目录的所有内容。如果您希望将自己的servlet映射到该URL,则可以执行此操作,但当然您可能会丢失其他一些Boot MVC功能。要添加自己的servlet并将其映射到根资源,只需声明一个Servlet类型的@Bean,并为其指定特殊的bean名称dispatcherServlet(如果要关闭它,还可以创建具有该名称的不同类型的bean)不要替换它。)

    我希望这会有所帮助。

相关问题