首页 > 解决方案 > 使用 JWT 保护微服务之间的通信

问题描述

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

1) Auth 服务 - 创建 JWT。

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

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

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

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

标签: spring-bootspring-securityjwtmicroservices

解决方案


智威汤逊示例

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 令牌是否存在,每个人都可以访问
  • /**/private/**拥有 JWT Token 的客户端可以访问。如果令牌不存在,它将响应 401/403(未经授权/禁止)

现在进入编码部分。您必须创建一个WebSecurityConfig扩展的类,该类WebSecurityConfigurerAdapter覆盖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 Filter Chain 的配置(WebSecurity web)。

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

HttpSecurity 和 WebSecurity 有什么区别?


推荐阅读