【问题标题】:Spring Boot with Jersey basic authentication always 404带有 Jersey 基本身份验证的 Spring Boot 始终为 404
【发布时间】:2015-10-02 08:50:34
【问题描述】:

我尝试使用 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。

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

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

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

    场景是:

    1. 例如,您使用 curl 发送了请求
    2. Jersey 尝试处理您的请求,但出现 HTTP 错误 401 Unauthorized
    3. 现在 Spring MVC 尝试处理您的请求
    4. 但是你没有在 Spring MVC 中配置这个特定的上下文,所以出现了 Http Error 404 Not found

    这就是为什么你总是有这个 404。

    最简单的解决方案是在 application.properties 中添加属性

    server.servlet-path=/some_context_for_spring_mvc
    

    这使得 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 并不要替换它)。

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-04-25
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      • 2013-01-14
      • 2018-06-21
      相关资源
      最近更新 更多