首页 > 解决方案 > Spring Security 与微服务的问题

问题描述

项目分为----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 extends OncePerRequestFilter ,检查 Token 并启动 SecurityContext

问题我不断收到 401 UNAUTHORIZED,无论我尝试调用服务和查询,但没有到达 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);
        }

}

标签: springspring-bootspring-securityjwtmicroservices

解决方案


推荐阅读