Spring Security:hasRole 不起作用 & AuthenticaionPrincipal 为 null



我有一个PUT映射控制器方法,该方法应该限制为具有ROLE_BUYER角色的用户。但是,在测试期间,它向没有该角色的用户返回200 OK。控制器方法正在被调用,但是@AuthenticationPrincipalHttpServletRequest.getRemoteUser()都是null

控制器:

@PutMapping("{bookId}/borrow/{userId}")
public boolean borrowBook(@PathVariable("bookId") long bookId, @PathVariable("userId") long userId, @AuthenticationPrincipal(errorOnInvalidType=true) UserDetails user) {
return bookService.borrowBook(bookId,userId);
}

安全配置:

@EnableWebSecurity 
public class LibrarySecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers(HttpMethod.PUT,"/**").hasRole("LIBRARIAN")
.mvcMatchers(HttpMethod.GET,"/**").permitAll()
.and().csrf().disable();
}   
}

试验方法:

@Test
public void borrowBookwithNormalUser() throws Exception {
var userId = gilbert.getId();
assertThat(gilbert.getAuthorities().contains(new SimpleGrantedAuthority("ROLE_LIBRARIAN"))).isFalse();
mockMvc.perform(
MockMvcRequestBuilders
.put("/books/2/borrow/"+userId)
.with(SecurityMockMvcRequestPostProcessors.user(gilbert))
).andExpect(
MockMvcResultMatchers.status().isForbidden()
);
}

下面是测试设置:

@SpringBootTest
public class BookControllerTests {
@Autowired
private WebApplicationContext context;
@Autowired
private UserDetailsService uds;
private MockMvc mockMvc;
private LibraryUser gilbert;
@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.build();
gilbert = (LibraryUser)uds.loadUserByUsername("gilbert");
}

LibraryUser是实现UserDetails的实体。

@Entity
public class LibraryUser implements Serializable, UserDetails {
@Id
private long id;    
@Column(unique=true)
private String username
private String password;
private boolean library = false;
public Collection<? extends GrantedAuthority> getAuthorities() {
var res = new ArrayList<GrantedAuthority>();
res.add(new SimpleGrantedAuthority("ROLE_USER"));
if(librarian) {
res.add(new SimpleGrantedAuthority("ROLE_LIBRARIAN"));
}
return res;
}
}

WebSecurityConfigurerAdapter还是测试本身的问题?

感谢@Toerktumlare,我发现问题是在我的测试设置。缺少.apply(SecurityMockMvcConfigurers.springSecurity())。下面是完整的测试设置:

@BeforeEach
public void setup() {
mockMvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(SecurityMockMvcConfigurers.springSecurity())
.build();
gilbert = (LibraryUser)uds.loadUserByUsername("gilbert");
}

PS:不确定,如果这应该是一个编辑/评论/回答。

相关内容

  • 没有找到相关文章

最新更新