这将与 flutter 移动应用程序集成
accessToken 和 refreshToken:
abstract class OAuthSource {
Future<Either<Failure, TokenResponse>> login({
required String email,
required String password,
});
Future<Either<Failure, TokenResponse>> refreshToken({
required String refreshToken,
});
}
class OAuthSourceImpl implements OAuthSource {
final String _authority;
final String _clientId;
final String _clientSecret;
OAuthSourceImpl({
required String authority,
required String clientId,
required String clientSecret,
}) : _authority = authority,
_clientId = clientId,
_clientSecret = clientSecret;
@override
Future<Either<Failure, TokenResponse>> login({
required String email,
required String password,
}) async {
try {
final authorizationEndpoint =
Uri.parse('${_authority}/protocol/openid-connect/token');
var body = {
'grant_type': 'password',
'client_id': _clientId,
'client_secret': _clientSecret,
'username': email,
'password': password,
};
var response = await http.post(
authorizationEndpoint,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body,
);
return response.parse(decoder: TokenResponse.fromJson);
} catch (e) {
return Left(Failure.server(message: e.toString(), code: 500));
}
}
@override
Future<Either<Failure, TokenResponse>> refreshToken({
required String refreshToken,
}) async {
try {
final refreshTokenEndpoint =
Uri.parse('${_authority}/protocol/openid-connect/token');
var body = {
'grant_type': 'refresh_token',
'client_id': _clientId,
'client_secret': _clientSecret,
'refresh_token': refreshToken,
};
var response = await http.post(
refreshTokenEndpoint,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: body,
);
return response.parse(decoder: TokenResponse.fromJson);
} catch (e) {
return Left(Failure.server(message: e.toString(), code: 500));
}
}
}
这里,_authority
是您的Keycloak领域URL。此外,您需要创建一个机密客户端并传递
_clientID
和
_clientSecret
中的凭据。我认为您无法在不被重定向到 Keycloak 登录页面的情况下使用 PKCE。