проблема с Spring Security с микросервисами - PullRequest
0 голосов
/ 03 мая 2020

Проект разделен на ---- Шлюз API (Zuul) --- услуги аутентификации (Вход / Регистрация, генерирование токена JWT) --- Услуги CaclulateFees --- Расчет сервисов Мне нужно сгенерировать токен на сервисах аутентификации с JWT (все в порядке), мне нужно, чтобы другие сервисы проверяли токен перед открытием метода.

Я добавил необходимое библиотека в CalculateFees, а затем реализует WebSecurityConfig, расширяет WebSecurityConfigurerAdapter

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // We don't need CSRF for this example
        httpSecurity.csrf().disable()
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate", "/register" ).permitAll().
                 anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    } 

после этого реализует CustomRequestFilter, расширяет OncePerRequestFilter, чтобы проверить токен и инициировать SecurityContext

Проблема, которую я продолжаю получать 401 НЕСАНКЦИОНИРОВАННО, я пытаюсь вызвать службы и запрос, не доходя до customrequestfilter.

Пожалуйста, помогите, я получил Попробуйте так много комбинаций и конфигурации без успеха.

Я использую SPRING BOOT 2.2.6.

ниже код для проверки токена

@Component
public class CustomRequestFilter extends OncePerRequestFilter{

     @Autowired
     private CustomJwtUserDetailsService jwtUserDetailsService;

     @Autowired
     private CustomJwtTokenProvider jwtTokenUtil;

     @Override
        protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws ServletException, IOException {
            final String requestTokenHeader = request.getHeader("Authorization");
            Long userID = null;
            String jwtToken = null;
            // JWT Token is in the form "Bearer token". Remove Bearer word and get
            // only the Token
            if (requestTokenHeader != null && requestTokenHeader.startsWith("Bearer ")) {
                jwtToken = requestTokenHeader.substring(7);
                try {
                    userID = jwtTokenUtil.getUserIdFromJWT(jwtToken);
                } catch (IllegalArgumentException e) {
                    System.out.println("Unable to get JWT Token");
                } catch (ExpiredJwtException e) {
                    System.out.println("JWT Token has expired");
                }
            } else {
                logger.warn("JWT Token does not begin with Bearer String");
            }
            // Once we get the token validate it.
            if (userID != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.jwtUserDetailsService.loadUserById(userID);
                // if token is valid configure Spring Security to manually set
                // authentication
                if (jwtTokenUtil.validateToken(jwtToken)) {
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                    usernamePasswordAuthenticationToken
                        .setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    // After setting the Authentication in the context, we specify
                    // that the current user is authenticated. So it passes the
                    // Spring Security Configurations successfully.
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                }
            }
            chain.doFilter(request, response);
        }

}
...