【问题标题】:How to add Jwt Token based security In Microservices如何在微服务中添加基于 Jwt 令牌的安全性
【发布时间】:2021-10-03 03:15:18
【问题描述】:

在我的微服务中,我会尝试实现Jwt spring-security,但是我不知道如何应用它。

在我的微服务中,我使用了 2020.0.3 spring cloud 版本。 在用户服务中,我已经使用 Rest 模板连接了部门服务。 我需要有关如何在这些微服务中添加 Jwt 安全性的帮助。

这是 4 个微服务

服务器 = 尤里卡服务器

service-API-gateway = Spring cloud Apigateway

service-department & services-user = 这两个微服务与 Rest 模板连接

微服务项目结构https://i.stack.imgur.com/ajTiX.png

【问题讨论】:

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


    【解决方案1】:

    因此,在更高级别上,当使用 jwt 作为身份验证时,Spring Security 应用于控制器级别。首先,您需要添加一个将扩展 WebSecurityConfigurerAdapter 的安全配置(这对于基于 http 的安全性很常见),并且在该类中您需要定义配置方法,例如:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic().disable()
                .csrf().disable()  // IF your clients connect without a cookie based, this will be fine
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/register", "/login","/your_open_endpoints_etc").permitAll()
                .and()
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
    }
    

    然后在扩展OncePerRequestFilter的过滤器类中,你可以像这样定义do过滤器,你必须在Spring认证上下文中设置UsernamePasswordAuthenticationFilter实例:

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        logger.info("do filter...");
        String token = jwtProvider.getTokenFromRequest((HttpServletRequest) httpServletRequest);
        try{
            if (token != null && jwtProvider.validateToken(token)) {
                String username = jwtProvider.getUsernameFromToken(token);
                UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, jwtProvider.getAuthorities(token));
                SecurityContextHolder.getContext().setAuthentication(auth);
            }
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
        catch (RuntimeException e)
        {
            // Some general Exception handling that will wrap and send as HTTP Response
        }
    
    }
    

    进一步检查扩展过滤器,它们可能会根据您的要求进行更改

    最后在休息端点你可以像这样保护:

    @PreAuthorize("hasRole('ROLE_YOURROLE')")
    @GetMapping(path = "/your_secured_endpoint", consumes = "application/json", 
      produces = "application/json")
    public ResponseEntity<List<SomePOJOObject>> getAllAppointmentsForPatient()
    {
       
        return new ResponseEntity<>(thatSomePOJOObjectListYouWant, HttpStatus.OK);
    }
    

    【讨论】:

    • 你好,Shamitha 我会在 API 网关中添加这个配置吗?。
    • 自 3 年前以来,spring 已经完全支持 JWT,编写自定义 JWT 过滤器安全解决方案是一种不好的做法docs.spring.io/spring-security/site/docs/current/reference/…downvoted。
    • @BhavikChavda 这应该放在你的 HTTP API 端,我认为应该有一个用作 REST API
    • @BhavikChavda 这个工作吗?如果是这样,您可以接受答案,这样您就可以增加将来获得答案的机会
    猜你喜欢
    • 2016-05-15
    • 2021-10-28
    • 2020-05-27
    • 2018-07-30
    • 2013-08-15
    • 2016-03-26
    • 2016-07-20
    • 2020-05-04
    • 2018-02-08
    相关资源
    最近更新 更多