使用 Oauth2 的 password 模式
接口是 https://ruby-china.org/oauth/token
final String _authEndpoint = Config.OauthBasetURL + "/oauth/authorize";
final String _tokenEndpoint = Config.OauthBasetURL + "/oauth/token";
final String _clientId = Config.OauthClientId;
Future<ResultData<Oauth2Credentials>> login(
{String username, String password}) async {
if (username == null || (username != null && username.isEmpty))
return Future.error('用户名不能为空.');
if (password == null || (password != null && password.isEmpty))
return Future.error('密码不能为空.');
var data = FormData.fromMap({
"client_id": _clientId,
"grant_type": "password",
"username": username,
"password": password,
});
var response =
await HttpManager.instance.request(_tokenEndpoint, "post", data: data);
if (response.ok) {
var credentials = Oauth2Credentials.fromJson(response.data);
return ResultData<Oauth2Credentials>(true, response.code,
data: credentials, meta: response.data["meta"], raw: response.raw);
} else {
var error = {
'error': '登陆错误',
'message': ['用户名或密码错误'],
};
return ResultData<Oauth2Credentials>(
false,
response.code,
data: null,
error: Error.fromJson(error),
raw: response.raw,
);
}
}
也可以参考 https://github.com/ruby-china/ruby-china-ios/blob/master/ruby-china-ios/Libraries/OAuth2.swift#L66