此问题已在此处有答案:
Springboot Security hasRole not working(3个答案)
2天前关闭。
我对springframework和 Boot 有经验,但对Spring Security 没有太多经验。
我有一个正在运行的测试,但失败测试成功。
我列出了:
- 服务 * 以防我错过了什么
- 安全配置,以防我已经borked那
- 测试用例本身,虽然它很简单
- maven依赖项,以防缺少启动器
售后服务:
@Service
public class BuildingService {
private final BuildingRepository repo;
public BuildingService(final BuildingRepository repo) {
this.repo = repo;
}
@Secured({RolesConst.MANAGING_AGENT, RolesConst.BACK_OFFICE})
public Page<Building> getAll(final Pageable pageable) {
return repo.findAll(pageable);
}
@Secured({RolesConst.MANAGING_AGENT, RolesConst.BACK_OFFICE})
public Optional<Building> getById(final String id) {
return repo.findById(id);
}
@Secured({RolesConst.MANAGING_AGENT, RolesConst.BACK_OFFICE})
public Building save(final Building building) {
return repo.save(building);
}
}
Spring安全配置:
@Configuration
@EnableMethodSecurity(prePostEnabled = true)
public class ServiceConfiguration {
@Bean
public MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
return new MongoTransactionManager(dbFactory);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeHttpRequests((authz) -> authz
.anyRequest().authenticated())
.httpBasic();
return http.build();
}
}
测试:
@Test
@WithMockUser(username = "bob", password = "password", authorities = {"TENANT"})
public void givenValidTent_whenAccessRestrictedResource_thenFailWith401() throws Exception {
final ClassPathResource resource = new ClassPathResource("payloads/successful-create-building.json");
final String payload = Files.readString(Path.of(resource.getURI()));
// Create building
mvc.perform(post("/building")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.content(payload))
.andExpect(status().isUnauthorized());
}
POM测试部门:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>mongodb</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<scope>test</scope>
</dependency>
编辑1:
- Spring Boot 3.0.5
- Java 20
编辑二:
已尝试将以下内容添加到测试用例,但仍失败
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@BeforeEach
public void setup() {
mvc = MockMvcBuilders.webAppContextSetup(context)
.apply(springSecurity())
.build();
}
1条答案
按热度按时间6mzjoqzu1#
配置很好,但是我在RoleConst中的值是:ROLE_MA,所以我需要使用 hasAnyAuthority 而不是anyRole