我正在開發一個春季啓動應用程序併爲用戶編寫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)需要被包含在安全配置。一旦這包括一切工作正常。
使用授權方法將角色分配給經過驗證的用戶 – Perry