当我尝试通过网关访问受保护的微服务 URL 时,例如:
HTTP://localhost:8080/services/microservicename/api/**
我收到以下错误
401 Unauthorized, full authentication requested
.
我正在为微服务使用 JWT 身份验证,并且我有一个单独的注册服务。是什么导致了这个问题?
调试的第一步应该是查看您是否通过网关进行身份验证。
要通过请求正文原始 json 数据中的网关进行身份验证
{"username":"admin","password":"admin","rememberMe":"true"}
http://localhost:8080/api/authenticate
,您将得到一个 id_token
作为响应。在您要处理的每个请求中使用此 id_token 数据作为 Authorization Bearer
令牌,例如:- http://localhost:8080/services/microservicename/path
在确认网关身份验证后,调试的第二步是在您尝试访问的特定微服务的配置文件夹中查看 SecurityConfiguration.java。在
SecurityFilterChain
函数中,您会看到类似 .antMatchers("/api/**").authenticated()
的内容。 antMatcher 的结尾将是 permitAll()
authenticated()
或 hasAuthority(AuthoritiesConstants.ADMIN)
.
如果是
permitAll()
,所有请求都将到达微服务并在网关身份验证时得到处理。
如果是
hasAuthority(AuthoritiesConstants.Admin)
意味着您必须以该特定用户身份登录。默认情况下,Jhipster 'admin' {username:admin, password:admin} 或用户 {username:user, password:user} 中有两个用户,只有这样微服务控制器才会处理您的请求。
如果是
authenticated()
那么任何用户类型的登录都会处理请求。
如果您仍然面临
401 Unauthorized, full authentication requested
,则可能是导致问题的 JWT 秘密。
在调试问题时,我最初错过了原始文档页面上的详细信息。 https://www.jhipster.tech/security/
确保您在
application-dev.yml
和 application-prod.yml
中拥有与网关的 application-dev.yml 和 application-prod.yml 文件相同的 jwt secret。