Spring Security 为什么`@PreAuthorize`不保护我的服务方法?

pbwdgjma  于 2023-04-12  发布在  Spring
关注(0)|答案(2)|浏览(181)

我有一个用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”的登录用户创建用户。
我在谷歌上搜索并阅读了注解@EnableGlobalMethodSecurity,但我不知道它在哪里。
我应该用它来注解我的UserService类吗?或者,WebController?或者两者都用?
请帮助我,因为我真的需要一些建议!

ih99xse1

ih99xse11#

该解决方案,感谢@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;

}

很好!谢谢!

lymnna71

lymnna712#

EnableGlobalMethodSecurity已被弃用并被EnableMethodSecurity取代,默认情况下prePostEnabledtrue

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;

@SpringBootApplication
@EnableMethodSecurity
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication, args);
    }
}

相关问题