无法将参数类型“Set<String>”分配给参数类型“Map<String, String>”

时间:2021-06-23 11:52:37

标签: flutter jwt auth0 flutter-http

我正在尝试在我的 Flutter 应用程序中使用 Auth0 创建一个用户身份验证系统。 Auth0 REST 文档给出了一个 cURL 示例,但我没有找到任何执行 cURL 工作的 flutter 包。所以,我使用了 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;
  }

这在第 10 行 (The argument type 'Set<String>' can't be assigned to the parameter type 'Map<String, String>'.) 上给了我一个错误 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"

请帮忙。这很重要。
提前致谢:)

1 个答案:

答案 0 :(得分: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;
  }