微服务的Spring Security问题

时间:2020-05-03 15:54:35

标签: spring spring-boot spring-security jwt microservices

项目划分为 ---- 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

问题是,在尝试调用服务并查询未进入customrequestfilter时,我一直得到401未经授权的提示。

请帮助,我尝试了很多组合和配置,但没有成功。

我正在使用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);
        }

}

0 个答案:

没有答案