带有Jersey基本身份验证的Spring Boot总是404

b0c*_*0c1 2 java spring spring-security jersey-2.0 spring-boot

我尝试使用jersey和spring安全性创建一个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");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的泽西岛控制器:

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

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

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

任何的想法?

小智 5

这是因为Jersey和Spring MVC映射到同一位置-根上下文“ /”。

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

场景是:

  1. 您使用例如curl发送了请求
  2. 泽西岛试图处理您的请求,但出现HTTP错误401未经授权
  3. 现在,Spring MVC尝试处理您的请求
  4. 但是您尚未在Spring MVC中配置此特定上下文,因此出现Http错误404找不到

这就是为什么您始终使用此404。

最简单的解决方案是在应用程序中添加属性。

server.servlet-path=/some_context_for_spring_mvc
Run Code Online (Sandbox Code Playgroud)

这使得Jersey将映射到根目录“ /”,但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,然后将其关闭。而不是更换它)。

我希望这有帮助。