【发布时间】:2017-12-21 01:43:04
【问题描述】:
我正在开发一个 Spring Boot 应用程序并编写一个 API 供用户阅读消息。其中一个 URL 是:
/users/USER1/messages
现在,我显然只希望经过身份验证的用户能够访问此 get 请求的内容。但是所有经过身份验证的用户是不够的。我还希望只有拥有用户名的用户 - USER1 才能在此处查看真实内容,其余的应该收到 403 状态。我想出了如何在没有弹簧安全配置的情况下做到这一点(在我的服务中,我正在检查登录的用户名并将其与 URL 中的参数进行比较,只有在它们相等时才继续),但我认为应该有一个更简单的方法仅使用 SecurityConfiguration?我当前的配置如下所示:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/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 的消息)。这是我的控制器,我在其中添加了 PreAuthorize 注释
@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:与接受答案中的 cmets 一样,@EnableGlobalMethodSecurity(prePostEnabled=true) 需要包含在安全配置中。一旦包含在内,一切正常。
【问题讨论】:
-
使用将角色分配给经过身份验证的用户的授权方法
标签: java spring spring-mvc spring-boot spring-security