我在 UI 服务中正确设置身份验证和授权时遇到问题。
我目前有以下设置(全部使用 Spring.* 和 Spring Cloud.*):
- Config Service;
- Registry Service;
- Gateway Service (Zuul);
- Authentication Service (Spring Cloud Security, JWT);
- Company backend service (db <-> rest);
- Ui service;
就后端安全而言,一切都按其应有的方式运行:您通过身份验证服务的网关请求带有凭据的 JWT token ,如果所有匹配,则通过 REST 返回。
公司服务知道新 token 并在出现时对其进行验证。
问题出在 UI 服务上。我目前正在做的是使用 Spring Boot 和 Thymeleaf 并手动构建 HttpHeaders、HttpEntity 和 Cookie 对象,而不在前端部分使用 Spring Cloud Security,以便访问 web 应用程序的某些部分。这是很多愚蠢的不必要的代码。我知道我无法理解如何将 Spring Cloud 安全性集成到我的 UI 服务中。
这是 Controller 方法之一的示例(非常难看):
@RequestMapping("/firms")
public String firm (Model model,
HttpServletRequest servletRequest,
HttpServletResponse servletResponse,
HttpSession httpSession) throws IOException {
final String returnPage;
Cookie cookie = authService.findCookie(servletRequest, servletResponse);
HttpHeaders httpHeaders = authService.createJwtAuthHeader(cookie);
HttpEntity requestEntity = new HttpEntity(httpHeaders);
ResponseEntity <UserObject> userObjectResponse = authService.createUserResponseEntity(requestEntity, servletResponse);
authService.setUserSessionDetails(userObjectResponse, httpSession);
if (userObjectResponse != null && userObjectResponse.getBody() != null) {
log.info(CommonMessages.GOT_COOKIE_FROM_AUTH_SERVICE.toString(), cookie.getName());
returnPage = "firm";
} else {
log.error(CommonMessages.NO_COOKIES_FOUND_NO_ACCESS_REDIRECTING.toString());
httpSession.setAttribute("authorized", false);
returnPage = "error";
}
return returnPage;
}
也许有人遇到了类似的问题,并找到了我可以使用的资源或示例,以便将 Spring Cloud Security 正确集成到我的 UI 服务中?
谢谢!
最佳答案
这是一个您可能想要查看的方便示例:https://github.com/ddewaele/spring-cloud-security-samples/blob/master/sample1/gateway/src/main/resources/application.yml
这里的主要思想是使用 @EnableOAuth2Sso
标记您的服务,以便它可以表现为 OAuth 2.0 Client 。这意味着它将执行以下操作:
- 将用户重定向到授权服务器,以便他们可以在那里输入凭据。
- 预计在成功输入凭据后,最终用户将通过授权代码从授权服务器重定向回来。该授权码将自动兑换为访问 token 。
- 可以使用
OAuth2RestTemplate
调用其他微服务,该微服务会自动将访问 token 注入(inject)到您的传出请求中。在这种情况下,您调用的微服务必须使用@EnableResourceServer
注解,这意味着它将需要访问 token 才能处理请求。
有关此主题的更多信息,您可以查看我的另一篇文章 here .
关于java - Spring 安全云 : UI service through a ZUUL gateway security setup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44631761/