如何用Postman通过Bearer令牌调用Spring Cloud Gateway授权接口
解决方案
要让Spring Cloud Gateway同时支持浏览器的OAuth2登录流程和Postman的Bearer令牌认证,需要在Security配置中添加OAuth2资源服务器支持,具体实现步骤如下:
1. 更新Security配置,添加资源服务器逻辑
修改securityWebFilterChain方法,加入oauth2ResourceServer配置,让网关能够验证Bearer令牌并加载OIDC用户信息:
@Bean public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http, ReactiveClientRegistrationRepository repository) { if (ssl) { http.redirectToHttps(Customizer.withDefaults()); } http.headers(headerSpec -> headerSpec .referrerPolicy(referrerPolicySpec -> referrerPolicySpec .policy(ReferrerPolicyServerHttpHeadersWriter.ReferrerPolicy.NO_REFERRER_WHEN_DOWNGRADE))); // 针对API路径关闭CSRF验证(Postman请求无需CSRF令牌),保留浏览器会话的CSRF保护 http.csrf(csrf -> csrf .csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()) .csrfTokenRequestHandler(new ServerCsrfTokenRequestAttributeHandler()) .ignoringMatchers("/api/**")); http.authorizeExchange(authorize -> authorize.anyExchange().authenticated()); // 保留原有OAuth2登录配置(支持浏览器会话式认证) http.oauth2Login(loginSpec -> loginSpec.authorizedClientRepository(authorizedClientRepository())) .logout(logoutSpec -> logoutSpec.logoutHandler(logoutHandler()) .logoutSuccessHandler(logoutSuccessHandler(repository)) .requiresLogout(ServerWebExchangeMatchers.pathMatchers(HttpMethod.GET, "/logout"))); // 添加OAuth2资源服务器配置(支持Bearer令牌无状态认证) http.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt .jwtAuthenticationConverter(jwtAuthenticationConverter()) .issuerUri("http://localhost:8000"))); // 与你的auth-service issuer-uri保持一致 return http.build(); } // 可选:自定义JWT转Authentication的转换器,映射OIDC用户信息到Principal private Converter<Jwt, Mono<AbstractAuthenticationToken>> jwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); // 若令牌包含自定义权限字段,可在此配置,例如: // grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_"); // grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities"); OidcIdTokenAuthenticationConverter authenticationConverter = new OidcIdTokenAuthenticationConverter(); authenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter); return authenticationConverter::convert; }
2. 确认依赖(若缺失则添加)
确保项目依赖中包含Spring OAuth2资源服务器模块:
<!-- Maven --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
或Gradle:
// Gradle implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
3. Postman请求验证
在Postman中调用接口时,添加请求头:
- 键:
Authorization - 值:
Bearer <你从SSO获取的JWT令牌>
网关会自动完成以下操作:
- 从auth-service的JWKS端点获取公钥,验证令牌签名有效性
- 解析令牌中的OIDC用户信息(sub、scope等),生成用户Principal
- 将认证后的请求转发到后端服务
关键说明
- 配置后网关同时支持两种认证模式:浏览器访问走OAuth2登录流程(会话保持),API调用走Bearer令牌验证(无状态)
issuerUri配置会让Spring自动发现auth-service的JWKS、userinfo等端点,无需手动配置所有URI- 针对
/api/**路径关闭CSRF,避免API请求被CSRF拦截,同时保留浏览器会话的CSRF保护
内容的提问来源于stack exchange,提问作者Moolerian
相关产品推荐
相关产品推荐

