具有长ID和电话的多重验证的Java doFilter身份验证令牌

时间:2019-04-30 23:13:14

标签: java spring spring-boot jwt jwt-auth

如何通过长ID和电话号码一起通过多重身份验证来验证令牌jwt?

我的代码只能通过长ID或电话号码来工作,我尝试插入一个if,但不起作用,我想让长ID或电话都可以工作。

@Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            Long userId = tokenProvider.getUserIdFromJWT(jwt);

            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);

            } else if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {

                String phoneNumber = jwtTokenHandler.validatePhone(jwt) ;
                UserDetails userDetailsPhone = customUserDetailsService.loadUserPhone(phoneNumber);

                UsernamePasswordAuthenticationToken authenticationMobile = new UsernamePasswordAuthenticationToken(userDetailsPhone, null, userDetailsPhone.getAuthorities());
                authenticationMobile.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authenticationMobile);
             }

        } catch (Exception ex) {
            logger.error("Could not set user authentication in security context", ex);
        }

        filterChain.doFilter(request, response);
    }

    private String getJwtFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7, bearerToken.length());
        }

0 个答案:

没有答案