繁体   English   中英

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

[英]Spring Boot with Jersey basic authentication always 404

我尝试使用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");
    }
}

我的泽西岛控制器:

@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。

任何想法?

这是因为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

这使得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,也可以使用该名称)而不是更换它)。

我希望这有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM