Oven-ready Dio interceptor for handling OAuth 2.0.
- Easily request authentication tokens using OAuth 2.0 grants
- Add an interceptor to your Dio instance which adds the Bearer token to every request
- Stores tokens using Flutter Secure Storage
- Automatically refreshes expired tokens
flutter pub add oauth_interceptor
final oAuth = OAuth(
tokenUrl: 'oauth/token',
clientId: '1',
clientSecret: 'secret',
dio: myBaseDio, // Optional; if ommitted OAuth will use a basic Dio instance
name: 'client', // Required if you have multiple instances of OAuth e.g. for storing client and password tokens separately
);
final authenticatedDio = Dio()..interceptors.add(oAuth);
final isSignedIn = await oAuth.isSignedIn; // Will be true if a token exists in storage
oAuth.login(const ClientCredentialsGrant());
oAuth.login(
PasswordGrant(username: '[email protected]', password: 'password'),
);
oAuth.logout();
oAuth.refresh(); // This should happen automatically if a token has expired, but you can also manually refresh tokens if you like.
The packages exposes an OAuthGrantType
abstract class which can be implemented, allowing you to create your own custom grant types.
class CustomGrantType implements OAuthGrantType {
@override
FutureOr<RequestOptions> handle(RequestOptions request) async {
// Do something fancy with the request
return request;
}
}