JHipster微服务网关无认证访问API及CURL调用401问题咨询
问题原因
- 网关侧路径匹配规则错误:你当前网关的
SecurityConfiguration中仅放行了网关本地路径/api/landing-page-by-organizations/**,但你通过网关调用微服务的请求路径为/services/tajvoteservice/api/landing-page-by-organizations,该路径未被纳入放行规则,会被/api/**的authenticated规则拦截,返回401未授权。 - 微服务侧鉴权拦截:即便网关完成放行,目标微服务
tajvoteservice自身的安全配置默认也会对所有/api/**路径做鉴权校验,没有放行对应接口的话同样会返回401。 - Swagger测试正常的原因:你在网关内使用Swagger测试时,已完成网关的登录认证,请求默认携带有效JWT凭证,所以可以正常访问接口。
解决方案
修改网关安全配置
在网关SecurityConfiguration的authorizeRequests配置块中,添加微服务转发路径的放行规则,注意必须放在/api/**的认证规则之前(Spring Security按顺序匹配路径,先匹配到的规则优先生效):
@Override public void configure(HttpSecurity http) throws Exception { // @formatter:off http // 原有其余配置保持不变 .and() .authorizeRequests() .antMatchers("/api/auth-info").permitAll() .antMatchers("/api/admin/**").hasAuthority(AuthoritiesConstants.ADMIN) .antMatchers("/api/landing-page-by-organizations/**").permitAll() // 新增下面这行,放行对应微服务的公共接口路径 .antMatchers("/services/tajvoteservice/api/landing-page-by-organizations/**").permitAll() .antMatchers("/api/**").authenticated() // 原有其余配置保持不变 // @formatter:on }
修改目标微服务的安全配置
在tajvoteservice微服务的SecurityConfiguration中,添加对应接口的放行规则,同样放在/api/**认证规则之前:
.authorizeRequests() // 原有其他放行规则保留 .antMatchers("/api/landing-page-by-organizations/**").permitAll() .antMatchers("/api/**").authenticated() // 其余原有配置保持不变
验证效果
重启网关和目标微服务后,直接执行CURL请求即可正常获取数据,无需携带认证凭证:
curl -X 'GET' \ 'http://localhost:8080/services/tajvoteservice/api/landing-page-by-organizations' \ -H 'accept: */*'
可选优化建议
建议统一所有微服务的公共接口路径前缀,比如都放到/api/public/**下,网关只需要配置一次/services/*/api/public/**的放行规则即可,不用每个接口单独添加配置,降低维护成本。
内容的提问来源于stack exchange,提问作者Amar Premsaran Patel
相关产品推荐
相关产品推荐

