diff --git a/packages/browser/README.md b/packages/browser/README.md index 64f2dca7..fea57340 100644 --- a/packages/browser/README.md +++ b/packages/browser/README.md @@ -45,4 +45,4 @@ authClient.signOut(); ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/express/README.md b/packages/express/README.md index 04f1fb77..11819211 100644 --- a/packages/express/README.md +++ b/packages/express/README.md @@ -21,52 +21,6 @@ pnpm add @asgardeo/express yarn add @asgardeo/express ``` -## Quick Start - -```javascript -import { AsgardeoExpressClient } from "@asgardeo/express"; - -// Initialize the client -const authClient = new AsgardeoExpressClient({ - clientId: "", - clientSecret: "", - baseUrl: "https://api.asgardeo.io/t/", - callbackURL: "http://localhost:3000/callback" -}); - -// Example Express.js integration -import express from "express"; -const app = express(); - -// Login endpoint -app.get("/login", (req, res) => { - const authUrl = authClient.getSignInUrl(); - res.redirect(authUrl); -}); - -// Callback handler -app.get("/callback", async (req, res) => { - try { - const { code } = req.query; - const tokens = await authClient.exchangeAuthorizationCode(code); - // Store tokens and redirect to home page - res.redirect("/"); - } catch (error) { - res.status(500).send("Authentication failed"); - } -}); - -// Get user info -app.get("/userinfo", async (req, res) => { - try { - const userInfo = await authClient.getUserInfo(); - res.json(userInfo); - } catch (error) { - res.status(401).send("Unauthorized"); - } -}); -``` - ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/javascript/README.md b/packages/javascript/README.md index 13be756d..d72b3861 100644 --- a/packages/javascript/README.md +++ b/packages/javascript/README.md @@ -8,50 +8,11 @@ License -## Installation - -```bash -# Using npm -npm install @asgardeo/javascript - -# or using pnpm -pnpm add @asgardeo/javascript - -# or using yarn -yarn add @asgardeo/javascript -``` - -## Quick Start - -```javascript -import { AsgardeoAuth } from "@asgardeo/javascript"; - -// Initialize the auth instance -const auth = new AsgardeoAuth({ - afterSignInUrl: "https://localhost:3000", - clientId: "", - baseUrl: "https://api.asgardeo.io/t/" -}); - -// Handle authentication -auth.signIn() - .then(() => { - // Handle successful sign in - }) - .catch((error) => { - // Handle sign in error - }); - -// Get authenticated user -auth.getUser() - .then((userInfo) => { - console.log(userInfo); - }); - -// Sign out -auth.signOut(); -``` +> [!IMPORTANT] +> ⚠️ Do not directly use this in your applications. +> `@asgardeo/javascript` is a framework agnostic SDK that provides core authentication functionalities. +> For framework-specific integrations, consider using the dedicated SDKs such as `@asgardeo/react`, `@asgardeo/next`, etc. ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/nextjs/README.md b/packages/nextjs/README.md index 336a678a..90e2b135 100644 --- a/packages/nextjs/README.md +++ b/packages/nextjs/README.md @@ -8,140 +8,14 @@ License -## Installation - -```bash -# Using npm -npm install @asgardeo/nextjs - -# or using pnpm -pnpm add @asgardeo/nextjs - -# or using yarn -yarn add @asgardeo/nextjs -``` - ## Quick Start -### Option 1: Provider-based Configuration (Recommended) - -1. Create a `.env.local` file with your Asgardeo configuration: - -```bash -NEXT_PUBLIC_ASGARDEO_BASE_URL=https://api.asgardeo.io/t/ -NEXT_PUBLIC_ASGARDEO_CLIENT_ID= -NEXT_PUBLIC_ASGARDEO_CLIENT_SECRET= -``` - -2. Add the `AsgardeoProvider` to your root layout with configuration: - -```tsx -// app/layout.tsx -import { AsgardeoProvider } from '@asgardeo/nextjs'; - -export default function RootLayout({ children }: { children: React.ReactNode }) { - const asgardeoConfig = { - baseUrl: process.env.NEXT_PUBLIC_ASGARDEO_BASE_URL, - clientId: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_ID, - clientSecret: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_SECRET, - afterSignInUrl: process.env.NEXT_PUBLIC_ASGARDEO_AFTER_SIGN_IN_URL || 'http://localhost:3000', - }; - - return ( - - - - {children} - - - - ); -} -``` - -3. Create a simple `middleware.ts` file in your project root: - -```typescript -import { asgardeoMiddleware } from '@asgardeo/nextjs/middleware'; - -export default asgardeoMiddleware; - -export const config = { - matcher: [ - // Skip Next.js internals and all static files, unless found in search params - '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', - // Always run for API routes - '/(api|trpc)(.*)', - ], -}; -``` - -### Option 2: Middleware-based Configuration - -2. Then create a `middleware.ts` file in your project root to handle authentication: - -```typescript -import { createAsgardeoMiddleware } from '@asgardeo/nextjs/middleware'; - -const middleware = createAsgardeoMiddleware({ - baseUrl: process.env.NEXT_PUBLIC_ASGARDEO_BASE_URL, - clientId: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_ID, - clientSecret: process.env.NEXT_PUBLIC_ASGARDEO_CLIENT_SECRET, - afterSignInUrl: 'http://localhost:3000', -}); - -export { middleware }; - -export const config = { - matcher: [ - '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)', - '/(api|trpc)(.*)', - ], -}; -``` - -3. Add `SignInButton` and `SignOutButton` buttons to your app - -```tsx -import styles from './page.module.css'; -import {SignInButton, SignedIn, SignOutButton, SignedOut} from '@asgardeo/nextjs'; - -export default function Home() { - return ( -
-
-
- - Sign In - - - Sign Out - -
-
-
- ); -} -``` - -## Server-side Usage - -You can access the Asgardeo client instance in server actions and other server-side code: - -```typescript -import { getAsgardeoClient } from '@asgardeo/nextjs/server'; - -export async function getUserProfile() { - const client = getAsgardeoClient(); - const user = await client.getUser(); - return user; -} -``` +Get started with Asgardeo in your Next.js application in minutes. Follow our [Next.js Quick Start Guide](https://wso2.com/asgardeo/docs/quick-starts/nextjs/) for step-by-step instructions on integrating authentication into your app. -## Architecture +## API Documentation -The SDK uses a singleton pattern for the `AsgardeoNextClient` to ensure consistent authentication state across your application. The client is automatically initialized when you provide configuration through the `AsgardeoProvider` or through the middleware configuration. +For complete API documentation including all components, hooks, and customization options, see the [Next.js SDK Documentation](https://wso2.com/asgardeo/docs/sdks/nextjs/overview). ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/node/README.md b/packages/node/README.md index 9e1dc1c1..2a1acebb 100644 --- a/packages/node/README.md +++ b/packages/node/README.md @@ -8,65 +8,11 @@ License -## Installation - -```bash -# Using npm -npm install @asgardeo/node - -# or using pnpm -pnpm add @asgardeo/node - -# or using yarn -yarn add @asgardeo/node -``` - -## Quick Start - -```javascript -import { AsgardeoNodeClient } from "@asgardeo/node"; - -// Initialize the client -const authClient = new AsgardeoNodeClient({ - clientId: "", - clientSecret: "", - baseUrl: "https://api.asgardeo.io/t/", - callbackURL: "http://localhost:3000/callback" -}); - -// Example Express.js integration -import express from "express"; -const app = express(); - -// Login endpoint -app.get("/login", (req, res) => { - const authUrl = authClient.getSignInUrl(); - res.redirect(authUrl); -}); - -// Callback handler -app.get("/callback", async (req, res) => { - try { - const { code } = req.query; - const tokens = await authClient.exchangeAuthorizationCode(code); - // Store tokens and redirect to home page - res.redirect("/"); - } catch (error) { - res.status(500).send("Authentication failed"); - } -}); - -// Get user info -app.get("/userinfo", async (req, res) => { - try { - const userInfo = await authClient.getUserInfo(); - res.json(userInfo); - } catch (error) { - res.status(401).send("Unauthorized"); - } -}); -``` +> [!IMPORTANT] +> ⚠️ Do not directly use this in your applications. +> `@asgardeo/node` is a framework agnostic SDK that provides core authentication functionalities. +> For framework-specific integrations, consider using the dedicated SDKs such as `@asgardeo/express`, etc. ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/nuxt/README.md b/packages/nuxt/README.md index 956364b3..21d1383e 100644 --- a/packages/nuxt/README.md +++ b/packages/nuxt/README.md @@ -8,19 +8,6 @@ License -## Installation - -```bash -# Using npm -npm install @asgardeo/nuxt - -# or using pnpm -pnpm add @asgardeo/nuxt - -# or using yarn -yarn add @asgardeo/nuxt -``` - ## License -Apache-2.0 +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/react-router/README.md b/packages/react-router/README.md index b1d5f7ce..19c72796 100644 --- a/packages/react-router/README.md +++ b/packages/react-router/README.md @@ -5,232 +5,10 @@ React Router integration for Asgardeo React SDK with protected routes. [![npm version](https://img.shields.io/npm/v/@asgardeo/react-router.svg)](https://www.npmjs.com/package/@asgardeo/react-router) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -## Overview - -`@asgardeo/react-router` is a supplementary package that provides seamless integration between Asgardeo authentication and React Router. It offers components to easily protect routes and handle authentication flows in your React applications. - -## Features - -- πŸ›‘οΈ **ProtectedRoute Component**: Drop-in replacement for React Router's Route with built-in authentication -- ⚑ **TypeScript Support**: Full TypeScript support with comprehensive type definitions -- 🎨 **Customizable**: Flexible configuration options for different use cases -- πŸ”’ **Authentication Guards**: Built-in authentication checking with loading states -- πŸš€ **Lightweight**: Minimal bundle size with essential features only - -## Installation - -```bash -npm install @asgardeo/react-router -# or -yarn add @asgardeo/react-router -# or -pnpm add @asgardeo/react-router -``` - -### Peer Dependencies - -This package requires the following peer dependencies: - -```bash -npm install @asgardeo/react react react-router -``` - ## Quick Start -### 1. Basic Setup with ProtectedRoute - -```tsx -import React from 'react'; -import { BrowserRouter, Routes, Route } from 'react-router-dom'; -import { AsgardeoProvider } from '@asgardeo/react'; -import { ProtectedRoute } from '@asgardeo/react-router'; -import Dashboard from './components/Dashboard'; -import Profile from './components/Profile'; -import SignIn from './components/SignIn'; - -function App() { - return ( - - - - Public Home Page} /> - } /> - - - - } - /> - - - - } - /> - - - - ); -} - -export default App; -``` - -### 2. Custom Fallback and Loading States - -```tsx -import { ProtectedRoute } from '@asgardeo/react-router'; - -// Redirect to custom login page - - - - } -/> - -// Custom fallback component - -

Please sign in

-

You need to be signed in to access this page.

- - }> - - - } -/> - -// Custom loading state -Loading...} - > - - - } -/> -``` - -### 3. Integration with Layouts - -```tsx -import { ProtectedRoute } from '@asgardeo/react-router'; - -function App() { - return ( - - - {/* Public routes */} - } /> - } /> - } /> - - {/* Protected routes with layout */} - }> - - - - } - /> - - - - } - /> - - - - } - /> - - - - ); -} -``` - -## API Reference - -### Components - -#### ProtectedRoute - -A component that protects routes based on authentication status. Should be used as the element prop of a Route component. - -```tsx -interface ProtectedRouteProps { - children: React.ReactElement; - fallback?: React.ReactElement; - redirectTo?: string; - loader?: React.ReactNode; -} -``` - -**Props:** - -- `children` - The component to render when authenticated -- `fallback` - Custom component to render when not authenticated (takes precedence over redirectTo) -- `redirectTo` - URL to redirect to when not authenticated (required unless fallback is provided) -- `loader` - Custom loading component to render while authentication status is being determined - -**Note:** Either `fallback` or `redirectTo` must be provided to handle unauthenticated users. - -## Examples - -Check out our sample applications in the repository: - -- [React Sample](../../samples/asgardeo-react) - Complete React application with Asgardeo authentication -- [Next.js Sample](../../samples/asgardeo-nextjs) - Next.js application example -- [Teamspace React](../../samples/teamspace-react) - Team collaboration app with React -- [Teamspace Next.js](../../samples/teamspace-nextjs) - Team collaboration app with Next.js - -## TypeScript Support - -This package is written in TypeScript and provides comprehensive type definitions. All components are fully typed for the best development experience. - -```tsx -import type { ProtectedRouteProps } from '@asgardeo/react-router'; -``` - -## Contributing - -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details. +Get started with protected routes in your React application. Follow our [Protecting Routes Guide](https://wso2.com/asgardeo/docs/sdks/react/guides/protecting-routes/) for step-by-step instructions on securing your React Router routes with Asgardeo authentication. ## License -This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details. - -## Support - -- πŸ“– [Documentation](https://wso2.com/asgardeo/docs/sdks/react/) -- πŸ’¬ [Community Forum](https://stackoverflow.com/questions/tagged/asgardeo) -- πŸ› [Issues](https://github.com/asgardeo/javascript/issues) - ---- - -Built with ❀️ by the [Asgardeo](https://wso2.com/asgardeo/) team. +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/react/API.md b/packages/react/API.md deleted file mode 100644 index e0d7ee9f..00000000 --- a/packages/react/API.md +++ /dev/null @@ -1,877 +0,0 @@ -# `@asgardeo/react` API Documentation - -This document provides complete API documentation for the Asgardeo React SDK, including all components, hooks, and customization options. - -## Table of Contents - -- [Components](#components) - - [AsgardeoProvider](#asgardeoprovider) - - [SignIn](#signin) - - [SignedIn](#signedin) - - [SignedOut](#signedout) - - [SignInButton](#signinbutton) - - [SignOutButton](#signoutbutton) - - [User](#user) - - [UserProfile](#userprofile) - - [Loaded](#loaded) - - [Loading](#loading) -- [Hooks](#hooks) - - [useAsgardeo](#useasgardeo) -- [Customization](#customization) - -## Components - -### AsgardeoProvider - -The root provider component that configures the Asgardeo SDK and provides authentication context to your React application. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `baseUrl` | `string` | Yes | Your Asgardeo organization URL | -| `clientId` | `string` | Yes | Your application's client ID | -| `afterSignInUrl` | `string` | No | URL to redirect after sign in (defaults to current URL) | -| `afterSignOutUrl` | `string` | No | URL to redirect after sign out (defaults to current URL) | -| `scopes` | `string[] \| string` | No | OAuth scopes to request (defaults to `'openid profile internal_login'`) | -| `storage` | `'localStorage' \| 'sessionStorage'` | No | Storage mechanism for tokens (defaults to `'localStorage'`) | - -#### Example - -##### Minimal Setup - -Following is a minimal setup with the mandatory configuration for the `AsgardeoProvider` in your main application file (e.g., `index.tsx`): - -```diff -import { StrictMode } from 'react'; -import { createRoot } from 'react-dom/client'; -+ import { AsgardeoProvider } from '@asgardeo/react'; -import App from './App'; - -const root = createRoot(document.getElementById('root')); - -root.render( - -+ - -+ - -); -``` - -##### Advanced Usage - -For more advanced configurations, you can specify additional props like `afterSignInUrl`, `afterSignOutUrl`, and `scopes`: - -```diff -import { StrictMode } from 'react'; -import { createRoot } from 'react-dom/client'; -+ import { AsgardeoProvider } from '@asgardeo/react'; -import App from './App'; - -const root = createRoot(document.getElementById('root')); - -root.render( - -+ - -+ - -); -``` - - -**Customization:** See [Customization](#customization) section for theming and styling options. The provider doesn't render any visual elements but can be styled through CSS custom properties. - -#### Available CSS Classes -This component doesn't render any HTML elements with CSS classes. Configuration is handled through props and CSS custom properties. - ---- - -### SignIn - -A comprehensive sign-in component that renders a complete sign-in interface with customizable styling and behavior. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `className` | `string` | No | CSS class name for styling the sign-in container | -| `redirectUrl` | `string` | No | URL to redirect after successful sign-in | -| `onSignInStart` | `() => void` | No | Callback fired when sign-in process starts | -| `onSignInSuccess` | `(user: User) => void` | No | Callback fired when sign-in is successful | -| `onSignInError` | `(error: Error) => void` | No | Callback fired when sign-in fails | -| `buttonText` | `string` | No | Custom text for the sign-in button (defaults to "Sign In") | -| `loadingText` | `string` | No | Text to show while signing in (defaults to "Signing in...") | -| `disabled` | `boolean` | No | Whether the sign-in interface is disabled | - -#### Example - -```diff -+ import { SignIn } from '@asgardeo/react'; - -const SignInPage = () => { - const handleSignInSuccess = (user) => { - console.log('User signed in:', user.username); - // Redirect to dashboard or update UI - }; - - const handleSignInError = (error) => { - console.error('Sign-in failed:', error.message); - // Show error message to user - }; - - return ( -
-

Welcome Back

-+ -
- ); -}; - -export default SignInPage; -``` - -**Customization:** See [Customization](#customization) for comprehensive styling and theming options. - -#### Available CSS Classes -- `.asgardeo-signin` - Main sign-in container -- `.asgardeo-signin--small` - Small size variant -- `.asgardeo-signin--large` - Large size variant -- `.asgardeo-signin--outlined` - Outlined variant -- `.asgardeo-signin--filled` - Filled variant -- `.asgardeo-signin__input` - Input field elements -- `.asgardeo-signin__input--small` - Small input variant -- `.asgardeo-signin__input--large` - Large input variant -- `.asgardeo-signin__button` - Sign-in button element -- `.asgardeo-signin__button--small` - Small button variant -- `.asgardeo-signin__button--large` - Large button variant -- `.asgardeo-signin__button--outlined` - Outlined button variant -- `.asgardeo-signin__button--filled` - Filled button variant -- `.asgardeo-signin__error` - Error message container -- `.asgardeo-signin__messages` - Messages container - ---- - -### SignedIn - -A conditional rendering component that only displays its children when the user is authenticated. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `children` | `React.ReactNode` | Yes | Content to render when user is signed in | -| `fallback` | `React.ReactNode` | No | Content to render while loading | - -#### Example - -```diff -+ import { SignedIn } from '@asgardeo/react'; -import Dashboard from './components/Dashboard'; -import LoadingSpinner from './components/LoadingSpinner'; - -const App = () => { - return ( -
-+ -+ -+

Checking authentication...

-+
-+ }> - -+ - - ); -}; - -export default App; -``` - -**Customization:** See [Customization](#customization) for styling the fallback loading state. - -#### Available CSS Classes -This component doesn't render any HTML elements with CSS classes. It conditionally renders children or fallback content. - ---- - -### SignedOut - -A conditional rendering component that only displays its children when the user is not authenticated. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `children` | `React.ReactNode` | Yes | Content to render when user is signed out | - -#### Example - -```diff -+ import { SignedOut } from '@asgardeo/react'; -import LandingPage from './components/LandingPage'; -import Hero from './components/Hero'; - -const App = () => { - return ( -
-+ - - -+ -
- ); -}; - -export default App; -``` - -**Customization:** See [Customization](#customization) for styling options. - -#### Available CSS Classes -This component doesn't render any HTML elements with CSS classes. It conditionally renders children when user is signed out. - ---- - -### SignInButton - -A pre-built button component that triggers the sign-in flow when clicked. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `children` | `React.ReactNode` | No | Custom button content (defaults to "Sign In") | -| `className` | `string` | No | CSS class name for styling | -| `disabled` | `boolean` | No | Whether the button is disabled | -| `onClick` | `() => void` | No | Additional click handler | - -#### Example - -```diff -+ import { SignInButton } from '@asgardeo/react'; - -const LoginPage = () => { - const handleClick = () => { - console.log('Sign-in button clicked'); - }; - - return ( -
-

Welcome to Our App

-

Please sign in to continue

- -+ -+ πŸ” Log In to Continue -+ -
- ); -}; - -export default LoginPage; -``` - -**Customization:** See [Customization](#customization) for theming and styling the sign-in button. - -#### Available CSS Classes -- `.asgardeo-sign-in-button` - Main sign-in button element - ---- - -### SignOutButton - -A pre-built button component that triggers the sign-out flow when clicked. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `children` | `React.ReactNode` | No | Custom button content (defaults to "Sign Out") | -| `className` | `string` | No | CSS class name for styling | -| `disabled` | `boolean` | No | Whether the button is disabled | -| `onClick` | `() => void` | No | Additional click handler | - -#### Example - -```diff -+ import { SignOutButton } from '@asgardeo/react'; - -const UserMenu = () => { - const handleSignOut = () => { - console.log('User signed out'); - // Additional cleanup logic - }; - - return ( -
-

Account Settings

- -+ -+ πŸšͺ Logout -+ -
- ); -}; - -export default UserMenu; -``` - -**Customization:** See [Customization](#customization) for theming and styling the sign-out button. - -#### Available CSS Classes -- `.asgardeo-sign-out-button` - Main sign-out button element - ---- - -### User - -A render prop component that provides access to the current user's information. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `children` | `({ user, isLoading, error }) => React.ReactNode` | Yes | Render function that receives user data | - -#### Render Props - -| Prop | Type | Description | -|------|------|-------------| -| `user` | `User \| null` | Current user object | -| `isLoading` | `boolean` | Whether user data is being loaded | -| `error` | `Error \| null` | Any error that occurred while fetching user data | - -#### User Object Properties - -| Property | Type | Description | -|----------|------|-------------| -| `sub` | `string` | User's unique identifier | -| `username` | `string` | Username | -| `email` | `string` | Email address | -| `givenname` | `string` | First name | -| `familyname` | `string` | Last name | -| `photourl` | `string` | Profile picture URL | - -#### Example - -```diff -+ import { User } from '@asgardeo/react'; - -const UserProfile = () => { - return ( -
-

User Profile

- -+ -+ {({ user, isLoading, error }) => { - if (isLoading) { - return ( -
-
-

Loading user information...

-
- ); - } - - if (error) { - return ( -
-

Error loading user: {error.message}

- -
- ); - } - - if (!user) { - return
No user data available
; - } - - return ( -
- {user.username} -

{user.givenname} {user.familyname}

-

@{user.username}

-

{user.email}

-
- ); -+ }} -+ -
- ); -}; - -export default UserProfile; -``` - -**Customization:** See [Customization](#customization) for styling user information displays. - -#### Available CSS Classes -This component doesn't render any HTML elements with CSS classes. It uses render props to provide user data to children. - ---- - -### UserProfile - -A pre-built component that displays a formatted user profile card. - -#### Props - -| Prop | Type | Required | Description | -|------|------|----------|-------------| -| `className` | `string` | No | CSS class name for styling | -| `showEmail` | `boolean` | No | Whether to display email (defaults to `true`) | -| `showAvatar` | `boolean` | No | Whether to display profile picture (defaults to `true`) | -| `avatarSize` | `'sm' \| 'md' \| 'lg'` | No | Size of the avatar (defaults to `'md'`) | - -#### Example - -```diff -+ import { UserProfile } from '@asgardeo/react'; - -const Header = () => { - return ( -
-
-

My Dashboard

- -
-+ -
-
-
- ); -}; - -const ProfileCard = () => { - return ( -
-

Profile Information

- -+ -
- ); -}; - -export { Header, ProfileCard }; -``` - -**Customization:** See [Customization](#customization) for comprehensive styling options for the user profile component. - -#### Available CSS Classes -- `.asgardeo-user-profile` - Main user profile container element - ---- - -## Hooks - -### useAsgardeo - -The main hook that provides access to all authentication functionality and state. - -#### Returns - -| Property | Type | Description | -|----------|------|-------------| -| `user` | `User \| null` | Current user object | -| `isSignedIn` | `boolean` | Whether user is authenticated | -| `isLoading` | `boolean` | Whether authentication state is being determined | -| `error` | `Error \| null` | Any authentication error | -| `signIn` | `(redirectUrl?: string) => Promise` | Function to initiate sign in | -| `signOut` | `(redirectUrl?: string) => Promise` | Function to sign out | -| `getAccessToken` | `() => Promise` | Get current access token | -| `getIdToken` | `() => Promise` | Get current ID token | -| `refreshTokens` | `() => Promise` | Refresh authentication tokens | - -#### Example - -```diff -+ import { useAsgardeo } from '@asgardeo/react'; -import { useState } from 'react'; - -const AuthenticatedApp = () => { -+ const { -+ user, -+ isSignedIn, -+ isLoading, -+ error, -+ signIn, -+ signOut, -+ getAccessToken -+ } = useAsgardeo(); - - const [apiData, setApiData] = useState(null); - const [apiLoading, setApiLoading] = useState(false); - - const handleApiCall = async () => { - try { - setApiLoading(true); - const token = await getAccessToken(); - - const response = await fetch('/api/protected-data', { - headers: { - 'Authorization': `Bearer ${token}`, - 'Content-Type': 'application/json', - }, - }); - - const data = await response.json(); - setApiData(data); - } catch (err) { - console.error('API call failed:', err); - } finally { - setApiLoading(false); - } - }; - - const handleSignOut = async () => { - await signOut('/goodbye'); - }; - - if (isLoading) { - return ( -
-
-

Initializing authentication...

-
- ); - } - - if (error) { - return ( -
-

Authentication Error

-

{error.message}

- -
- ); - } - - return ( -
- {isSignedIn ? ( -
-
-

Welcome, {user?.givenname}!

- -
- -
-
- - - {apiData && ( -
-                  {JSON.stringify(apiData, null, 2)}
-                
- )} -
-
-
- ) : ( -
-

Welcome to Our App

-

Please sign in to access your dashboard

- -
- )} -
- ); -}; - -export default AuthenticatedApp; -``` - ---- - -## Customization - -The Asgardeo React SDK provides multiple ways to customize the appearance and behavior of components to match your application's design system. - -### CSS Classes and Styling - -All components accept a `className` prop that allows you to apply custom CSS styles: - -```tsx - - Sign In - - - -``` - -### Default CSS Classes - -Components come with default CSS classes that you can target for styling: - -- `.asgardeo-signin-button` - Sign in button -- `.asgardeo-signout-button` - Sign out button -- `.asgardeo-user-profile` - User profile container -- `.asgardeo-user-avatar` - User avatar image -- `.asgardeo-user-info` - User information container - -### CSS Custom Properties (CSS Variables) - -The SDK supports CSS custom properties for consistent theming: - -```css -:root { - --asgardeo-primary-color: #007bff; - --asgardeo-primary-hover: #0056b3; - --asgardeo-border-radius: 8px; - --asgardeo-font-family: 'Inter', sans-serif; - --asgardeo-button-padding: 12px 24px; - --asgardeo-avatar-size-sm: 32px; - --asgardeo-avatar-size-md: 48px; - --asgardeo-avatar-size-lg: 64px; -} -``` - -### Custom Button Content - -Replace default button text with custom content: - -```tsx - - πŸ” - Login with Asgardeo - - - - - Sign Out - -``` - -### Bring your own UI Library - -For applications using popular UI libraries, you can leverage render props for maximum flexibility and control: - -#### Material-UI Integration with Render Props -```tsx -import { Button, CircularProgress } from '@mui/material' -import { SignIn } from '@asgardeo/react' - -function CustomSignInButton() { - return ( - - {({ signIn, isLoading, error }) => ( - - )} - - ) -} -``` - -#### Tailwind CSS Integration with Render Props -```tsx -import { SignIn } from '@asgardeo/react' - -function TailwindSignInButton() { - return ( - - {({ signIn, isLoading, error }) => ( -
- - {error && ( -

{error.message}

- )} -
- )} -
- ) -} -``` - -#### Ant Design Integration with Render Props -```tsx -import { Button, Alert } from 'antd' -import { SignIn } from '@asgardeo/react' - -function AntdSignInButton() { - return ( - - {({ signIn, isLoading, error }) => ( -
- - {error && ( - - )} -
- )} -
- ) -} -``` - -#### Chakra UI Integration with Render Props -```tsx -import { Button, Alert, AlertIcon, Spinner } from '@chakra-ui/react' -import { SignIn } from '@asgardeo/react' - -function ChakraSignInButton() { - return ( - - {({ signIn, isLoading, error }) => ( -
- - {error && ( - - - {error.message} - - )} -
- )} -
- ) -} -``` - -### Custom Loading States - -Customize loading indicators for better user experience: - -```tsx - - - Authenticating... -
-}> - - -``` - -### Advanced Customization with Render Props - -Use the `User` component for complete control over user data presentation: - -```tsx - - {({ user, isLoading }) => ( -
- {isLoading ? ( - - ) : ( -
- -
-

{user?.givenname} {user?.familyname}

- {user?.email} -
-
- )} -
- )} -
-``` - -### Configuration-Based Customization - -Customize behavior through the `AsgardeoProvider` configuration: - -```tsx - - - -``` - -This comprehensive customization approach ensures that Asgardeo components can seamlessly integrate with any design system or UI framework while maintaining functionality and accessibility standards. diff --git a/packages/react/README.md b/packages/react/README.md index 5568f3eb..538ab19d 100644 --- a/packages/react/README.md +++ b/packages/react/README.md @@ -8,126 +8,14 @@ License
-## Installation - -```bash -# Using npm -npm install @asgardeo/react - -# or using pnpm -pnpm add @asgardeo/react - -# or using yarn -yarn add @asgardeo/react -``` - ## Quick Start -1. Add `` to your app - -```tsx -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.tsx' -import { AsgardeoProvider } from '@asgardeo/react' - -createRoot(document.getElementById('root')).render( - - ' - clientId: '' - > - - - -) -``` - -2. Add signed-in and signed-out to your app - -```tsx -import { SignedIn, SignedOut, SignInButton, SignOutButton } from '@asgardeo/react' -import './App.css' - -function App() { - return ( - <> - - - - - - - - ) -} - -export default App -``` - -3. Start using other drop-in components like `User`, `UserProfile`, etc. - -```tsx -import { User, UserProfile } from '@asgardeo/react' -import './App.css' - -function App() { - return ( - <> - - {({ user }) => ( -
-

Welcome, {user.username}

- -
- )} -
- - - - ) -} -export default App -``` - -## Using the `useAsgardeo` Hook (For Programmatic Control) - -For more granular control, you can use the useAsgardeo hook. This hook provides direct access to SDK's functions and state: - -```tsx -import { useAsgardeo } from '@asgardeo/react' -import './App.css' - -function App() { - const { user, signIn, signOut, isSignedIn, isLoading } = useAsgardeo() - - if (isLoading) { - return
Loading...
- } - - return ( -
- {isSignedIn ? ( -
-
- {user.username} -

Welcome back, {user.givenname}

-
- -
- ) : ( - - )} -
- ) -} -``` +Get started with Asgardeo in your React application in minutes. Follow our [React Quick Start Guide](https://wso2.com/asgardeo/docs/quick-starts/react/) for step-by-step instructions on integrating authentication into your app. -## Documentation +## API Documentation -For complete API documentation including all components, hooks, and customization options, see [API.md](./API.md). +For complete API documentation including all components, hooks, and customization options, see the [React SDK Documentation](https://wso2.com/asgardeo/docs/sdks/react/overview). ## License -Licenses this source under the Apache License, Version 2.0 [LICENSE](../../LICENSE), You may not use this file except in compliance with the License. +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/react/docs/README.md b/packages/react/docs/README.md deleted file mode 100644 index f149c2f9..00000000 --- a/packages/react/docs/README.md +++ /dev/null @@ -1,19 +0,0 @@ -# @asgardeo/react - Overview - -The Asgardeo React SDK provides a comprehensive set of hooks, components, and utilities to integrate Asgardeo authentication into your React applications. Built on top of the `@asgardeo/browser` SDK, it offers a React-specific wrapper with pre-built components and React hooks for seamless authentication experiences. - -## Features - -- πŸ” **Complete Authentication Flow**: Sign-in, sign-up, and sign-out functionality -- 🎨 **Pre-built Components**: Ready-to-use UI components for authentication -- πŸͺ **React Hooks**: Powerful hooks for authentication state management -- 🌐 **Multi-language Support**: Built-in internationalization (i18n) support -- 🎭 **Theming & Branding**: Customizable themes and branding options -- 🏒 **Organization Management**: Support for organization-based authentication -- πŸ“± **Social Login**: Built-in support for popular social providers -- πŸ”’ **Type Safe**: Full TypeScript support for better developer experience -- ⚑ **Performance Optimized**: Efficient re-rendering and state management - -## What's Next - -- [Quickstart Guide](./getting-started/overview.md): Get started with a simple integration. diff --git a/packages/react/docs/components/OVERVIEW.md b/packages/react/docs/components/OVERVIEW.md deleted file mode 100644 index bf7887d9..00000000 --- a/packages/react/docs/components/OVERVIEW.md +++ /dev/null @@ -1,59 +0,0 @@ -# Components Overview - -The Asgardeo React SDK provides a comprehensive set of components to handle authentication, user management, and organization features in your React applications. The components are organized into different categories based on their functionality. - -## Root Components - -Root components are the entry points for integrating Asgardeo authentication into your React application. They provide the necessary context and configuration for the SDK. - -- [**`AsgardeoProvider`**](./asgardeo-provider.md) - The main provider component that wraps your application, providing authentication context and configuration. - -## Action Components - -Action components trigger specific authentication-related actions when users interact with them. - -### Sign-In Components - -- **`SignInButton`** - A customizable button that initiates the sign-in flow -- **`SignUpButton`** - A button for user registration flows -- **`SignOutButton`** - A button that handles user sign-out - -These components support both render props and traditional props patterns, giving you flexibility in how you implement them. - -## Control Components - -Control components manage the conditional rendering of content based on authentication state. - -- **`SignedIn`** - Renders children only when the user is authenticated -- **`SignedOut`** - Renders children only when the user is not authenticated -- **`Loading`** - Shows loading state during authentication operations - -## Presentation Components - -Presentation components display user and organization information with built-in styling and functionality. - -### User Components - -- **`User`** - Provides render props access to user data -- **`UserProfile`** - Displays comprehensive user profile information -- **`UserDropdown`** - A dropdown menu with user info and actions - -### Organization Components - -- **`Organization`** - Displays organization information -- **`OrganizationProfile`** - Shows detailed organization profile -- **`OrganizationSwitcher`** - Allows switching between organizations -- **`OrganizationList`** - Lists available organizations -- **`CreateOrganization`** - Form for creating new organizations - -### Authentication UI Components - -- **`SignIn`** - Complete sign-in form with multiple authentication options -- **`SignUp`** - User registration form - -## Next Steps - -- [Explore Action Components](./actions/) - Learn about sign-in, sign-out, and sign-up buttons -- [Learn Control Components](./control/) - Understand conditional rendering based on auth state -- [Discover Presentation Components](./presentation/) - Explore user and organization display components -- [Customize with Primitives](./primitives/) - Use low-level UI components for custom implementations diff --git a/packages/react/docs/components/asgardeo-provider.md b/packages/react/docs/components/asgardeo-provider.md deleted file mode 100644 index a4000622..00000000 --- a/packages/react/docs/components/asgardeo-provider.md +++ /dev/null @@ -1,150 +0,0 @@ -# AsgardeoProvider - -The `AsgardeoProvider` is the root context provider component that configures the Asgardeo React SDK and provides authentication context to your entire React application. It must wrap your application to enable authentication features. - -## Overview - -The `AsgardeoProvider` initializes the Asgardeo authentication client, manages authentication state, and provides context to child components through React Context. It handles token management, user sessions, organization switching, and branding preferences automatically. - -## Props - -All props are based on the `AsgardeoReactConfig` interface, which extends the base configuration from `@asgardeo/javascript`. - -### Required Props - -| Prop | Type | Default | Description | -|------|------|---------|-------------| -| `baseUrl` | `string` | **REQUIRED** | The base URL of your Asgardeo organization. Format: `https://api.asgardeo.io/t/{org_name}` | -| `clientId` | `string` | **REQUIRED** | The client ID obtained from your Asgardeo application registration | -| `afterSignInUrl` | `string` | `window.location.origin` | URL to redirect users after successful sign-in. Must match configured redirect URIs in Asgardeo | -| `afterSignOutUrl` | `string` | `window.location.origin` | URL to redirect users after sign-out. Must match configured post-logout redirect URIs | -| `scopes` | `string \| string[]` | `openid profile internal_login` | OAuth scopes to request during authentication (e.g., `"openid profile email"` or `["openid", "profile", "email"]`) | -| `organizationHandle` | `string` | - | Organization handle for organization-specific features like branding. Auto-derived from `baseUrl` if not provided. Required for custom domains | -| `applicationId` | `string` | - | UUID of the Asgardeo application for application-specific branding and features | -| `signInUrl` | `string` | - | Custom sign-in page URL. If provided, users will be redirected here instead of Asgardeo's default sign-in page | -| `signUpUrl` | `string` | - | Custom sign-up page URL. If provided, users will be redirected here instead of Asgardeo's default sign-up page | -| `clientSecret` | `string` | - | Client secret for confidential clients. Not recommended for browser applications | -| `tokenValidation` | [TokenValidation](#tokenvalidation) | - | Token validation configuration for ID tokens including validation flags and clock tolerance | -| `preferences` | [Preferences](#preferences) | - | Configuration object for theming, internationalization, and UI customization | - -
- -

TokenValidation

- -The `tokenValidation` prop allows you to configure how ID tokens are validated. - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `idToken` | `IdTokenValidation` | `{}` | Configuration for ID token validation | - -#### IdTokenValidation - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `validate` | `boolean` | `true` | Whether to validate the ID token | -| `validateIssuer` | `boolean` | `true` | Whether to validate the issuer | -| `clockTolerance` | `number` | `300` | Allowed clock skew in seconds | - -
- -
- -

Preferences

- -The `preferences` prop allows you to customize the UI components provided by the SDK. - -#### Theme Preferences (`preferences.theme`) - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `inheritFromBranding` | `boolean` | `true` | Whether to inherit theme from Asgardeo organization/application branding | -| `mode` | `'light' \| 'dark' \| 'system'` | `'system'` | Theme mode. `'system'` follows user's OS preference | -| `overrides` | `ThemeConfig` | `{}` | Custom theme overrides for colors, typography, spacing, etc. | - -#### Internationalization Preferences (`preferences.i18n`) - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `language` | `string` | Browser default | Language code for UI text (e.g., `'en-US'`, `'es-ES'`) | -| `fallbackLanguage` | `string` | `'en-US'` | Fallback language when translations aren't available | -| `bundles` | `object` | `{}` | Custom translation bundles to override default text | - -
- -## Usage - -### Basic Setup - -```tsx -import React from 'react'; -import { createRoot } from 'react-dom/client'; -import { AsgardeoProvider } from '@asgardeo/react'; -import App from './App'; - -const root = createRoot(document.getElementById('root')); - -root.render( - - - -); -``` - -### Advanced Configuration - -```tsx -import React from 'react'; -import { AsgardeoProvider } from '@asgardeo/react'; -import App from './App'; - -function MyApp() { - return ( - - - - ); -} -``` - -### Environment Variables - -You can use environment variables for configuration: - -```tsx - - - -``` diff --git a/packages/react/docs/components/sign-in-button.md b/packages/react/docs/components/sign-in-button.md deleted file mode 100644 index 64dc0a98..00000000 --- a/packages/react/docs/components/sign-in-button.md +++ /dev/null @@ -1,338 +0,0 @@ -# SignInButton - -The `SignInButton` component provides a pre-built, customizable button that handles user authentication through the Asgardeo identity provider. It supports both render props and traditional props patterns, making it flexible for various UI implementations. - -## Overview - -The `SignInButton` component automatically integrates with the Asgardeo authentication context and handles the sign-in flow including loading states, error handling, and redirection. It leverages the `useAsgardeo` hook to access authentication methods and can be customized with preferences for internationalization and theming. - -## Basic Usage - -### Traditional Props Pattern - -```tsx -import React from 'react'; -import { SignInButton } from '@asgardeo/react'; - -function LoginPage() { - return ( -
-

Welcome to Our App

- Sign In -
- ); -} -``` - -### With Custom Styling - -```tsx -import React from 'react'; -import { SignInButton } from '@asgardeo/react'; - -function CustomLoginPage() { - return ( - - Get Started - - ); -} -``` - -## Advanced Usage - -### Render Props Pattern - -The render props pattern gives you full control over the button's appearance and behavior while still leveraging the authentication logic: - -```tsx -import React from 'react'; -import { SignInButton } from '@asgardeo/react'; - -function AdvancedLoginPage() { - return ( - - {({ signIn, isLoading }) => ( - - )} - - ); -} -``` - -### Custom Click Handler - -```tsx -import React from 'react'; -import { SignInButton } from '@asgardeo/react'; - -function TrackingLoginPage() { - const handleSignInClick = (event) => { - // Track analytics event - analytics.track('sign_in_button_clicked'); - console.log('User initiated sign-in process'); - }; - - return ( - - Sign In - - ); -} -``` - -### Component-Level Internationalization - -```tsx -import React from 'react'; -import { SignInButton } from '@asgardeo/react'; - -function LocalizedLoginPage() { - return ( - - {/* Will use localized text from preferences */} - - ); -} -``` - -## Props - -The `SignInButton` component accepts all standard HTML button attributes plus the following: - -### SignInButtonProps - -| Prop | Type | Default | Description | -|------|------|---------|-------------| -| `children` | `ReactNode \| ((props: RenderProps) => ReactNode)` | Localized "Sign In" text | Button content or render function | -| `onClick` | `(event: MouseEvent) => void` | - | Custom click handler called after sign-in initiation | -| `className` | `string` | - | Additional CSS classes to apply to the button | -| `style` | `CSSProperties` | - | Inline styles to apply to the button | -| `preferences` | `Preferences` | - | Component-level configuration for theming and internationalization | -| `disabled` | `boolean` | `false` | Whether the button is disabled (overridden during loading) | -| `type` | `"button" \| "submit" \| "reset"` | `"button"` | HTML button type | - -### Render Props - -When using the render props pattern, the function receives the following props: - -| Prop | Type | Description | -|------|------|-------------| -| `signIn` | `() => Promise` | Function to initiate the sign-in process | -| `isLoading` | `boolean` | Whether the sign-in process is currently in progress | - -## Preferences - -The `preferences` prop allows you to customize the component's behavior and appearance. - -| Property | Type | Default | Description | -|----------|------|---------|-------------| -| `i18n` | `I18nConfig` | - | Internationalization configuration for custom translations | -| `theme` | `ThemeConfig` | - | Theme configuration for styling customization | - -### I18nConfig - -| Property | Type | Description | -|----------|------|-------------| -| `bundles` | `Record }>` | Translation bundles keyed by locale | - -For the SignInButton, the relevant translation key is: - -- `elements.buttons.signIn` - The default button text - - -## Behavior - -### Authentication Flow - -1. **Initial State**: Button displays with default or custom text -2. **Click Event**: User clicks the button, triggering the sign-in process -3. **Loading State**: Button becomes disabled and shows loading indicator -4. **Navigation**: User is redirected to Asgardeo sign-in page or custom sign-in URL -5. **Completion**: After successful authentication, user returns to the application - -### Custom Sign-In URL - -If a `signInUrl` is configured in the `AsgardeoProvider`, the button will navigate to that URL instead of initiating the OAuth flow directly: - -```tsx -// In your AsgardeoProvider configuration - - - -``` - -### Error Handling - -The component automatically handles sign-in errors and throws an `AsgardeoRuntimeError` with detailed information: - -```tsx -// Error details include: -// - Error message -// - Error code: 'SignInButton-handleSignIn-RuntimeError-001' -// - Package: 'react' -// - User-friendly message -``` - -## Accessibility - -The `SignInButton` component includes accessibility features: - -- **Keyboard Navigation**: Fully keyboard accessible -- **Screen Readers**: Proper ARIA attributes and semantic HTML -- **Loading States**: Disabled state prevents multiple submissions -- **Focus Management**: Maintains focus states for keyboard users - -## Integration with BaseSignInButton - -The `SignInButton` is built on top of `BaseSignInButton`, which provides the core functionality. If you need more control or want to build a custom implementation, you can use `BaseSignInButton` directly: - -```tsx -import React, { useState } from 'react'; -import { BaseSignInButton } from '@asgardeo/react'; -import { useAsgardeo } from '@asgardeo/react'; - -function CustomSignInButton() { - const { signIn } = useAsgardeo(); - const [isLoading, setIsLoading] = useState(false); - - const handleSignIn = async () => { - setIsLoading(true); - try { - await signIn(); - } finally { - setIsLoading(false); - } - }; - - return ( - - Custom Sign In Implementation - - ); -} -``` - -## Best Practices - -### 1. Consistent Styling - -Maintain consistent button styling across your application: - -```tsx -// Create a styled wrapper -const StyledSignInButton = styled(SignInButton)` - background: var(--primary-color); - color: white; - border-radius: 8px; - padding: 12px 24px; - font-weight: 600; - - &:hover { - background: var(--primary-hover-color); - } -`; -``` - -### 2. Loading States - -Always provide clear feedback during the sign-in process: - -```tsx - - {({ isLoading }) => ( - <> - {isLoading && } - {isLoading ? 'Signing in...' : 'Sign In'} - - )} - -``` - -### 3. Error Boundaries - -Wrap your authentication components in error boundaries to handle potential errors gracefully: - -```tsx -Something went wrong}> - Sign In - -``` - -### 4. Responsive Design - -Ensure your sign-in button works well on all device sizes: - -```tsx - - Sign In - -``` - -## Common Issues - -### Button Not Working - -- Ensure `AsgardeoProvider` is properly configured and wrapping your component -- Check that all required configuration props are provided -- Verify network connectivity and Asgardeo service availability - -### Custom Styling Not Applied - -- Check CSS specificity and ensure your styles are not being overridden -- Use browser developer tools to inspect the rendered element -- Consider using CSS-in-JS solutions or CSS modules for better style isolation - -### Translation Not Showing - -- Verify the translation key `elements.buttons.signIn` exists in your bundles -- Check that the locale is correctly set in your preferences -- Ensure the `preferences` prop is passed correctly - -## Related Components - -- [`AsgardeoProvider`](./asgardeo-provider.md) - Required context provider for authentication -- [`BaseSignInButton`](#integration-with-basesigninbutton) - Lower-level component for custom implementations -- [`SignOutButton`](./sign-out-button.md) - Companion component for signing out users diff --git a/packages/react/docs/getting-started/QUICKSTART.md b/packages/react/docs/getting-started/QUICKSTART.md deleted file mode 100644 index 36a4ee18..00000000 --- a/packages/react/docs/getting-started/QUICKSTART.md +++ /dev/null @@ -1,184 +0,0 @@ -# React Quickstart - -Welcome to the React Quickstart guide! In this document, you will learn to build a React app, add user sign-in and display user profile information using Asgardeo. - -## What You Will Learn - -- Create new React app using Vite -- Install @asgardeo/react package -- Add user sign-in and sign-out -- Display user profile information - -## Prerequisites - -Before you start, ensure you have the following: - -- About 15 minutes -- Asgardeo account -- Install Node.js on your system -- Make sure you have a JavaScript package manager like npm, yarn, or pnpm -- A favorite text editor or IDE - -## Example Source Code - -[React Vite App Sample](../../samples/) - -## 1. Configure an Application in Asgardeo - -1. Sign into the Asgardeo Console and navigate to **Applications** > **New Application**. -2. Select **React** and complete the wizard by providing a suitable name and an authorized redirect URL. - -**Example:** - -- Name: `asgardeo-react` -- Authorized redirect URL: `http://localhost:5173` - -Once you finish creating the application, note down the following values from its **Guide** tab. You will need them to configure Asgardeo React SDK. - -- **Client ID** - The unique identifier for your application. -- **Base URL** - The base URL of your Asgardeo organization. This typically follows the format `https://api.asgardeo.io/t/` - -> **Info**: The authorized redirect URL determines where Asgardeo should send users after they successfully log in. Typically, this will be the web address where your app is hosted. For this guide, we'll use `http://localhost:5173`, as the sample app will be accessible at this URL. - -## 2. Create a React App Using Vite - -Create (scaffold) your new React app using Vite: - -```bash -npm create vite@latest asgardeo-react -- --template react -cd asgardeo-react -npm install -npm run dev -``` - -## 3. Install @asgardeo/react - -Asgardeo React SDK provides all the components and hooks you need to integrate Asgardeo into your app. To get started, simply add the Asgardeo React SDK to the project. Make sure to stop the dev server you started in the previous step. - -```bash -# Using npm -npm install @asgardeo/react - -# Using pnpm -pnpm add @asgardeo/react - -# Using yarn -yarn add @asgardeo/react -``` - -## 4. Add `` to Your App - -The `` serves as a context provider for the SDK. You can integrate this provider to your app by wrapping the root component. - -Add the following changes to the `main.jsx` file. - -> **Important**: Replace below placeholders with your registered organization name in Asgardeo and the generated client-id from the app you registered in Asgardeo. -> -> - `` -> - `https://api.asgardeo.io/t/` - -```jsx -import { StrictMode } from 'react' -import { createRoot } from 'react-dom/client' -import './index.css' -import App from './App.jsx' -import { AsgardeoProvider } from '@asgardeo/react' - -createRoot(document.getElementById('root')).render( - - - - - -) -``` - -## 5. Add Sign-In and Sign-Out to Your App - -Asgardeo SDK provides `SignInButton`, `SignOutButton` components to handle user sign-in and sign-out. You can use these components alongside `SignedIn` and `SignedOut` components to conditionally render content based on the user's logged in state. - -Replace the existing content of the `App.jsx` file with following content: - -```jsx -import { SignedIn, SignedOut, SignInButton, SignOutButton } from '@asgardeo/react' -import './App.css' - -function App() { - return ( -
- - - - - - -
- ) -} - -export default App -``` - -## 6. Display Signed-In User's Profile Information - -You can use the `User`, `UserProfile`, or `UserDropdown` components to access and display user profile information in a declarative way. - -- **User**: The `User` component provides a render prop pattern to access user profile information: -- **UserProfile**: The `UserProfile` component provides a declarative way to display and update user profile information. -- **UserDropdown**: The `UserDropdown` component provides a dropdown menu with built-in user information and sign-out functionality. - -```jsx -import { SignedIn, SignedOut, SignInButton, SignOutButton, User, UserDropdown, UserProfile } from '@asgardeo/react' -import './App.css' - -function App() { - return ( - <> -
- - - - - - - -
-
- - - {(user) => ( -
-

Welcome back, {user.userName || user.username || user.sub}

-
- )} -
- -
-
- - ) -} - -export default App -``` - -## 7. Run the App - -To run the app, use the following command: - -```bash -npm run dev -``` - -Visit your app's homepage at [http://localhost:5173](http://localhost:5173). - -> **Important**: To try out sign-in and sign-out features, create a test user in Asgardeo by following [this guide](https://wso2.com/asgardeo/docs/guides/users/manage-users/#onboard-a-user). - -## What's Next? - -Now that you have basic authentication working, you can: - -- [Explore all available components](../components/overview.md) to enhance your app. diff --git a/packages/react/docs/guides/accessing-protected-apis.md b/packages/react/docs/guides/accessing-protected-apis.md deleted file mode 100644 index ac7ae391..00000000 --- a/packages/react/docs/guides/accessing-protected-apis.md +++ /dev/null @@ -1,264 +0,0 @@ -# Accessing Protected APIs - -This guide shows how to make authenticated API calls to protected resources using the Asgardeo React SDK. The SDK provides an authenticated `http` module that automatically handles authentication headers and token refresh. - -## Overview - -When your application is wrapped with `AsgardeoProvider`, you can use the `useAsgardeo` hook to access the authenticated `http` module. This module has the following features: - -- Includes the necessary authentication headers (Bearer token) -- Handles token refresh when tokens expire -- Provides methods like `request()` and `requestAll()` for making API calls - -## Basic Usage - -```tsx -import React, { useEffect, useState } from 'react'; -import { useAsgardeo } from '@asgardeo/react'; - -export default function UserProfile() { - const { http, isSignedIn } = useAsgardeo(); - const [userData, setUserData] = useState(null); - - useEffect(() => { - if (!isSignedIn) { - return; - } - - (async () => { - try { - const response = await http.request({ - url: 'https://api.asgardeo.io/t//scim2/Me', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - }, - method: 'GET', - }); - - setUserData(response.data); - } catch (error) { - console.error('Error fetching user data:', error); - } - })(); - }, [http, isSignedIn]); - - if (!isSignedIn) { - return
Please sign in to view your profile.
; - } - - return ( -
-

User Profile

- {userData && ( -
{JSON.stringify(userData, null, 2)}
- )} -
- ); -} -``` - -## Multiple API Calls with `requestAll()` - -When you need to make multiple API calls simultaneously, you can use the `http.requestAll()` method: - -```tsx -import React, { useEffect, useState } from 'react'; -import { useAsgardeo } from '@asgardeo/react'; - -export default function UserProfile() { - const { http, isSignedIn } = useAsgardeo(); - const [userData, setUserData] = useState({ - profile: null, - discoverableApplications: [], - }); - - useEffect(() => { - if (!isSignedIn) { - return; - } - - const requests = []; - - requests.push({ - headers: { - Accept: 'application/json', - 'Content-Type': 'application/json', - }, - method: 'GET', - url: 'https://api.asgardeo.io/t//api/users/v1/me/applications', - }); - - requests.push({ - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - }, - method: 'GET', - url: 'https://api.asgardeo.io/t//scim2/Me', - }); - - (async () => { - try { - const response = await http.requestAll(requests); - - setUserData({ - discoverableApplications: response[0].data.applications, - profile: response[1].data, - }); - } catch (error) { - console.error('Error fetching data:', error); - } - })(); - }, [http, isSignedIn]); - - return
{JSON.stringify(userData, null, 4)}
; -} -``` - -## Making Different Types of API Calls - -### GET Request - -```tsx -const fetchUsers = async () => { - try { - const response = await http.request({ - url: 'https://api.asgardeo.io/t//scim2/Users', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - }, - method: 'GET', - }); - - return response.data; - } catch (error) { - console.error('Error fetching users:', error); - throw error; - } -}; -``` - -### POST Request - -```tsx -const createUser = async (userData) => { - try { - const response = await http.request({ - url: 'https://api.asgardeo.io/t//scim2/Users', - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - }, - method: 'POST', - data: userData, - }); - - return response.data; - } catch (error) { - console.error('Error creating user:', error); - throw error; - } -}; -``` - -### PUT Request - -```tsx -const updateUser = async (userId, userData) => { - try { - const response = await http.request({ - url: `https://api.asgardeo.io/t//scim2/Users/${userId}`, - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - }, - method: 'PUT', - data: userData, - }); - - return response.data; - } catch (error) { - console.error('Error updating user:', error); - throw error; - } -}; -``` - -### DELETE Request - -```tsx -const deleteUser = async (userId) => { - try { - const response = await http.request({ - url: `https://api.asgardeo.io/t//scim2/Users/${userId}`, - headers: { - Accept: 'application/json', - }, - method: 'DELETE', - }); - - return true; - } catch (error) { - console.error('Error deleting user:', error); - throw error; - } -}; -``` - -## Bring your own HTTP Client - -If you prefer to use your own HTTP client (like the native `fetch` API), you can use the `getAccessToken()` method to manually add the authorization header: - -```tsx -import React, { useEffect, useState } from 'react'; -import { useAsgardeo } from '@asgardeo/react'; - -export default function UserProfile() { - const { isSignedIn, getAccessToken } = useAsgardeo(); - const [userData, setUserData] = useState(null); - - useEffect(() => { - if (!isSignedIn) { - return; - } - - (async () => { - try { - const response = await fetch('https://api.asgardeo.io/t//scim2/Me', { - headers: { - Accept: 'application/json', - 'Content-Type': 'application/scim+json', - Authorization: `Bearer ${await getAccessToken()}`, - }, - method: 'GET', - }); - - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - - const responseData = await response.json(); - - setUserData(responseData); - } catch (error) { - console.error('Error fetching data:', error); - } - })(); - }, [isSignedIn, getAccessToken]); - - if (!isSignedIn) { - return
Please sign in to view your profile.
; - } - - return ( -
-

User Profile

- {userData && ( -
{JSON.stringify(userData, null, 2)}
- )} -
- ); -} -``` diff --git a/packages/tanstack-router/README.md b/packages/tanstack-router/README.md index 434eb38d..3ce85b7b 100644 --- a/packages/tanstack-router/README.md +++ b/packages/tanstack-router/README.md @@ -5,279 +5,10 @@ TanStack Router integration for Asgardeo React SDK with protected routes. [![npm version](https://img.shields.io/npm/v/@asgardeo/tanstack-router.svg)](https://www.npmjs.com/package/@asgardeo/tanstack-router) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -## Overview - -`@asgardeo/tanstack-router` is a supplementary package that provides seamless integration between Asgardeo authentication and TanStack Router. It offers components to easily protect routes and handle authentication flows in your React applications using TanStack Router. - -## Features - -- πŸ›‘οΈ **ProtectedRoute Component**: Drop-in component for TanStack Router with built-in authentication -- ⚑ **TypeScript Support**: Full TypeScript support with comprehensive type definitions -- 🎨 **Customizable**: Flexible configuration options for different use cases -- πŸ”’ **Authentication Guards**: Built-in authentication checking with loading states -- πŸš€ **Lightweight**: Minimal bundle size with essential features only -- πŸ”„ **API Consistency**: Compatible interface with `@asgardeo/react-router` for easy migration - -## Installation - -```bash -npm install @asgardeo/tanstack-router -# or -yarn add @asgardeo/tanstack-router -# or -pnpm add @asgardeo/tanstack-router -``` - -### Peer Dependencies - -This package requires the following peer dependencies: - -```bash -npm install @asgardeo/react @tanstack/react-router react -``` - ## Quick Start -### 1. Basic Setup with ProtectedRoute - -```tsx -import React from 'react'; -import { createRouter, createRoute, createRootRoute } from '@tanstack/react-router'; -import { AsgardeoProvider } from '@asgardeo/react'; -import { ProtectedRoute } from '@asgardeo/tanstack-router'; -import Dashboard from './components/Dashboard'; -import Profile from './components/Profile'; -import SignIn from './components/SignIn'; - -const rootRoute = createRootRoute({ - component: () =>
Root Layout
, -}); - -const indexRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/', - component: () =>
Public Home Page
, -}); - -const signinRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/signin', - component: SignIn, -}); - -const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => ( - - - - ), -}); - -const profileRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/profile', - component: () => ( - - - - ), -}); - -const routeTree = rootRoute.addChildren([ - indexRoute, - signinRoute, - dashboardRoute, - profileRoute, -]); - -const router = createRouter({ routeTree }); - -function App() { - return ( - - - - ); -} - -export default App; -``` - -### 2. Custom Fallback and Loading States - -```tsx -import { ProtectedRoute } from '@asgardeo/tanstack-router'; - -// Redirect to custom login page -const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => ( - - - - ), -}); - -// Custom fallback component -const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => ( - -

Please sign in

-

You need to be signed in to access this page.

- - }> - -
- ), -}); - -// Custom loading state -const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => ( - Loading...} - > - - - ), -}); -``` - -### 3. Integration with Route Layouts - -```tsx -import { ProtectedRoute } from '@asgardeo/tanstack-router'; - -const appLayoutRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/app', - component: AppLayout, -}); - -const appDashboardRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/dashboard', - component: () => ( - - - - ), -}); - -const appProfileRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/profile', - component: () => ( - - - - ), -}); - -const appSettingsRoute = createRoute({ - getParentRoute: () => appLayoutRoute, - path: '/settings', - component: () => ( - - - - ), -}); -``` - -## API Reference - -### Components - -#### ProtectedRoute - -A component that protects routes based on authentication status. Should be used as the component prop of a TanStack Router route. - -```tsx -interface ProtectedRouteProps { - children: React.ReactElement; - fallback?: React.ReactElement; - redirectTo?: string; - loader?: React.ReactNode; -} -``` - -**Props:** - -- `children` - The component to render when authenticated -- `fallback` - Custom component to render when not authenticated (takes precedence over redirectTo) -- `redirectTo` - URL to redirect to when not authenticated (required unless fallback is provided) -- `loader` - Custom loading component to render while authentication status is being determined - -**Note:** Either `fallback` or `redirectTo` must be provided to handle unauthenticated users. - -## Migration from @asgardeo/react-router - -This package provides the same API as `@asgardeo/react-router`, making migration straightforward: - -```tsx -// Before (React Router) - - - - } -/> - -// After (TanStack Router) -const dashboardRoute = createRoute({ - getParentRoute: () => rootRoute, - path: '/dashboard', - component: () => ( - - - - ), -}); -``` - -## Examples - -Check out our sample applications in the repository: - -- [React TanStack Router Sample](../../samples/react-tanstack-router) - Simple React application demonstrating TanStack Router integration with protected routes - -## TypeScript Support - -This package is written in TypeScript and provides comprehensive type definitions. All components are fully typed for the best development experience. - -```tsx -import type { ProtectedRouteProps } from '@asgardeo/tanstack-router'; -``` - -## Contributing - -We welcome contributions! Please see our [Contributing Guide](../../CONTRIBUTING.md) for details. +Get started with protected routes in your React application. Follow our [Protecting Routes Guide](https://wso2.com/asgardeo/docs/sdks/react/guides/protecting-routes/) for step-by-step instructions on securing your TanStack Router routes with Asgardeo authentication. ## License -This project is licensed under the Apache License 2.0. See the [LICENSE](LICENSE) file for details. - -## Support - -- πŸ“– [Documentation](https://wso2.com/asgardeo/docs/sdks/react/) -- πŸ’¬ [Community Forum](https://stackoverflow.com/questions/tagged/asgardeo) -- πŸ› [Issues](https://github.com/asgardeo/javascript/issues) - ---- - -Built with ❀️ by the [Asgardeo](https://wso2.com/asgardeo/) team. \ No newline at end of file +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License. diff --git a/packages/vue/README.md b/packages/vue/README.md index 874ef3df..f2593186 100644 --- a/packages/vue/README.md +++ b/packages/vue/README.md @@ -8,95 +8,6 @@ License -## Installation - -```bash -# Using npm -npm install @asgardeo/vue - -# or using pnpm -pnpm add @asgardeo/vue - -# or using yarn -yarn add @asgardeo/vue -``` - -## Basic Setup - -1. Configure the authentication plugin: - -```typescript -import { createApp } from 'vue' -import { AsgardeoAuth } from '@asgardeo/vue' - -const app = createApp(App) - -app.use(AsgardeoAuth, { - afterSignInUrl: "http://localhost:3000", - afterSignOutUrl: "http://localhost:3000", - clientId: "", - baseUrl: "https://api.asgardeo.io/t/", - scope: ["openid", "profile"] -}) - -app.mount('#app') -``` - -2. Use in your components: - -```vue - - - -``` - -## Composables - -- `useAsgardeo()`: Main composable that provides: - - `isSignedIn`: Boolean indicating authentication status - - `user`: Current user information - - `signIn()`: Function to initiate sign in - - `signOut()`: Function to sign out - - `getAccessToken()`: Function to get the current access token - - `getUser()`: Function to get basic user information - -- `useAuthContext()`: Composable to access the raw authentication context -- `useIsAuthenticated()`: Composable to check authentication status - -## Development - -1. Install dependencies: -```bash -pnpm install -``` - -2. Build: -```bash -pnpm build -``` - -3. Run tests: -```bash -pnpm test -``` - -4. Run development server: -```bash -pnpm dev -``` - ## License -Apache License, Version 2.0 - see [LICENSE](./LICENSE) for details. +Licenses this source under the Apache License, Version 2.0 [LICENSE](./LICENSE), You may not use this file except in compliance with the License.