模拟jwt时,spring security webtestclient不会调用onceperrequestfilter

af7jpaap  于 2021-07-23  发布在  Java
关注(0)|答案(0)|浏览(309)

spring boot版本:2.4.2
我的应用程序实现以下工作流:
外部客户机在 Authorization 标题。
这个 JwtRequestfilter 扩展 OncePerRequestFilter 并从令牌中提取信息。
这是传递给 CustomUserDetailsService 它检查数据库中是否存在具有此信息的用户。
仅当此检查通过时,才会使用调用控制器方法 @AuthenticationPrincipal 作为参数。
现在我想用spring的 @WebTestClient 并用 mockJwt() . 我成功地获得了调用 CustomUserDetailsService 但似乎有两个问题:
这个 JwtRequestFilter 完全不调用,即 loadUserById() 方法未调用。
找不到用户 CustomUserDetailsService . 由于我想依赖实际的数据库,我的想法是用mockito模拟存储库,但它总是抛出 UsernameNotFoundException .
这是测试实现:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerIT {

    @Autowired
    private WebApplicationContext context;

    private WebTestClient webTestClient;

    @MockBean
    private UserRepo userRepo;

    @BeforeEach
    public void setup() {
        webTestClient = MockMvcWebTestClient
                .bindToApplicationContext(this.context)
                .apply(springSecurity())
                .build();
    }

    @Test
    @WithUserDetails
    public void testIt() {
        final User user = createUser("foo@bar.com", "my-password");

        when(userRepo.findByEmail(anyString())).thenReturn(Optional.of(user));
        when(userRepo.findById(anyLong())).thenReturn(Optional.of(user));

        webTestClient
                .mutateWith(mockJwt())
                .get()
                .uri("/services/user")
                .accept(MediaType.APPLICATION_JSON)
                .exchange()
                .expectStatus().is2xxSuccessful();
    }
}

以下是相关课程:
JWT请求筛选器

@Component
@Slf4j
public class JwtRequestFilter extends OncePerRequestFilter {

    private static final String BEARER_PREFIX = "Bearer ";

    private final HandlerExceptionResolver resolver;

    private final JwtService jwtService;
    private final CustomUserDetailsService userDetailsService;

    public JwtRequestFilter(@Qualifier("handlerExceptionResolver") HandlerExceptionResolver resolver, JwtService jwtService, CustomUserDetailsService userDetailsService) {
        this.resolver = resolver;
        this.jwtService = jwtService;
        this.userDetailsService = userDetailsService;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String token = parseTokenFromRequest(request);
            if (isNotBlank(token)) {
                String subject = jwtService.getSubject(token);
                if (isNotBlank(subject) && isNull(SecurityContextHolder.getContext().getAuthentication())) {
                    final MyaUserDetails userDetails = userDetailsService.loadUserById(Long.valueOf(subject));
                    if (jwtService.validateToken(token, userDetails)) {
                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    }
                }
            }
            filterChain.doFilter(request, response);
        } catch (JwtException e) {
            resolver.resolveException(request, response, null, e);
        }
    }

    private String parseTokenFromRequest(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (isNotBlank(token) && token.startsWith(BEARER_PREFIX)) {
            return token.substring(BEARER_PREFIX.length());
        } else {
            return null;
        }
    }
}

CustomUserDetails服务

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private static final String USER_NOT_FOUND = "User not found";

    private final UserRepo userRepo;

    @Override
    public CustomUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        final User user = userRepo.findByEmail(username)
                .orElseThrow(() -> new UsernameNotFoundException(USER_NOT_FOUND));
        return buildUserDetails(user);
    }

    public CustomUserDetails loadUserById(Long id) throws UsernameNotFoundException {
        final User user = userRepo.findById(id)
                .orElseThrow(() -> new UsernameNotFoundException(USER_NOT_FOUND));
        return buildUserDetails(user);
    }
}

用户控制器

@GetMapping
public ResponseEntity<UserData> getUserData(@AuthenticationPrincipal CustomUserDetails userDetails) {
    try {
        final UserData userData = userService.getUser(userDetails.getId());
        return ResponseEntity.ok(userData);
    } catch (UserNotFoundException e) {
        log.error("User with id {} not found", userDetails.getId());
        return ResponseEntity.notFound().build();
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题