spring-boot - 使用 JWT 保护微服务之间的通信
问题描述
我使用 Spring Boot 构建了 3 个微服务:
1) Auth 服务 - 创建 JWT。
2 和 3 - 做某事的微服务 (REST API)。
理论上,用户可以在没有微服务 1 创建的令牌的情况下访问微服务 2 和 3。
假设我将令牌传递给微服务 2 和 3 - 如何验证令牌的完整性?微服务 2 和微服务 3 是否需要与微服务 1 通信?
如果有人有一个很好的例子,那就太好了。
解决方案
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 有什么区别?
推荐阅读
- ascii - 在 Ada 中将字符串转换为 ascii
- android - 如何使用 express 向不同的客户端发送实时更新
- javascript - 比较嵌套对象和 JavaScript 中的数组并返回键相等
- google-admin-sdk - 哪个警报时间戳(createTime 或 endTime)与电子邮件“REMOVED_FROM_INBOX”的时间相关
- javascript - JQuery addClass 方法不适用于 $(this) 元素或 event.currentTraget
- linux - 有没有办法执行脚本,不管它在哪里?
- apache-beam - 当 ParDo 函数出现错误时,NACK 不会从 Dataflow 发送回 Google Cloud Pub/Sub
- next.js - 在 Nextjs 中获取嵌套组件的数据
- migration - 我想将 Windows 2008 r2 的用户列表迁移到 Windows 2016
- java - java - 如何在Java中返回所有带有名称+字段的枚举实例?