2017-07-16 121 views
0

我正在開發一個春季啓動應用程序併爲用戶編寫API以便能夠閱讀消息。其中一個網址是:春季安全只允許訪問具有特定用戶名的用戶

/users/USER1/messages 

現在,我顯然希望只有經過身份驗證的用戶才能訪問此獲取請求的內容。但所有認證的用戶是不夠的。我也希望只有擁有用戶名USER1的用戶才能在這裏查看真實內容,休息時應該接收403個狀態。我想如何在沒有spring安全配置的情況下做到這一點(在我的服務中,我正在檢查登錄的用戶名並將其與URL中的參數進行比較,只有在它們相等時才進行),但我認爲應該有一個更簡單的方法只使用SecurityConfiguration?我現在的配置是這樣的:

@Configuration 
@EnableWebSecurity 
public class SecurityConfiguration extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http.authorizeRequests() 
      .antMatchers(HttpMethod.GET, "https://stackoverflow.com/users/**").authenticated() 
      .antMatchers("/h2-console/*").permitAll() 
       .anyRequest().authenticated() 
      .and() 
       .formLogin(); 

     http.csrf().disable(); 
     http.headers().frameOptions().disable(); 
    } 

    @Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth.inMemoryAuthentication() 
       .withUser("superman").password("superman").roles("USER") 
       .and() 
       .withUser("admin").password("admin").roles("ADMIN"); 
    } 
} 

編輯:以下的答案提示方法安全表達式我已經用它,但它似乎仍然沒有工作(如果我鑑定爲USER2我仍然可以讀取消息USER1)。這裏是我的控制器,我已經添加預授權註釋

@RequestMapping(method = RequestMethod.GET, value = "/messages", produces = {"application/json"}) 
@ResponseBody 
@PreAuthorize("#userHandle == authentication.name") 
public List<Message> getMessages(@PathVariable("userHandle") String userHandle, 
         @RequestParam(value="search", defaultValue="") String search) { 
    //todo: change to return DTO not model 
    return messageFacade.getMessages(userHandle, search); 
} 

EDIT2:如在接受的答案@EnableGlobalMethodSecurity評論(prePostEnabled = TRUE)需要被包含在安全配置。一旦這包括一切工作正常。

+0

使用授權方法將角色分配給經過驗證的用戶 – Perry

回答

3

我覺得你需要彈簧Method Security。在本細則的例子是幾乎從字面上你的情況:

import org.springframework.data.repository.query.Param; 

... 

@PreAuthorize("#n == authentication.name") 
Contact findContactByName(@Param("n") String name); 

PS:不要忘記@EnableGlobalMethodSecurity!查看教程here

+0

非常感謝!在我的搜索谷歌彈出唯一的事情是「確保春季啓動應用程序」,這並沒有觸及!現在就來看看! –

+0

使用你的建議,但悲傷沒有效果。爲了清晰起見,我包含了控制器。 –

+2

你有'@ EnableGlobalMethodSecurity'? –