【问题标题】:Why is `@PreAuthorize` not protecting my service method?为什么`@PreAuthorize` 不保护我的服务方法?
【发布时间】: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


【解决方案1】:

解决方案,感谢@R.G提供的链接...

我像这样将@EnableGlobalMethodSecurity(prePostEnabled=true) 添加到我的配置类中......

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled=true)
public class AppConfig {
    /* ... */
}

然后我将@PreAuthorize添加到界面中的方法中,就像这样......

public interface UserService {

    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Integer createUser(String username) throws Exception;

}

有效!谢谢!

【讨论】:

    猜你喜欢
    • 2011-06-28
    • 1970-01-01
    • 2011-01-17
    • 2014-10-09
    • 2015-01-16
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-25
    相关资源
    最近更新 更多