我正在使用 spring OAuth2 和 JWT 令牌来保护应用程序。我正在延长org.springframework.security.core.userdetails为了向令牌添加一些附加属性,然后可以使用这些属性来执行授权,调用端点。
public class CustomUser extends User {
private Set<String> bookIds;
public CustomUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
}
}
我还有 org.springframework.security.access.PermissionEvaluator 的自定义实现,它能够反序列化令牌并检查自定义属性是否是其中的一部分,可以将其添加到控制器端点。
@PreAuthorize("hasPermission(authentication, #bookId,'read')")
现在一切正常,我可以通过邮递员测试我的应用程序,并且只有具有有效 JWT 令牌且其 bookIds 集的 URL 部分中包含 bookID 的用户才能访问该资源
@PreAuthorize("hasPermission(authentication, #bookId,'read')")
@GetMapping(value = "api/books/{bookId}")
public Book getBook(@PathVariable String bookId) {}
然而,我正在努力测试它,因为这是微服务应用程序的一部分,其中身份验证和服务不属于同一项目,并且将在单独的虚拟机上运行。理想情况下,我希望能够模拟每个服务中的令牌,并在此 bookId 集中添加我需要的任何值。
我知道在 spring 4 之后我们可以使用 @WithMockUser,但是,据我所知,这仅限于用户名/密码/角色/权限,例如:
@WithMockUser(username = "ram", roles={"ADMIN"})
我真正想做的是扩展此注释以支持我的自定义属性“bookId”或在其中注入模拟集的方法。这是否可能,如果不可能,我的替代方案是什么,因为我无法在单元测试中调用我的身份验证提供程序,因为该实现将存在于托管在单独应用程序上的另一个 spring 上下文中。
提前谢谢了 !