0

我正在尝试在我的 Flutter 应用程序中使用 Auth0 创建用户身份验证系统。Auth0 REST 文档给出了 cURL 的示例,但我没有找到任何可以完成 cURL 工作的颤振包。所以,我用了http. 这是代码:

  Future<String> getToken(String userId) async {
    final response = await http.post(
      Uri.parse('https://my-auth0-subdomain.auth0.com/oauth/token'),  // I used my real subdomain
      body: jsonEncode({
        'grant_type=client_credentials',
        'client_id=my_project_client_id',  // I used my real client id
        'client_secret=my_project_client_secret',  // I used my real client secret
        'audience=https://my-auth0-subdomain.auth0.com/api/v2/'  // I used my real subdomain
      }),
      headers: {
        'content-type: application/x-www-form-urlencoded'
      },
    );
    final token = jsonDecode(response.body)["access_token"];

    return token;
  }

这给了我The argument type 'Set<String>' can't be assigned to the parameter type 'Map<String, String>'.第 10 行(headers: {...})上的错误。
我可以使用headers: {'content-type': 'application/x-www-form-urlencoded'},.
但这会给出来自 Auth0 的错误{"error":"access_denied","error_description":"Unauthorized"}。API 设置正确,因为在运行时

curl --request POST \
  --url 'https://my-auth0-subdomain.auth0.com/oauth/token' \
  --header "content-type: application/x-www-form-urlencoded" \
  --data grant_type=client_credentials \
  --data 'client_id=my_project_client_id' \
  --data client_secret=my_project_client_secret \
  --data 'audience=https://my-auth0-subdomain.auth0.com/api/v2/'

它返回一个"access_token","scope"和. 请帮忙。这很重要。 提前致谢 :)"expires_in""token_type"


4

1 回答 1

0

尝试使用以下方式将数据作为 url 编码发送:

Map<String, String> myBody= {

'grant_type' : 'client_credentials',
        'client_id' : 'my_project_client_id',  // I used my real client id
        'client_secret' : 'my_project_client_secret',  // I used my real client secret
        'audience ' : 'https://my-auth0-subdomain.auth0.com/api/v2/'  // I used my real subdomain     
};

Future<String> getToken(String userId) async {
    final response = await http.post(
      Uri.parse('https://my-auth0-subdomain.auth0.com/oauth/token'),  // I used my real subdomain
      body: myBody,
      headers: {
        'content-type: application/x-www-form-urlencoded'
      },
    );
    final token = jsonDecode(response.body)["access_token"];

    return token;
  }
于 2021-06-23T12:51:29.520 回答