使用JWT的微服务之间的安全通信

时间:2019-07-13 14:56:21

标签: spring-boot spring-security jwt microservices

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

1)身份验证服务-创建JWT。

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

理论上,用户可以访问微服务2和3,而无需微服务1创建的令牌。

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

如果有人有一个很好的榜样,那就太好了。

1 个答案:

答案 0 :(得分:0)

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

现在进入编码部分。您必须创建一个扩展WebSecurityConfig的{​​{1}}类,以覆盖WebSecurityConfigurerAdapter

configure(HttpSecurity http)

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

您还可以添加不想配置Spring Security筛选器链的端点以配置(WebSecurity web)。

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);
   }
}

What is the difference between HttpSecurity and WebSecurity?

相关问题