0

我開發了一個使用Spring Boot的REST風格的Web服務。一旦輸入一個URL,就會返回一個JSON資源。服務器端並不完美JSON API符合,但它的工作原理。安全的Restful Spring啓動應用程序

現在我想用簡單的HTTP基本認證保護RESTful服務。簡單地說,如果一個客戶端,以便發送一個HTTP GET訪問

http://mycompany.com/restful/xyz 

會收到一個HTTP錯誤未認證的,除非請求配置適當Authorization basic XXXXXXXX。 xxxxxx是用戶的加密形式:pwd

我想用Spring Security來做。一些谷歌搜索後,我可能需要創建一些類,如:

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 
    @Autowired 
    public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception { 
    .... 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     .... 
    } 
} 

有兩件事情我需要了解:

  1. 大多數Spring Security的樣品,我發現使用Spring MVC以某種方式與Web應用程序,但我確信它可以用在上面所示的場景中 - 獨立的Web服務(在Tomcat中沒有問題,但不是Web應用程序);

  2. 任何人都可以顯示在這兩種方法高於工作,只有某些用戶/密碼被允許在過濾器傳遞到資源的效果一些代碼段,

    http://mycompany.com/restful/xyz 
    

    否則HTTP認證錯誤代碼返回。

任何人都可以幫忙嗎?

回答

0

你可以有這樣的事情:

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests().antMatchers("/restful/**").hasRole("ROLE_USER").and().httpBasic(); 
    } 

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication().withUser("john").password("mypass").roles("ROLE_USER"); 
    } 
} 
+0

謝謝你,就像一個魅力 –