且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 oauth2 身份验证之上实现用户权限

更新时间:2022-12-06 22:46:30

范围

我不会为此目的使用 OAuth2 范围.原因是 OAuth2 范围用于限制 应用程序 可以对用户的资源 做什么,而不是限制 用户应用.

Scopes

I would not use OAuth2 scopes for this purpose. The reason is that OAuth2 scopes are for restricting what an application can do with a user's resource, not for restricting what a user can do in the application.

例如,如果我编写了一个 Web 应用程序,向用户显示他们在其 Google 文档中使用的语言,则需要 Google 授予的权限才能阅读用户的 Google 文档,但不需要例如阅读他们的日历.因此,应用程序将从 Google 获得一个 OAuth2 令牌,该令牌范围具有读取文档权限,但没有读取日历权限或任何其他不必要的权限.

For example, if I wrote a web application that showed users what languages they used in their Google Docs, it would need the privilege delegated from Google to read the user's Google Docs, but not to, for example, read their calendar. So the application would get an OAuth2 token from Google that was scoped with the read-Docs privilege, but not the read-calendar privilege or any other unnecessary privileges.

使用范围来携带有关用户权限(而不是应用程序权限)的信息的具体缺点是,如果您想实现上述内容,应用程序可以在应用程序中对用户资源进行不同级别的访问,尝试同时以多种方式使用 OAuth2 范围可能会令人困惑.如果您想通过 API 向客户公开应用程序中的功能以集成到他们自己的应用程序中,这可能会成为一个问题.

The concrete drawback of using scopes to carry info about user permissions (as opposed to application permissions) would be, if you want to implement something like the above, where applications get varying levels of access to users' resources within your application, it could be confusing trying to use OAuth2 scopes in multiple ways simultaneously. This could become a problem if you want to expose functionality within your application via an API to your customers to integrate into their own applications.

您提到您使用 OAuth2 进行身份验证.OAuth2 用于委托授权,不用于身份验证.OAuth2 访问令牌不代表经过身份验证的用户.OpenId Connect ID 令牌可以.

You mentioned you are using OAuth2 for authentication. OAuth2 is for delegating authorization, not for authentication. OAuth2 access tokens do not represent authenticated users. OpenId Connect ID tokens do.

我喜欢使用 AWS Cognito 进行身份验证.它为您跟踪您的用户,因此您不需要用户数据库,并处理对他们的身份验证.它与 Google 和 Facebook 等外部身份提供商集成.对于跟踪不同类型用户的用例,您可以使用 Cognito .此处 是一篇带有示例的博客文章.

I like using AWS Cognito for authentication. It keeps track of your users for you, so you don't need a user database, and handles authenticating them. It integrates with external identity providers like Google and Facebook. For your use case of keeping track of different kinds of users, you can use Cognito Groups. Here is a blog post with an example.

基本上,您将从 Cognito 获得 ID 令牌,您的客户端或服务器可以读取 ID 令牌以找出用户的组(管理员、普通用户等),并采取相应的行动.这里是阅读的例子来自令牌的组.

Basically you'll get an ID token from Cognito, and your client or your server can read the ID token to figure out the user's groups (admin, regular-user, etc), and act accordingly. Here is an example of reading the group from the token.