2017-07-28 84 views
1

我有一個基於Spring-Boot 1.5.4.RELEASE和spring-boot-starter-security的基於REST的微服務。該服務沒有網頁,只有JSON進出。用戶名和密碼在application.properties文件中配置。隨着信貸http://ryanjbaxter.com/2015/01/06/securing-rest-apis-with-spring-boot/以下配置導致服務器實現基本的HTTP認證相當不錯,它接受的憑據,拒絕未經授權的請求:Spring-Boot REST服務基本http認證排除一個端點

import org.springframework.context.annotation.Configuration; 
import org.springframework.security.config.annotation.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 

@Configuration 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.csrf().disable().authorizeRequests() // 
       .anyRequest().authenticated().and().httpBasic();   
    } 
} 

我的問題是,我想排除一個小OLE路徑,一個來自基本的HTTP認證。從瘋狂的谷歌搜索和SO複製粘貼我修改了上面有這樣的:

http.csrf().disable().authorizeRequests() // 
     .antMatchers("/healthcheck").permitAll() 
     .anyRequest().authenticated().and().httpBasic(); 

這編譯和無預警運行,但該路徑不是爲未經驗證的訪問打開。我仍然必須提供憑據來檢查服務的健康狀況。

我必須一一匹配路徑嗎?我的小健康檢查終端位於上下文路徑的基礎上,以及其他許多終端 - 逐個添加路徑將是一件麻煩事。

我application.properties文件的相關部分是:

security.user.name = web-user 
security.user.password = web-pass 
management.security.roles=SUPERUSER 

也許我需要以某種方式擺弄角色?

請幫助,在此先感謝。

更新1:

路徑信息 - 我想這條道路(以及更多的根)來加以防護:

localhost:8081/abcd/user 

而且我想只有這一條路徑是開放的沒有身份驗證要求:

localhost:8081/abcd/healthcheck 

更新2:看起來像我主要是複製這個3歲的問題,但沒有答案被接受在那裏我的問題:

spring-boot setup basic auth on a single web app path?

+0

你能發佈完整的url請求,產生問題? – efekctive

+0

看這裏:https:// stackoverflow。com/questions/24696717/spring-security-permitall-not-allowed-anonymous-access – JavaBoy

+0

/healhtcheck不是/ abcd/healthcheck – efekctive

回答

0

你說你的鏈接看起來像:

localhost:8081/abcd/healthcheck 

試試這個:

http.csrf().disable().authorizeRequests() // 
    .antMatchers("/abcd/healthcheck").permitAll() 
    .anyRequest().authenticated().and().httpBasic(); 
+0

謝謝@JavaBoy非常快速的答覆,但沒有喜悅..我使用了代碼,測試過通過在不提供憑證的情況下使用curl請求該端點;答覆是401未經授權。 – chrisinmtown

+0

你有沒有在你的課堂上使用過@EnableWebSecurity? https://github.com/spring-projects/spring-boot/issues/8646 – JavaBoy

+0

無論WebSecurityConfigurerAdapter類中是否存在@EnableWebSecurity批註,我都會看到相同的行爲。 – chrisinmtown

1

好以後更多的實驗,我發現了以下工作 - @efekctive請注意,健康檢查上沒有上下文前綴:

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http.csrf().disable().authorizeRequests() 
    .antMatchers("/healthcheck").permitAll() 
    .antMatchers("/**").authenticated().and().httpBasic(); 
} 

需要注意的一點是:當我發佈這個消息時,我通過使用BOGUS http憑據調用curl來測試healthcheck終結點,期待Spring忽略它們,但是Spring總是回答401未經授權的問題。正確的測試是使用NO http證書調用curl,然後健康檢查終端非常高興地回答。