首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用JWT实现微服务之间的安全通信

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

Stack Overflow用户
提问于 2019-07-13 22:56:22
回答 1查看 462关注 0票数 1

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

1)认证服务-创建JWT。

2和3-执行某些操作的微服务(REST API)。

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-07-14 00:13:23

JWT Example

代码语言:javascript
运行
复制
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

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

无论是否存在JWT令牌,或者拥有JWT令牌的客户端都可以访问not

  • /**/private/**,每个人都可以访问
  • /**/public/**。如果不存在令牌,它将响应401/403 (Unauthorized/Forbidden)

现在来看编码部分。您必须创建一个WebSecurityConfig类来扩展覆盖configure(HttpSecurity http)WebSecurityConfigurerAdapter

代码语言:javascript
运行
复制
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()。

您还可以添加endPoints来配置( Spring ),因为您不想对其应用Spring Security Filter Chain。

代码语言:javascript
运行
复制
@Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers("**/public/**")
    }

What is the difference between HttpSecurity and WebSecurity?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57020255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档