Tauri Plugin Auth Session API
This package provides the TypeScript API for `tauri-plugin-auth-session`, a Tauri v2 plugin designed for secure in-app OAuth authentication across mobile and desktop platforms. It leverages native browser authentication sessions: `ASWebAuthenticationSession` on macOS and iOS, and Chrome Custom Tabs on Android. The plugin enables a seamless, secure authorization flow by capturing OAuth redirects to custom URL schemes directly within the app, bypassing the need for external browser launches or localhost web server listeners. It's crucial for Tauri v2 mobile development, where traditional desktop OAuth patterns are impractical. The current stable version is 0.2.2, indicating active development within the v0 series, with new features and stability improvements likely tied to the progression of Tauri v2 itself. Key differentiators include a single `start()` API call, native browser security (credentials never touch WebView), SSO support, and full compatibility with PKCE/OAuth 2.0/OIDC providers.
Common errors
-
Plugin 'auth-session' not found or not initialized.
cause The Tauri Rust plugin `tauri-plugin-auth-session` was not correctly added to `src-tauri/Cargo.toml` or not initialized in `src-tauri/src/lib.rs`.fixVerify the Rust installation steps, ensuring both `Cargo.toml` specifies the plugin dependency and `lib.rs` registers `tauri_plugin_auth_session::init()`. -
Cannot find name 'start'.
cause The `start` function was not correctly imported from the `tauri-plugin-auth-session-api` package in your TypeScript/JavaScript file.fixAdd `import { start } from 'tauri-plugin-auth-session-api';` at the top of your relevant source file. -
java.lang.RuntimeException: AuthSessionActivity not found. Did you register the intent filter in AndroidManifest.xml?
cause The `AndroidManifest.xml` for your Android application was not correctly configured with the `intent-filter` for `AuthSessionActivity` and your custom URL scheme.fixAdd the provided `<activity>` and `<intent-filter>` XML snippet, replacing `myapp` with your actual scheme, to `src-tauri/gen/android/app/src/main/AndroidManifest.xml`. -
error invoking 'plugin:auth-session|start': unsupported platform
cause Attempted to call the `start()` function on an unsupported platform (Windows or Linux).fixImplement platform-specific logic (e.g., using `import { platform } from '@tauri-apps/api/os';`) to disable or provide alternative authentication methods when running on Windows or Linux, or ensure error handling is robust. -
ReferenceError: require is not defined
cause Attempting to use CommonJS `require()` syntax in a modern JavaScript or TypeScript project that is configured for ES Modules (ESM).fixReplace `const { start } = require('tauri-plugin-auth-session-api');` with `import { start } from 'tauri-plugin-auth-session-api';`.
Warnings
- breaking This package is the frontend API for `tauri-plugin-auth-session`. You must also install and configure the Rust plugin counterpart in `src-tauri/Cargo.toml` and register it in `src-tauri/src/lib.rs` for the JavaScript API to function.
- breaking For Android, you must manually add an `intent-filter` to `AuthSessionActivity` in your app's `AndroidManifest.xml` to correctly capture OAuth redirect URLs. Failure to do so will prevent the redirect from returning to your application.
- breaking The `tauri-plugin-auth-session` requires the `auth-session:default` capability to be enabled in your Tauri application's `default.json` or other capability file.
- gotcha The plugin's core `start()` function is a stub on Windows and Linux platforms. Calling it on these systems will always result in an error, as the native authentication methods (ASWebAuthenticationSession, Chrome Custom Tabs) are not available.
- gotcha This package relies on `@tauri-apps/api` version `2.0.0` or higher as a peer dependency. Ensure your project has the correct major version installed, specifically `@tauri-apps/api@next` for Tauri v2.
Install
-
npm install tauri-plugin-auth-session-api -
yarn add tauri-plugin-auth-session-api -
pnpm add tauri-plugin-auth-session-api
Imports
- start
const { start } = require('tauri-plugin-auth-session-api');import { start } from 'tauri-plugin-auth-session-api'; - AuthSessionOptions
import { AuthSessionOptions } from 'tauri-plugin-auth-session-api';import type { AuthSessionOptions } from 'tauri-plugin-auth-session-api';
Quickstart
import { start } from 'tauri-plugin-auth-session-api';
/**
* Initiates an OAuth 2.0 PKCE authentication flow with Google.
* Replace placeholders with your actual OAuth provider details.
*
* NOTE: This client-side code assumes a backend will handle the code exchange for tokens.
* For a purely public client, you'd exchange the code directly.
*/
async function authenticateWithGoogle(): Promise<void> {
const clientId = 'YOUR_GOOGLE_CLIENT_ID'; // Replace with your actual client ID
const redirectUri = 'myapp://oauth-callback'; // Must match your native app setup (AndroidManifest, Associated Domains)
const scope = 'openid profile email';
// In a real application, you would securely generate code_verifier and code_challenge
// For simplicity, placeholders are used here.
const codeVerifier = 'YOUR_GENERATED_CODE_VERIFIER';
const codeChallenge = 'YOUR_GENERATED_CODE_CHALLENGE_S256';
const authorizeUrl = `https://accounts.google.com/o/oauth2/v2/auth?` +
`client_id=${clientId}&` +
`redirect_uri=${encodeURIComponent(redirectUri)}&` +
`response_type=code&` +
`scope=${encodeURIComponent(scope)}&` +
`state=secure_random_state_string&` + // Always generate a cryptographically secure state
`code_challenge=${codeChallenge}&` +
`code_challenge_method=S256`;
try {
console.log('Starting OAuth flow...');
const callbackUrl = await start({
authorizeUrl,
redirectUri: redirectUri, // The scheme and host your app will intercept
ephemeral: false // Set to true on Apple platforms for non-SSO sessions
});
console.log('OAuth callback URL received:', callbackUrl);
const url = new URL(callbackUrl);
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
if (code && state) {
console.log('Authorization Code:', code);
console.log('State:', state);
// Now, exchange the 'code' for access/refresh tokens.
// This is typically done on a backend server to keep client secret secure.
} else {
console.error('Authorization code or state not found in callback URL.');
}
} catch (error) {
console.error('OAuth flow failed:', error);
if (error instanceof Error && error.message.includes("unsupported platform")) {
console.warn("Authentication is not supported on this platform (Windows/Linux).");
}
}
}
// Example usage (e.g., triggered by a button click)
// authenticateWithGoogle();