簡體   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