Skip to content

Commit 6349484

Browse files
authored
docs: Add GitHub IDP docs (#402)
1 parent 6ea335f commit 6349484

14 files changed

Lines changed: 1552 additions & 1 deletion

File tree

docs/06-concepts/11-authentication/02-basics.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ To register a signed in user, call:
191191
await client.auth.updateSignedInUser(authInfo);
192192
```
193193

194-
This will persist the authentication information and refresh any open streaming connection. This is the method used by identity providers to register a signed in user. For more details on providers, see [Custom Providers](providers/custom-providers).
194+
This will persist the authentication information and refresh any open streaming connection. This is the method used by identity providers to register a signed in user. For more details on providers, see [Custom Providers](providers/custom-providers/overview).
195195

196196
### Monitor authentication changes
197197

Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
# Setup
2+
3+
To set up **Sign in with GitHub**, you must create OAuth2 credentials on [GitHub](https://github.com/settings/apps) and configure your Serverpod application accordingly.
4+
5+
:::caution
6+
You need to install the auth module before you continue, see [Setup](../../setup).
7+
:::
8+
9+
## Choosing Your GitHub App Type
10+
11+
GitHub offers two ways to obtain OAuth2 credentials:
12+
13+
- **GitHub Apps**: more suitable when building integrations or bots that belong to an organization or repository, operate with their own identity, continue functioning regardless of which users come and go, and only access the repositories and permissions explicitly granted. They provide fine‑grained control, short‑lived tokens, and are the modern, secure choice for most automation and service scenarios.
14+
- **OAuth Apps**: preferred when the primary need is authenticating users with "Sign in with GitHub" or performing actions strictly as the currently logged‑in user under broad OAuth scopes. Similar to other OAuth providers like Google or Apple, they allow access to a user’s GitHub resources within the scopes granted, but lack the flexibility and security of GitHub Apps.
15+
16+
:::tip
17+
[GitHub Apps](https://github.com/settings/apps) are the preferred choice for most scenarios — especially mobile and modern integrations.
18+
See the official comparison here: [Differences between GitHub Apps and OAuth Apps](https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/differences-between-github-apps-and-oauth-apps).
19+
:::
20+
21+
## Create your credentials
22+
23+
1. Go to [GitHub Developer Settings](https://github.com/settings/apps).
24+
2. Click **New GitHub App** (recommended) or **New OAuth App**.
25+
26+
![GitHub App Setup](/img/authentication/providers/github/1-register-app.png)
27+
28+
3. Fill in the required fields:
29+
- **App name**
30+
- **Homepage URL**
31+
- **Callback URL(s)** (use your app's redirect URI, e.g., `myapp://auth` for mobile)
32+
- **Permissions** (at minimum: account permission = profile; add others as needed)
33+
- **Webhook URL** (disable if not required; serves to receive events like commits, pull requests, and repo changes)
34+
35+
![GitHub App Setup](/img/authentication/providers/github/2-add-permission.png)
36+
37+
![GitHub App Setup](/img/authentication/providers/github/3-add-permission.png)
38+
39+
:::tip
40+
Webhooks let your GitHub App automatically receive notifications about repository activity.
41+
If your app doesn’t need to react to events (like commits or pull requests), it’s best to disable the webhook URL to reduce unnecessary traffic and complexity.
42+
:::
43+
44+
4. Click **Create GitHub App** (for GitHub Apps) or **Register application** (for OAuth Apps). This will save your app and generate the **Client ID**.
45+
46+
5. After the app is created, click **Generate a new client secret** to obtain the **Client Secret**. Copy both the **Client ID** and **Client Secret** for later use.
47+
48+
![GitHub App Setup](/img/authentication/providers/github/4-get-credentials.png)
49+
50+
## Server-side Configuration
51+
52+
### Store the Credentials
53+
54+
This can be done by adding your credentials to the `githubClientId` and `githubClientSecret` keys in the `config/passwords.yaml` file, or by setting them as the values of the `SERVERPOD_PASSWORD_githubClientId` and `SERVERPOD_PASSWORD_githubClientSecret` environment variables.
55+
56+
```yaml
57+
development:
58+
githubClientId: 'YOUR_GITHUB_CLIENT_ID'
59+
githubClientSecret: 'YOUR_GITHUB_CLIENT_SECRET'
60+
```
61+
62+
:::warning
63+
Keep your Client Secret confidential. Never commit this value to version control. Store it securely using environment variables or secret management.
64+
:::
65+
66+
### Configure the GitHub Identity Provider
67+
68+
In your main `server.dart` file, configure the GitHub identity provider:
69+
70+
```dart
71+
import 'package:serverpod/serverpod.dart';
72+
import 'package:serverpod_auth_idp_server/core.dart';
73+
import 'package:serverpod_auth_idp_server/providers/github.dart';
74+
75+
void run(List<String> args) async {
76+
final pod = Serverpod(
77+
args,
78+
Protocol(),
79+
Endpoints(),
80+
);
81+
82+
pod.initializeAuthServices(
83+
tokenManagerBuilders: [
84+
JwtConfigFromPasswords(),
85+
],
86+
identityProviderBuilders: [
87+
GitHubIdpConfig(
88+
clientId: pod.getPassword('githubClientId')!,
89+
clientSecret: pod.getPassword('githubClientSecret')!,
90+
),
91+
],
92+
);
93+
94+
await pod.start();
95+
}
96+
```
97+
98+
:::tip
99+
You can use `GitHubIdpConfigFromPasswords()` to automatically load credentials from `config/passwords.yaml` or the `SERVERPOD_PASSWORD_githubClientId` and `SERVERPOD_PASSWORD_githubClientSecret` environment variables:
100+
101+
```dart
102+
identityProviderBuilders: [
103+
GitHubIdpConfigFromPasswords(),
104+
],
105+
```
106+
107+
:::
108+
109+
### Expose the Endpoint
110+
111+
Create an endpoint that extends `GitHubIdpBaseEndpoint` to expose the GitHub authentication API:
112+
113+
```dart
114+
import 'package:serverpod_auth_idp_server/providers/github.dart';
115+
116+
class GitHubIdpEndpoint extends GitHubIdpBaseEndpoint {}
117+
```
118+
119+
### Generate and Migrate
120+
121+
Finally, run `serverpod generate` to generate the client code and create a migration to initialize the database for the provider. More detailed instructions can be found in the general [identity providers setup section](../../setup#identity-providers-configuration).
122+
123+
### Basic configuration options
124+
125+
- `clientId`: Required. The Client ID of your GitHub App or OAuth App.
126+
- `clientSecret`: Required. The Client Secret generated for your GitHub App or OAuth App.
127+
128+
For more details on configuration options, see the [configuration section](./configuration).
129+
130+
## Client-side configuration
131+
132+
Add the `serverpod_auth_idp_flutter` package to your Flutter app. The GitHub provider uses [`flutter_web_auth_2`](https://pub.dev/packages/flutter_web_auth_2) to handle the OAuth2 flow, so any documentation there should also apply to this setup.
133+
134+
### iOS and MacOS
135+
136+
There is no special configuration needed for iOS and MacOS for "normal" authentication flows.
137+
However, if you are using **Universal Links** on iOS, they require redirect URIs to use **https**.
138+
Follow the instructions in the [flutter_web_auth_2](https://pub.dev/packages/flutter_web_auth_2#ios) documentation.
139+
140+
### Android
141+
142+
In order to capture the callback url, the following activity needs to be added to your `AndroidManifest.xml`. Be sure to replace `YOUR_CALLBACK_URL_SCHEME_HERE` with your actual callback url scheme registered in your GitHub app.
143+
144+
```xml
145+
<manifest>
146+
<application>
147+
148+
<activity
149+
android:name="com.linusu.flutter_web_auth_2.CallbackActivity"
150+
android:exported="true"
151+
android:taskAffinity="">
152+
<intent-filter android:label="flutter_web_auth_2">
153+
<action android:name="android.intent.action.VIEW" />
154+
<category android:name="android.intent.category.DEFAULT" />
155+
<category android:name="android.intent.category.BROWSABLE" />
156+
<data android:scheme="YOUR_CALLBACK_URL_SCHEME_HERE" />
157+
</intent-filter>
158+
</activity>
159+
160+
</application>
161+
</manifest>
162+
```
163+
164+
### Web
165+
166+
On the web, you need a specific endpoint to capture the OAuth2 callback. To set this up, create an HTML file (e.g., `auth.html`) inside your project's `./web` folder and add the following content:
167+
168+
```html
169+
<!DOCTYPE html>
170+
<title>Authentication complete</title>
171+
<p>Authentication is complete. If this does not happen automatically, please close the window.</p>
172+
<script>
173+
function postAuthenticationMessage() {
174+
const message = {
175+
'flutter-web-auth-2': window.location.href
176+
};
177+
178+
if (window.opener) {
179+
window.opener.postMessage(message, window.location.origin);
180+
window.close();
181+
} else if (window.parent && window.parent !== window) {
182+
window.parent.postMessage(message, window.location.origin);
183+
} else {
184+
localStorage.setItem('flutter-web-auth-2', window.location.href);
185+
window.close();
186+
}
187+
}
188+
189+
postAuthenticationMessage();
190+
</script>
191+
```
192+
193+
:::note
194+
You only need a single callback file (e.g. `auth.html`) in your `./web` folder.
195+
This file is shared across all IDPs that use the OAuth2 utility, as long as your redirect URIs point to it.
196+
:::
197+
198+
## Present the authentication UI
199+
200+
### Initializing the `GitHubSignInService`
201+
202+
To use the GitHubSignInService, you need to initialize it in your main function. The initialization is done from the `initializeGitHubSignIn()` extension method on the `FlutterAuthSessionManager`.
203+
204+
```dart
205+
import 'package:flutter/material.dart';
206+
import 'package:flutter/material.dart';
207+
import 'package:serverpod_flutter/serverpod_flutter.dart';
208+
import 'package:your_client/your_client.dart';
209+
210+
late Client client;
211+
212+
void main() async {
213+
WidgetsFlutterBinding.ensureInitialized();
214+
215+
// Create the Serverpod client
216+
client = Client('http://localhost:8080/')
217+
..connectivityMonitor = FlutterConnectivityMonitor()
218+
..authSessionManager = FlutterAuthSessionManager();
219+
220+
// Initialize Serverpod auth
221+
await client.auth.initialize();
222+
223+
// Initialize GitHub Sign-In
224+
// Note: For Web, ensure the redirectUri matches your auth.html location.
225+
await client.auth.initializeGitHubSignIn(
226+
clientId: 'YOUR_GITHUB_CLIENT_ID',
227+
redirectUri: Uri.parse('https://example.com/auth.html'),
228+
);
229+
230+
runApp(const MyApp());
231+
}
232+
```
233+
234+
:::info
235+
**Important**: Ensure the redirect URIs used in your code are also explicitly listed in your **GitHub App Dashboard** under "Callback URLs". For Android, you must also register this scheme in your `AndroidManifest.xml`.
236+
:::
237+
238+
### Using GitHubSignInWidget
239+
240+
If you have configured the `GitHubSignInWidget` as described in the [setup section](#present-the-authentication-ui), the GitHub identity provider will be automatically detected and displayed in the sign-in widget.
241+
242+
You can also use the `GitHubSignInWidget` to include the GitHub authentication flow in your own custom UI.
243+
244+
```dart
245+
import 'package:serverpod_auth_idp_flutter/serverpod_auth_idp_flutter.dart';
246+
247+
GitHubSignInWidget(
248+
client: client,
249+
onAuthenticated: () {
250+
// Do something when the user is authenticated.
251+
//
252+
// NOTE: You should not navigate to the home screen here, otherwise
253+
// the user will have to sign in again every time they open the app.
254+
},
255+
onError: (error) {
256+
// Handle errors
257+
ScaffoldMessenger.of(context).showSnackBar(
258+
SnackBar(content: Text('Error: $error')),
259+
);
260+
},
261+
)
262+
```
263+
264+
The widget automatically handles:
265+
266+
- GitHub Sign-In flow for iOS, macOS, Android, and Web.
267+
- Token management.
268+
- Underlying GitHub Sign-In package error handling.
269+
270+
For details on how to customize the GitHub Sign-In UI in your Flutter app, see the [customizing the UI section](./customizing-the-ui).
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# Configuration
2+
3+
This page covers configuration options for the GitHub identity provider beyond the basic setup.
4+
5+
## Configuration options
6+
7+
Below is a non-exhaustive list of some of the most common configuration options. For more details on all options, check the `GitHubIdpConfig` in-code documentation.
8+
9+
### Custom Account Validation
10+
11+
You can customize the validation for GitHub account details before allowing sign-in. By default, the validation checks that the received account details contain a non-empty userIdentifier.
12+
13+
```dart
14+
final githubIdpConfig = GitHubIdpConfig(
15+
// Optional: Custom validation for GitHub account details
16+
githubAccountDetailsValidation: (GitHubAccountDetails accountDetails) {
17+
// Throw an exception if account doesn't meet custom requirements
18+
if (accountDetails.userIdentifier.isEmpty) {
19+
throw GitHubUserInfoMissingDataException();
20+
}
21+
},
22+
);
23+
```
24+
25+
:::note
26+
GitHub users can keep their email private, so email may be null even for valid accounts. To avoid blocking real users with private profiles from signing in, adjust your validation function with care.
27+
:::
28+
29+
### GitHubAccountDetails
30+
31+
The `githubAccountDetailsValidation` callback receives a `GitHubAccountDetails` record with the following properties:
32+
33+
| Property | Type | Description |
34+
| ---------- | ------ | ------------- |
35+
| `userIdentifier` | `String` | The GitHub user's unique identifier (UID) |
36+
| `email` | `String?` | The user's email address (may be null if private) |
37+
| `name` | `String?` | The user's display name from GitHub |
38+
| `image` | `Uri?` | URL to the user's profile image |
39+
40+
Example of accessing these properties:
41+
42+
```dart
43+
githubAccountDetailsValidation: (accountDetails) {
44+
print('GitHub UID: ${accountDetails.userIdentifier}');
45+
print('Email: ${accountDetails.email}');
46+
print('Display name: ${accountDetails.name}');
47+
print('Profile image: ${accountDetails.image}');
48+
49+
// Custom validation logic
50+
if (accountDetails.email == null) {
51+
throw GitHubUserInfoMissingDataException();
52+
}
53+
},
54+
```
55+
56+
:::info
57+
The properties available depend on user privacy settings and granted permissions.
58+
:::
59+
60+
### Configuring Client IDs on the App
61+
62+
#### Passing Client IDs in Code
63+
64+
You can pass the `clientId` and `redirectUri` directly during initialization the GitHub Sign-In service:
65+
66+
```dart
67+
await client.auth.initializeGitHubSignIn(
68+
clientId: 'YOUR_GITHUB_CLIENT_ID',
69+
redirectUri: 'test-app://github/auth',
70+
);
71+
```
72+
73+
This approach is useful when you need different client IDs per platform and want to manage them in your Dart code.
74+
75+
#### Using Environment Variables
76+
77+
Alternatively, you can pass client IDs during build time using the `--dart-define` option. The GitHub Sign-In provider supports the following environment variables:
78+
79+
- `GITHUB_CLIENT_ID`: Your GitHub OAuth client ID.
80+
- `GITHUB_REDIRECT_URI`: The callback URI.
81+
82+
**Example usage:**
83+
84+
```bash
85+
flutter run -d <device> \
86+
--dart-define="GITHUB_CLIENT_ID=your_id" \
87+
--dart-define="GITHUB_REDIRECT_URI=test-app://github/auth"
88+
```
89+
90+
This approach is useful when you need to:
91+
92+
- Manage separate client IDs for different platforms (Android, iOS, Web) in a centralized way
93+
- Avoid committing client IDs to version control
94+
- Configure different credentials for different build environments (development, staging, production)
95+
96+
:::tip
97+
You can also set these environment variables in your IDE's run configuration or CI/CD pipeline to avoid passing them manually each time.
98+
:::

0 commit comments

Comments
 (0)