【问题标题】:Secure communication between microservices using JWT使用 JWT 保护微服务之间的通信
【发布时间】:2019-11-23 00:08:28
【问题描述】:

我使用 Spring Boot 构建了 3 个微服务:

1) Auth 服务 - 创建 JWT。

2 和 3 - 做某事的微服务 (REST API)。

理论上,用户可以在没有微服务 1 创建的令牌的情况下访问微服务 2 和微服务 3。

假设我将令牌传递给微服务 2 和 3 - 如何验证令牌的完整性?微服务 2 和微服务 3 是否需要与微服务 1 通信?

如果有人有一个很好的例子,那就太好了。

【问题讨论】:

  • 您需要有以下场景,用户想要访问 2 和 3,然后从 2 和 3 需要针对 auth 进行通信,检查 JWT 令牌,然后如果没问题,继续 2 和3. 那就是。
  • 这里可能使用的典型模式是网关/外观模式。任何微服务的所有传入请求都将首先到达网关 API,然后网关 API 将检查 JWT 以查看它是否仍然有效。如果不是,则该请求将立即被拒绝。否则,请求将被允许继续发送到微服务。
  • 你好 Avi,看看我的回答,我也给出了一个工作示例

标签: spring-boot spring-security jwt microservices


【解决方案1】:

JWT Example

1. /authenticate --> Auth Service - Creates JWT.
2. /public/profile --> can be accessed without JWT Token
3. /public/resource --> can be accessed without JWT Token
4. /private/users --> can be accessed with JWT Token

考虑您的应用程序的上述端点。这里,

  • /**/public/** 所有人都可以访问,这无关紧要 JWT Token 是否存在
  • /**/private/** 将可供拥有 JWT 的客户端访问 令牌。如果令牌不存在,它将以 401/403 响应 (未经授权/禁止)

现在进入编码部分。您必须创建一个扩展 WebSecurityConfigurerAdapterWebSecurityConfig 类,该类覆盖 configure(HttpSecurity http)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{ 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests()
        .antMatchers("/authenticate").permitAll()
        .antMatchers("/**/private/**").authenticated()
        .anyRequest().permitAll() 
        .and()
    .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
    .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint);
   }
}

如果您想对所有请求进行身份验证,请将 .anyRequest().permitAll() 更改为 .anyRequest().authenticated()。

您还可以将端点添加到您不想为其应用 Spring Security 过滤器链的配置(WebSecurity web)。

@Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers("**/public/**")
    }

What is the difference between HttpSecurity and WebSecurity?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 2017-05-24
    • 2016-06-10
    • 2016-03-05
    • 2018-01-22
    • 1970-01-01
    • 2021-06-20
    • 2016-08-10
    相关资源
    最近更新 更多