auth0-java v1.0.0 失败并出现错误 400:用户无权访问这些范围的受众

auth0-java v1.0.0 fails with error 400: User is not authorized to the audience for those scopes

我正在尝试开发一个微服务来处理 Auth0 的身份验证。

我在其最新版本中添加了 auth0-java 依赖项:

    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>auth0</artifactId>
        <version>1.0.0</version>
    </dependency>

该服务应获取 user/pwd 并在 Auth0 上对其进行验证并发回 AccessToken。

这是失败的代码:

    AuthAPI auth = new AuthAPI("my-domain.auth0.com", "xxx", "yyy");
    AuthRequest request = auth.login(username, password, "Username-Password-Authentication")
            .setAudience("https://my-domain.auth0.com/api/v2/")
            .setScope("openid name email app_metadata");
    try {
        TokenHolder holder = request.execute();
        return holder;
    } catch (Auth0Exception e) {
        throw new AuthentException("Error authenticating " + username, e);
    }

此代码失败:

Request failed with status code 400: User is not authorized to the audience for those scopes

我试过 "read:client read:user" 等范围...但同样的问题。

然后我尝试使用旧版本 0.4.0,它可以工作。

这是工作代码:

    Auth0 auth = new Auth0("xxx", "my-domain.auth0.com");
    AuthenticationAPIClient client = auth.newAuthenticationAPIClient();
    try {
        Authentication execute = client.getProfileAfter(client.login(username, password)
                .setConnection("Username-Password-Authentication")).setScope("openid name email app_metadata").execute();
        return execute.getCredentials();
    } catch (APIException e) {
        throw new AuthentException("Error authenticating " + username, e);
    }

那么为什么 0.4.0 有效,而 1.0.0 无效?

对于 1.0.0,您正在尝试对用户进行身份验证以进行管理 API。您无法根据管理 API 对用户进行身份验证。 Auth0 管理 API 仅允许通过 client credentials grant reference

进行身份验证

使用 0.4.0 代码片段,通过调用 login api,您正在使用 password 授权对用户进行身份验证。

要使用 1.0.0 版本的密码授权对用户进行身份验证,您可以使用相同的代码段,但是将受众设置为您自己的资源服务器 (API),例如。 https://example.com/api。或者,如果您不想为特定受众获取访问令牌,则使用更简单的登录 api reference