how to use If else statement java to a auth filter

北战南征 提交于 2020-01-05 07:22:07

问题


I have two ways of authentication users by phone number and username password, I am trying to use both in my filter, should I use If and Else or there is a better way? I've tried the my code below although it does not working.

 @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);
    }

回答1:


I would personally use two filters BasicAuthFilter and PhoneAuthFilter, but if you want to have a quick refactor of the existing, here is a proposition

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);
}



回答2:


I don't if this is the best option but it make it worked.

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);
    }


来源:https://stackoverflow.com/questions/55941420/how-to-use-if-else-statement-java-to-a-auth-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!