【发布时间】:2020-09-28 01:56:57
【问题描述】:
我有一个使用 Java Spring MVC 构建的 Web 应用程序,并使用 Spring Security 进行登录。登录/注销效果很好。有两个用户角色“ROLE_ADMIN”和“ROLE_USER”。
我想确保我的方法 userService.createUser(username) 只能由具有“ROLE_ADMIN”角色的用户访问。
我像这样添加了@PreAuthorize 注释...
public class UserServiceImpl implements UserService {
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Integer createUser(String username) throws Exception {
/* .... */
}
/* ... */
}
...但这并不能阻止只有“ROLE_USER”的登录用户创建用户。
我在 Google 上搜索并阅读了注释 @EnableGlobalMethodSecurity,但我不知道它的去向。
我是否用它来注释我的 UserService 类?或者,WebController?还是两者兼有?
请帮忙,因为我真的可以使用一些建议!
【问题讨论】:
-
@EnableGlobalMethodSecurity是一个配置,它与任何@Configuration注释类一起使用。@Configuration更贴切,尽管它适用于@Component或其专业。 Example -
谢谢!按照示例链接中的示例代码进行操作,它可以工作!我将发布解决方案作为答案。干杯!
标签: spring spring-mvc spring-security