我正试图在Flutter应用程序中使用Auth0创建一个用户身份验证系统。Auth0REST文档给出了一个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"
请帮忙。这很重要。
提前感谢:(
尝试将数据发送为使用编码的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;
}