簡體   English   中英

在Spring Security中將HttpBasic和FormLogin與Spring-boot-starter混合使用

[英]Mix HttpBasic and FormLogin in Spring Security with Spring-boot-starter

我使用具有彈簧安全性的spring-boot-starter 0.5.0.M6構建包含以下內容的應用程序:

  1. “ / admin / ” **:具有ADMIN角色,基於表單的登錄名的任何人都應該可以訪問
  2. “ / api / ” **:具有角色API,http基本登錄名的任何人都應該可以訪問

我的第一次嘗試是:

@Override
protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
          .antMatchers("/resources/**").permitAll()
          .antMatchers("/admin/**").hasRole("ADMIN")
        .and()
          .formLogin()
          .defaultSuccessUrl("/admin/home")
          .loginPage("/login")
          .permitAll()
        .and()
          .logout()
          .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
          .permitAll();  
      http
        .authorizeRequests()
          .antMatchers("/api/**").hasRole("API")
        .and()
          .httpBasic();
}

使用這種方法:

  1. 所有的“ / admin / ”和“ / api / ”都可以使用基本和基於表單的身份驗證進行身份驗證。 這不是關鍵問題。
  2. 當發生任何安全問題(例如:身份驗證失敗或授權失敗)時,將顯示登錄表單。 這是一個關鍵問題,如果/ api / **獲得身份驗證失敗或授權失敗,我希望它顯示帶有401/403狀態碼的基本身份驗證彈出窗口。

然后我嘗試使用https://github.com/spring-projects/spring-security-javaconfig/blob/master/samples-web.md#sample-multi-http-web-configuration的解決方案,但我只能保護/api/**/admin/**但不能同時保護二者,取決於我使用@Order注釋的哪個。

請幫我一下。

非常感謝

對於您的api部分,請使用以下內容。 請注意,第一個螞蟻匹配器限制了此安全配置過濾的內容的范圍。 那是我起初從您的參考文獻中不了解的部分。

@Configuration
@Order(1)
public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        // the ant matcher is what limits the scope of this configuration.
        http.antMatcher("/api/**").authorizeRequests()
            .antMatchers("/api/**").authenticated()
            .and().httpBasic().realmName("Sourcing API");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM