DAr*_*rkO 3 spring-security spring-boot spring-security-oauth2 spring-webflux
我对 Spring 生态系统和 Webflux 都很陌生。我试图弄清楚两件事,但找不到任何具体细节。
我的设置:
我正在使用 WebFlux 编写 Spring Boot 2 REST API(不使用控制器,而是使用处理程序函数)。身份验证服务器是一项单独的服务,它发出 JWT 令牌,并将这些令牌作为身份验证标头附加到每个请求。这是一个请求方法的简单示例:
public Mono<ServerResponse> all(ServerRequest serverRequest) {
return principal(serverRequest).flatMap(principal ->
ReactiveResponses.listResponse(this.projectService.all(principal)));
}
Run Code Online (Sandbox Code Playgroud)
我用它来响应用户有权访问的所有“项目”列表的 GET 请求。
之后我有一个服务检索该用户的项目列表,并呈现一个 json 响应。
问题:
现在,为了根据当前用户 ID 过滤项目,我需要从请求主体中读取它。这里的一个问题是,我有很多需要当前用户信息的服务方法,并将其传递给服务似乎是一种矫枉过正。一种解决方案是从以下位置读取服务内的主体:
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
问题一:
在编写功能代码时,这通常是一个很好的做法吗(如果我这样做而不是传播主体)?尽管在每种方法中读取主体并将其从请求发送到服务都很复杂,但这是否是一个好方法?
问题2:
我应该使用 SecurityContextHolder 线程本地来获取主体,如果我这样做,我该如何为我的服务编写测试?
如果我使用安全上下文,如何测试需要类型为主体的服务实现JWTAuthenticationToken 
null当我尝试做类似此处描述的事情时,我总是会遇到这样的情况:使用 Spring Security 进行单元测试
在服务测试中,到目前为止,我在测试中所做的是将主体传播到服务方法并使用mockito 来模拟主体。这非常简单。在端点测试中,我@WithMockUser在执行请求时使用填充主体,并模拟服务层。这样做的缺点是主要类型不同。
这是我的服务层测试类的样子:
@DataMongoTest
@Import({ProjectServiceImpl.class})
class ProjectServiceImplTest extends BaseServiceTest {
@Autowired
ProjectServiceImpl projectService;
@Autowired
ProjectRepository projectRepository;
@Mock
Principal principal;
@Mock
Principal principal2;
@BeforeEach
void setUp() {
initMocks(this);
when(principal.getName()).thenReturn("uuid");
when(principal2.getName()).thenReturn("uuid2");
}
// Cleaned for brevity
@Test
public void all_returnsOnlyOwnedProjects() {
Flux<Project> saved = projectRepository.saveAll(
Flux.just(
new Project(null, "First", "uuid"),
new Project(null, "Second", "uuid2"),
new Project(null, "Third", "uuid3")
)
);
Flux<Project> all = projectService.all(principal2);
Flux<Project> composite = saved.thenMany(all);
StepVerifier
.create(composite)
.consumeNextWith(project -> {
assertThat(project.getOwnerUserId()).isEqualTo("uuid2");
})
.verifyComplete();
}
}
Run Code Online (Sandbox Code Playgroud)
根据另一个答案,我设法通过以下方式解决这个问题。
我添加了以下方法来从通常驻留在 JWT 令牌中的声明中读取 id。
public static Mono<String> currentUserId() {
return jwt().map(jwt -> jwt.getClaimAsString(USER_ID_CLAIM_NAME));
}
public static Mono<Jwt> jwt() {
return ReactiveSecurityContextHolder.getContext()
.map(context -> context.getAuthentication().getPrincipal())
.cast(Jwt.class);
}
Run Code Online (Sandbox Code Playgroud)
然后,我在服务中需要的地方使用它,并且我不会通过处理程序将其转发到服务。
棘手的部分始终是测试。我可以使用自定义 SecurityContextFactory 解决此问题。我创建了一个注释,我可以以与 @WithMockUser 相同的方式附加该注释,但带有一些我需要的声明详细信息。
@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockTokenSecurityContextFactory.class)
public @interface WithMockToken {
String sub() default "uuid";
String email() default "test@test.com";
String name() default "Test User";
}
Run Code Online (Sandbox Code Playgroud)
然后是工厂:
String token = "....ANY_JWT_TOKEN_GOES_HERE";
@Override
public SecurityContext createSecurityContext(WithMockToken tokenAnnotation) {
SecurityContext context = SecurityContextHolder.createEmptyContext();
HashMap<String, Object> headers = new HashMap<>();
headers.put("kid", "SOME_ID");
headers.put("typ", "JWT");
headers.put("alg", "RS256");
HashMap<String, Object> claims = new HashMap<>();
claims.put("sub", tokenAnnotation.sub());
claims.put("aud", new ArrayList<>() {{
add("SOME_ID_HERE");
}});
claims.put("updated_at", "2019-06-24T12:16:17.384Z");
claims.put("nickname", tokenAnnotation.email().substring(0, tokenAnnotation.email().indexOf("@")));
claims.put("name", tokenAnnotation.name());
claims.put("exp", new Date());
claims.put("iat", new Date());
claims.put("email", tokenAnnotation.email());
Jwt jwt = new Jwt(token, Instant.now(), Instant.now().plus(1, ChronoUnit.HOURS), headers,
claims);
JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(jwt, AuthorityUtils.NO_AUTHORITIES); // Authorities are needed to pass authentication in the Integration tests
context.setAuthentication(jwtAuthenticationToken);
return context;
}
Run Code Online (Sandbox Code Playgroud)
然后一个简单的测试将如下所示:
@Test
@WithMockToken(sub = "uuid2")
public void delete_whenNotOwner() {
Mono<Void> deleted = this.projectService.create(projectDTO)
.flatMap(saved -> this.projectService.delete(saved.getId()));
StepVerifier
.create(deleted)
.verifyError(ProjectDeleteNotAllowedException.class);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8553 次 |
| 最近记录: |