https://github.com/netsells/oauth_interceptor
Oven-ready Dio interceptor for handling OAuth 2.0
https://github.com/netsells/oauth_interceptor
Last synced: about 1 month ago
JSON representation
Oven-ready Dio interceptor for handling OAuth 2.0
- Host: GitHub
- URL: https://github.com/netsells/oauth_interceptor
- Owner: netsells
- License: mit
- Created: 2022-08-09T08:30:12.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2024-05-28T09:16:43.000Z (12 months ago)
- Last Synced: 2025-02-02T18:51:50.722Z (3 months ago)
- Language: Dart
- Size: 11.7 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
Awesome Lists containing this project
README
# OAuth Interceptor
Oven-ready [Dio](https://pub.dev/packages/dio) interceptor for handling OAuth 2.0.
## Features
- 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](https://pub.dev/packages/flutter_secure_storage)
- Automatically refreshes expired tokens## Installation

```bash
flutter pub add oauth_interceptor
```## Usage
### Step 1: Create an `OAuth` instance
```dart
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
);
```### Step 2: Add the `OAuth` instance as a Dio interceptor
```dart
final authenticatedDio = Dio()..interceptors.add(oAuth);
```### Step 3: Use the login/logout methods
```dart
final isSignedIn = await oAuth.isSignedIn; // Will be true if a token exists in storageoAuth.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.
```### Creating your own grant type
The packages exposes an `OAuthGrantType` abstract class which can be implemented, allowing you to create your own custom grant types.
```dart
class CustomGrantType implements OAuthGrantType {
@override
FutureOr handle(RequestOptions request) async {
// Do something fancy with the request
return request;
}
}
```