sessionize-auth
Version:
A flexible session management library for React, Next.js, Angular, and React Native
523 lines (415 loc) โข 11.6 kB
Markdown
# ๐ SSO (Single Sign-On) Documentation
Sessionize Auth v2.0 includes a powerful SSO system that supports multiple OAuth 2.0 providers with a clean, extensible architecture.
## ๐ Quick Start
### Installation
```bash
npm install sessionize-auth
```
### Basic Setup
```tsx
import { SSOManager, useSSO, SSOProviderList } from 'sessionize-auth';
// Configure SSO providers
const ssoManager = new SSOManager({
providers: [
{
id: 'google',
name: 'Google',
clientId: 'your-google-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['openid', 'email', 'profile']
}
]
});
// Use in your component
function LoginPage() {
const { providers, loginWithProvider } = useSSO(ssoManager);
const handleSSOLogin = async (providerId: string) => {
const result = await loginWithProvider(providerId);
if (result.success && result.user) {
// Handle successful login
console.log('User logged in:', result.user);
}
};
return (
<SSOProviderList
providers={providers}
onProviderLogin={handleSSOLogin}
/>
);
}
```
## ๐ฏ Supported Providers
### Google OAuth 2.0
```tsx
const googleProvider = {
id: 'google',
name: 'Google',
clientId: 'your-google-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['openid', 'email', 'profile']
};
```
**Setup Steps:**
1. Go to [Google Cloud Console](https://console.cloud.google.com/)
2. Create a new project or select existing one
3. Enable Google+ API
4. Create OAuth 2.0 credentials
5. Add your redirect URI to authorized redirect URIs
### Microsoft Azure AD
```tsx
const microsoftProvider = {
id: 'microsoft',
name: 'Microsoft',
clientId: 'your-microsoft-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['openid', 'email', 'profile', 'User.Read']
};
```
**Setup Steps:**
1. Go to [Azure Portal](https://portal.azure.com/)
2. Navigate to Azure Active Directory
3. Go to App registrations
4. Create a new registration
5. Add redirect URI and configure permissions
### GitHub OAuth 2.0
```tsx
const githubProvider = {
id: 'github',
name: 'GitHub',
clientId: 'your-github-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['user:email', 'read:user']
};
```
**Setup Steps:**
1. Go to [GitHub Developer Settings](https://github.com/settings/developers)
2. Create a new OAuth App
3. Set Authorization callback URL
4. Copy Client ID and Client Secret
## ๐ ๏ธ Advanced Configuration
### Custom Provider
```tsx
import { BaseSSOProvider } from 'sessionize-auth';
class CustomSSOProvider extends BaseSSOProvider {
protected getProviderName(): string {
return 'Custom Provider';
}
protected getProviderIcon(): string {
return 'https://example.com/icon.png';
}
protected getProviderColor(): string {
return '#FF6B6B';
}
protected getScopes(): string[] {
return ['read', 'write'];
}
protected getAuthUrl(): string {
return 'https://api.example.com/oauth/authorize';
}
protected getTokenUrl(): string {
return 'https://api.example.com/oauth/token';
}
protected getUserInfoUrl(): string {
return 'https://api.example.com/user';
}
protected parseUserInfo(data: any, accessToken: string): SSOUser {
return {
id: data.id,
email: data.email,
name: data.name,
provider: 'custom',
providerId: data.id,
accessToken: accessToken
};
}
protected getCustomParams(): Record<string, string> {
return {
custom_param: 'value'
};
}
}
```
### SSO Manager Configuration
```tsx
const ssoManager = new SSOManager({
providers: [
// Your providers here
],
defaultRedirectPath: '/dashboard',
stateParam: 'state',
codeParam: 'code',
errorParam: 'error',
popupMode: false,
popupWidth: 500,
popupHeight: 600
});
```
## ๐จ Components
### SSOButton
```tsx
import { SSOButton } from 'sessionize-auth';
<SSOButton
provider={provider}
onLogin={handleLogin}
isLoading={isLoading}
disabled={disabled}
className="custom-sso-button"
style={{ backgroundColor: '#custom-color' }}
/>
```
### SSOProviderList
```tsx
import { SSOProviderList } from 'sessionize-auth';
<SSOProviderList
providers={providers}
onProviderLogin={handleProviderLogin}
isLoading={isLoading}
layout="grid" // 'vertical' | 'horizontal' | 'grid'
showLabels={true}
/>
```
### SSOCallback
```tsx
import { SSOCallback } from 'sessionize-auth';
<SSOCallback
ssoManager={ssoManager}
onSuccess={(result) => console.log('Login successful:', result)}
onError={(error) => console.error('Login failed:', error)}
loadingComponent={<CustomLoadingSpinner />}
errorComponent={(error) => <CustomErrorDisplay error={error} />}
successComponent={(result) => <CustomSuccessDisplay result={result} />}
/>
```
## ๐ง Hooks
### useSSO
```tsx
import { useSSO } from 'sessionize-auth';
function MyComponent() {
const {
providers,
isLoading,
error,
loginWithProvider,
handleCallback,
refreshToken,
getUserInfo,
clearError
} = useSSO(ssoManager);
// Use the hook methods
}
```
### useSSOCallback
```tsx
import { useSSOCallback } from 'sessionize-auth';
function CallbackPage() {
const { result, isProcessing } = useSSOCallback(ssoManager);
if (isProcessing) {
return <div>Processing...</div>;
}
if (result?.success) {
return <div>Login successful!</div>;
}
return <div>Login failed: {result?.error}</div>;
}
```
## ๐ Security Features
### State Parameter Validation
The SSO system automatically generates and validates state parameters to prevent CSRF attacks:
```tsx
// State is automatically generated and validated
const authUrl = ssoManager.generateAuthUrl('google');
// Contains: ?state=randomly-generated-state
```
### Token Management
```tsx
// Automatic token refresh
const newToken = await ssoManager.refreshToken('google', refreshToken);
// Get user info with current token
const userInfo = await ssoManager.getUserInfo('google', accessToken);
```
### Error Handling
```tsx
try {
const result = await loginWithProvider('google');
if (!result.success) {
console.error('Login failed:', result.error);
}
} catch (error) {
console.error('Unexpected error:', error);
}
```
## ๐ฏ Authentication Modes
### Redirect Mode (Default)
```tsx
// User is redirected to provider's login page
const result = await loginWithProvider('google');
// After login, user is redirected back to your app
```
### Popup Mode
```tsx
// Login opens in a popup window
const result = await loginWithProvider('google', undefined, true);
// Popup closes automatically after login
```
## ๐ Integration with Session Management
```tsx
import { useAuth, useSSO } from 'sessionize-auth';
function LoginPage() {
const { login } = useAuth();
const { providers, loginWithProvider } = useSSO(ssoManager);
const handleSSOLogin = async (providerId: string) => {
const result = await loginWithProvider(providerId);
if (result.success && result.user) {
// Integrate with session management
login(result.user);
}
};
return (
<SSOProviderList
providers={providers}
onProviderLogin={handleSSOLogin}
/>
);
}
```
## ๐งช Testing
### Mock Providers
```tsx
// For testing, you can create mock providers
const mockProvider = {
id: 'mock',
name: 'Mock Provider',
clientId: 'mock-client-id',
redirectUri: 'http://localhost:3000/auth/callback',
scopes: ['read']
};
const mockSSOManager = new SSOManager({
providers: [mockProvider]
});
```
### Testing SSO Flow
```tsx
import { render, screen, fireEvent } from '@testing-library/react';
import { SSOProviderList } from 'sessionize-auth';
test('SSO login flow', async () => {
const mockOnLogin = jest.fn();
render(
<SSOProviderList
providers={providers}
onProviderLogin={mockOnLogin}
/>
);
const googleButton = screen.getByText('Continue with Google');
fireEvent.click(googleButton);
expect(mockOnLogin).toHaveBeenCalledWith('google');
});
```
## ๐ Best Practices
### 1. Secure Configuration
```tsx
// Use environment variables for sensitive data
const ssoManager = new SSOManager({
providers: [
{
id: 'google',
name: 'Google',
clientId: process.env.REACT_APP_GOOGLE_CLIENT_ID,
redirectUri: process.env.REACT_APP_REDIRECT_URI,
scopes: ['openid', 'email', 'profile']
}
]
});
```
### 2. Error Handling
```tsx
const handleSSOLogin = async (providerId: string) => {
try {
const result = await loginWithProvider(providerId);
if (result.success) {
// Handle success
} else {
// Handle error
showError(result.error);
}
} catch (error) {
// Handle unexpected errors
showError('An unexpected error occurred');
}
};
```
### 3. Loading States
```tsx
function LoginPage() {
const { providers, loginWithProvider, isLoading } = useSSO(ssoManager);
return (
<div>
{isLoading && <LoadingSpinner />}
<SSOProviderList
providers={providers}
onProviderLogin={loginWithProvider}
isLoading={isLoading}
/>
</div>
);
}
```
## ๐ API Reference
### SSOManager
```tsx
class SSOManager {
constructor(config: SSOConfig)
getProviders(): SSOProvider[]
getProvider(providerId: string): SSOProvider | null
generateAuthUrl(providerId: string, returnTo?: string): string
handleCallback(providerId: string, code: string, state: string): Promise<SSOAuthResult>
refreshToken(providerId: string, refreshToken: string): Promise<{ accessToken: string; expiresIn?: number }>
getUserInfo(providerId: string, accessToken: string): Promise<SSOUser>
updateConfig(newConfig: Partial<SSOConfig>): void
}
```
### Types
```tsx
interface SSOProvider {
id: string;
name: string;
icon?: string;
color?: string;
scopes: string[];
authUrl: string;
tokenUrl: string;
userInfoUrl: string;
clientId: string;
redirectUri: string;
}
interface SSOUser {
id: string;
email: string;
name: string;
avatar?: string;
provider: string;
providerId: string;
accessToken?: string;
refreshToken?: string;
expiresAt?: number;
}
interface SSOAuthResult {
success: boolean;
user?: SSOUser;
error?: string;
provider?: string;
}
```
## ๐ค Contributing
We welcome contributions to the SSO system! Please see our [Contributing Guide](./CONTRIBUTING.md) for details.
### Adding New Providers
1. Create a new provider class extending `BaseSSOProvider`
2. Implement all required abstract methods
3. Add the provider to the exports
4. Update documentation and tests
## ๐ Support
- **Documentation**: [README.md](./README.md)
- **Issues**: [GitHub Issues](https://github.com/Katumbela/sessionize-auth/issues)
- **Discussions**: [GitHub Discussions](https://github.com/Katumbela/sessionize-auth/discussions)
- **Email**: [ja3328173@gmail.com](mailto:ja3328173@gmail.com)
---
**Made with โค๏ธ by [Joao Afonso Katombela](https://github.com/Katumbela)**