2017-04-15 41 views
2

我是Spring的新用戶,我需要爲我的其餘控制器的8/10 URL啓用基本身份驗證,其他2應該可以在沒有任何基本身份驗證的情況下訪問。 我正在使用gradle來構建應用程序,因此沒有涉及這樣的xml文件。 (我看到了一個web.xml的幾個解決方案,我沒有一個) 這裏是我的web安全配置:禁用特定URL的基本身份驗證彈簧

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    public void configure(WebSecurity web) throws Exception { 
     super.configure(web); 
     web.ignoring().antMatchers("/abcd/**"); 

    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication().withUser("user").password("password"); 

    } 
} 

這裏是我的控制器:

@RestController 
@RequestMapping(value = "/abcd") 
public class PaymentController implements ElasticSearchConstants { 

    @RequestMapping(value = "/sample", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE) 
    public static void authExpemtedController(HttpServletRequest request, HttpServletResponse response) throws Exception { 
     //do something 
    } 
} 

我試過網絡。忽略()antMatchers( 「/ ABCD /」);沒有幫助。我總是得到一個401錯誤,當我從郵遞員嘗試:​​ { 「時間戳」:1492274727955, 「狀態」:401, 「錯誤」:「未授權」, 「消息」:「全認證訪問,這是必需的資源」, ‘路徑’:‘/ ABCD /樣本’ }

我有一個要求揭露像這樣的API,不需要任何身份驗證,在與其他的API需要被authernticated。

感謝您的幫助提前

更新: 我瞭解http.authoriseRequest()antMatchers( 「/ ABCD」)permitAll() 這種方法只允許任何用戶訪問。我不想將任何用戶信息都傳遞給此API。

回答

2

你可能要參考Section 5.4 Authorize Requests of the Spring Security docs

我們的例子只要求用戶進行身份驗證,並已經這樣做對我們的應用程序的每個URL。我們可以通過向我們的http.authorizeRequests()方法添加多個子項來爲我們的URL指定自定義需求。例如:

protected void configure(HttpSecurity http) throws Exception { 
    http 
     .authorizeRequests()                      
      .antMatchers("/resources/**", "/signup", "/about").permitAll()         
      .antMatchers("/admin/**").hasRole("ADMIN")             
      .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")       
      .anyRequest().authenticated() 
      .and() 
     // ... 
     .formLogin(); 
} 
+0

我已經試過這個選項,但沒有工作。仍然遇到同樣的問題。我已經給HTTP \t .authorizeRequests() \t .antMatchers( 「/ ABCD/**」)permitAll() \t \t .anyRequest()認證()。; – Gaurav