如何使用if else语句将Java传递给auth过滤器

时间:2019-05-01 19:13:41

标签: java spring spring-boot jwt-auth

我有两种通过电话号码和用户名密码对用户进行身份验证的方法,我正在尝试在过滤器中同时使用这两种方法,应该使用If and Else还是有更好的方法?我尝试了下面的我的代码,尽管它不起作用。

 @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) && jwtTokenHandler.validateToken(jwt)) {

                String phoneNumber = jwtTokenHandler.validatePhone(jwt) ;

                UserDetails userDetailsUser = customUserDetailsService.loadUserPhone(phoneNumber);

                UsernamePasswordAuthenticationToken authenticationMobile = new UsernamePasswordAuthenticationToken(userDetailsUser, null, userDetailsUser.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);
    }

2 个答案:

答案 0 :(得分:0)

我个人会使用两个过滤器BasicAuthFilterPhoneAuthFilter,但是如果您想快速重构现有过滤器,这是一个建议

protected void doFilterInternal(HttpServletRequest request, 
                                HttpServletResponse response, 
                                FilterChain filterChain) 
                                    throws ServletException, 
                                           IOException {
    try {
        String jwt = getJwtFromRequest(request);
        if (StringUtils.hasText(jwt)) {
            UserDetails userDetails = null;
            if (tokenProvider.validateToken(jwt)) {
                Long userId = tokenProvider.getUserIdFromJWT(jwt);
                userDetails = customUserDetailsService.loadUserById(userId);
            } else if (tokenProvider.validatePhone(jwt)) {
                String phoneNumber = jwtTokenHandler.validatePhone(jwt);
                userDetails = customUserDetailsService.loadUserPhone(phoneNumber);
            }

            if (userDetails != null) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.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);
}

答案 1 :(得分:0)

如果这是最好的选择,我不知道,但这使它可行。

protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException,
            IOException {

        try {
            String jwt = getJwtFromRequest(request);

            if (StringUtils.hasText(jwt)) {

                UserDetails userDetails = null;

                if (tokenProvider.validateToken(jwt)) {
                    Long userId = tokenProvider.getUserIdFromJWT(jwt);
                    userDetails = customUserDetailsService.loadUserById(userId);
                }

                if (userDetails != null) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authentication);

                }
            }
        } catch (Exception tryAgain) {
            logger.error("Could not set user authentication. Let's try with mobile auth", tryAgain);
            try {
                String jwt = getJwtFromRequest(request);

                if (StringUtils.hasText(jwt)) {

                    UserDetails userDetails = null;

                    if (jwtTokenHandler.validateToken(jwt)) {
                        String phoneNumber = jwtTokenHandler.validatePhone(jwt);
                        userDetails = customUserDetailsService.loadUserPhone(phoneNumber);
                    }

                    if (userDetails != null) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);

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

        }

        filterChain.doFilter(request, response);
    }