我正在开发一个春季启动应用程序并为用户编写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