Spring Cloud - 如何仅允许访问特定微服务的端点?

时间:2017-07-08 16:42:24

标签: spring oauth-2.0 microservices spring-cloud

我有简单的微服务架构:

  • 边缘服务
  • 服务注册表
  • auth服务(我正在使用JWT和OAuth2)
  • 用户服务
  • 前端和一些核心服务

当用户尝试登录时,凭据将从边缘服务传递到身份验证服务。 Auth服务从用户服务获取用户数据(使用 @FeignClient ),如果用户名/密码匹配,则生成令牌。没什么好看的。

此方法存在“小问题”:用户服务中的端点/api/user/{username}(由auth服务用于获取用户的数据)可能被任何用户用于获取任何其他用户的数据(密码,角色等)。一个解决方案是以某种方式为角色为AUTH_SERVICE的auth-service创建JWT令牌,并在用户服务端检查JWT,如果角色不同于AUTH_SERVICE拒绝请求。

还有其他解决方案吗?

修改

我认为我的设计很常见,但显然我应该首先更具体:

  • Auth-servie是我的授权服务器,其他服务是资源服务器
  • 我使用API​​网关模式,我的身份验证服务也是behin proxy
  • 客户端应用程序获取JWT后,将其添加到每个请求中,并根据执行的身份验证和授权;每个资源服务器都有一个公钥,用于验证签名;如果它有效,则服务知道JWT已由受信任的身份验证服务生成,并且基于JWT的服务创建包含所有用户信息的OAuth2Authenication对象

EDIT2:

我最终将auth-service合并到用户服务,这是一些SO用户提出的建议。在考虑之后,似乎没有必要为JWT生成单独的auth服务。我已经接受了@Abhijit Sarkar的回答,因为它有一些有效点,即使他对额外调用auth-service以验证令牌的有效性是不对的。

2 个答案:

答案 0 :(得分:2)

在我看来,你的服务太薄了;这种情况发生了,随着时间的推移,您开始意识到由于维护和性能问题,服务需要更粗糙。从auth到用户服务的另一个HTTP调用的成本,以及维护服务间身份验证的开销并非易事。

IMO,用户服务可以存在其他用户信息,如地址等,如果存在,但auth服务应负责管理自己的数据。这正是Spring Security有UserDetailsService

的原因

这实际上是一种设计选择,无论用户凭据和其他用户信息是在同一个表中,还是在同一个数据库中。不同的人会给你不同的答案,但根据我的意见和经验,数量的相关服务之间的共享数据库是可以接受的,特别是因为这些表将是相关的通过外键(userId)。分布式事务是纯粹的邪恶与微服务,所以我甚至没有去那里。删除/更新用户时,请使用事件进行最终一致性。

修改

与OP聊天后,我了解到用户服务实际上是他设计中的OAuth资源服务器。他不清楚,因此对我来说,OAuth授权服务器在哪里。无论如何,我坚持我的建议是合并用户服务和身份验证服务。

答案 1 :(得分:1)

It would be way better to use the same DB in auth & user service. Auth service just needs to access the credential.

You can even have a security layer at User service to implement the access control over the URI according to the role.

You need something like this:

  1. Define a prefilter in edge service
  2. Edge service gets authentication request and forwards it to authentication service.
  3. Auth service uses the same DB as of User service to authenticate the user and generates JWT token.
  4. All other requests would have the token in the request header.
  5. Edge service shares the key by which JWT token was created or has a public key to verify the signature.
  6. Edge service verifies the token in its prefilter and adds user info in the request header in the plain. Redirects request to required service.
  7. Service takes the request and in its security filter, it uses user information from header to enforce the access control over resources.