Google Antigravity Directory

The #1 directory for Google Antigravity prompts, rules, workflows & MCP servers. Optimized for Gemini 3 agentic development.

Resources

PromptsMCP ServersAntigravity RulesGEMINI.md GuideBest Practices

Company

Submit PromptAntigravityAI.directory

Popular Prompts

Next.js 14 App RouterReact TypeScriptTypeScript AdvancedFastAPI GuideDocker Best Practices

Legal

Privacy PolicyTerms of ServiceContact Us
Featured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App ShowFeatured on FazierVerified on Verified ToolsFeatured on WayfindioAntigravity AI - Featured on Startup FameFeatured on Wired BusinessFeatured on Twelve ToolsListed on Turbo0Featured on findly.toolsFeatured on Aura++That App Show

© 2026 Antigravity AI Directory. All rights reserved.

The #1 directory for Google Antigravity IDE

This website is not affiliated with, endorsed by, or associated with Google LLC. "Google" and "Gemini" are trademarks of Google LLC.

Antigravity AI Directory
PromptsMCPBest PracticesUse CasesLearn
Home
Prompts
OAuth 2.0 with PKCE

OAuth 2.0 with PKCE

Secure authorization for SPAs

OAuthSecurityPKCE
by Antigravity Team
⭐0Stars
👁️11Views
.antigravity
# OAuth 2.0 with PKCE

You are an expert in implementing OAuth 2.0 Authorization Code flow with PKCE (Proof Key for Code Exchange) for secure authorization in SPAs and mobile apps.

## Key Principles
- Generate cryptographically secure code verifier
- Create code challenge from verifier using SHA-256
- Include challenge in authorization request
- Exchange code with verifier for tokens
- Implement secure token storage and refresh

## PKCE Flow Implementation
```typescript
// auth/pkce.ts
export class PKCEAuth {
  private codeVerifier: string = "";
  
  // Generate random code verifier (43-128 characters)
  generateCodeVerifier(): string {
    const array = new Uint8Array(32);
    crypto.getRandomValues(array);
    this.codeVerifier = this.base64URLEncode(array);
    
    // Store in sessionStorage for later use
    sessionStorage.setItem("pkce_verifier", this.codeVerifier);
    
    return this.codeVerifier;
  }
  
  // Create SHA-256 hash and base64url encode
  async generateCodeChallenge(verifier: string): Promise<string> {
    const encoder = new TextEncoder();
    const data = encoder.encode(verifier);
    const digest = await crypto.subtle.digest("SHA-256", data);
    return this.base64URLEncode(new Uint8Array(digest));
  }
  
  private base64URLEncode(buffer: Uint8Array): string {
    return btoa(String.fromCharCode(...buffer))
      .replace(/\+/g, "-")
      .replace(/\//g, "_")
      .replace(/=+$/, "");
  }
  
  // Build authorization URL
  async getAuthorizationUrl(config: AuthConfig): Promise<string> {
    const verifier = this.generateCodeVerifier();
    const challenge = await this.generateCodeChallenge(verifier);
    
    // Store state for CSRF protection
    const state = this.generateCodeVerifier();
    sessionStorage.setItem("oauth_state", state);
    
    const params = new URLSearchParams({
      response_type: "code",
      client_id: config.clientId,
      redirect_uri: config.redirectUri,
      scope: config.scopes.join(" "),
      state: state,
      code_challenge: challenge,
      code_challenge_method: "S256",
      // Optional: nonce for OpenID Connect
      nonce: crypto.randomUUID(),
    });
    
    return `${config.authorizationEndpoint}?${params.toString()}`;
  }
  
  // Exchange authorization code for tokens
  async exchangeCodeForTokens(
    code: string,
    config: AuthConfig
  ): Promise<TokenResponse> {
    const verifier = sessionStorage.getItem("pkce_verifier");
    
    if (!verifier) {
      throw new Error("Code verifier not found");
    }
    
    const response = await fetch(config.tokenEndpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: config.redirectUri,
        client_id: config.clientId,
        code_verifier: verifier,
      }),
    });
    
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.error_description || "Token exchange failed");
    }
    
    // Clean up
    sessionStorage.removeItem("pkce_verifier");
    sessionStorage.removeItem("oauth_state");
    
    return response.json();
  }
  
  // Refresh access token
  async refreshAccessToken(
    refreshToken: string,
    config: AuthConfig
  ): Promise<TokenResponse> {
    const response = await fetch(config.tokenEndpoint, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: new URLSearchParams({
        grant_type: "refresh_token",
        refresh_token: refreshToken,
        client_id: config.clientId,
      }),
    });
    
    if (!response.ok) {
      throw new Error("Token refresh failed");
    }
    
    return response.json();
  }
}

interface AuthConfig {
  clientId: string;
  redirectUri: string;
  authorizationEndpoint: string;
  tokenEndpoint: string;
  scopes: string[];
}

interface TokenResponse {
  access_token: string;
  refresh_token?: string;
  id_token?: string;
  token_type: string;
  expires_in: number;
  scope?: string;
}
```

## React Integration
```tsx
// hooks/useAuth.ts
import { createContext, useContext, useEffect, useState } from "react";
import { PKCEAuth } from "../auth/pkce";

interface AuthContextType {
  isAuthenticated: boolean;
  isLoading: boolean;
  user: User | null;
  login: () => Promise<void>;
  logout: () => void;
  getAccessToken: () => Promise<string | null>;
}

const AuthContext = createContext<AuthContextType | null>(null);

const authConfig: AuthConfig = {
  clientId: process.env.NEXT_PUBLIC_OAUTH_CLIENT_ID!,
  redirectUri: `${window.location.origin}/callback`,
  authorizationEndpoint: "https://auth.example.com/authorize",
  tokenEndpoint: "https://auth.example.com/oauth/token",
  scopes: ["openid", "profile", "email"],
};

export function AuthProvider({ children }: { children: React.ReactNode }) {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [user, setUser] = useState<User | null>(null);
  const [tokens, setTokens] = useState<TokenResponse | null>(null);
  
  const pkce = new PKCEAuth();
  
  useEffect(() => {
    // Check for existing session
    const storedTokens = localStorage.getItem("auth_tokens");
    if (storedTokens) {
      const parsed = JSON.parse(storedTokens);
      setTokens(parsed);
      setIsAuthenticated(true);
      fetchUserProfile(parsed.access_token);
    }
    setIsLoading(false);
  }, []);
  
  const login = async () => {
    const authUrl = await pkce.getAuthorizationUrl(authConfig);
    window.location.href = authUrl;
  };
  
  const handleCallback = async (code: string, state: string) => {
    // Verify state
    const storedState = sessionStorage.getItem("oauth_state");
    if (state !== storedState) {
      throw new Error("State mismatch - possible CSRF attack");
    }
    
    const tokens = await pkce.exchangeCodeForTokens(code, authConfig);
    
    // Store tokens securely
    localStorage.setItem("auth_tokens", JSON.stringify(tokens));
    setTokens(tokens);
    setIsAuthenticated(true);
    
    // Schedule token refresh
    scheduleTokenRefresh(tokens.expires_in);
    
    // Fetch user profile
    await fetchUserProfile(tokens.access_token);
  };
  
  const getAccessToken = async (): Promise<string | null> => {
    if (!tokens) return null;
    
    // Check if token is expired
    const tokenData = parseJwt(tokens.access_token);
    if (tokenData.exp * 1000 < Date.now()) {
      // Refresh token
      if (tokens.refresh_token) {
        const newTokens = await pkce.refreshAccessToken(
          tokens.refresh_token,
          authConfig
        );
        localStorage.setItem("auth_tokens", JSON.stringify(newTokens));
        setTokens(newTokens);
        return newTokens.access_token;
      }
      // Force re-login
      logout();
      return null;
    }
    
    return tokens.access_token;
  };
  
  const logout = () => {
    localStorage.removeItem("auth_tokens");
    setTokens(null);
    setUser(null);
    setIsAuthenticated(false);
  };
  
  return (
    <AuthContext.Provider value={{
      isAuthenticated,
      isLoading,
      user,
      login,
      logout,
      getAccessToken,
    }}>
      {children}
    </AuthContext.Provider>
  );
}

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) throw new Error("useAuth must be within AuthProvider");
  return context;
};
```

## Callback Handler
```tsx
// pages/callback.tsx
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useAuth } from "../hooks/useAuth";

export default function Callback() {
  const router = useRouter();
  const { handleCallback } = useAuth();
  
  useEffect(() => {
    const { code, state, error } = router.query;
    
    if (error) {
      console.error("OAuth error:", error);
      router.push("/login?error=" + error);
      return;
    }
    
    if (code && state) {
      handleCallback(code as string, state as string)
        .then(() => router.push("/dashboard"))
        .catch((err) => {
          console.error("Callback error:", err);
          router.push("/login?error=callback_failed");
        });
    }
  }, [router.query]);
  
  return <div>Processing login...</div>;
}
```

## Best Practices
- Always use PKCE for public clients (SPAs, mobile)
- Validate state parameter to prevent CSRF
- Store tokens securely (not in localStorage for sensitive apps)
- Implement token refresh before expiration
- Use short-lived access tokens with refresh tokens
- Implement proper logout (revoke tokens)

When to Use This Prompt

This OAuth prompt is ideal for developers working on:

  • OAuth applications requiring modern best practices and optimal performance
  • Projects that need production-ready OAuth code with proper error handling
  • Teams looking to standardize their oauth development workflow
  • Developers wanting to learn industry-standard OAuth patterns and techniques

By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their oauth implementations.

How to Use

  1. Copy the prompt - Click the copy button above to copy the entire prompt to your clipboard
  2. Paste into your AI assistant - Use with Claude, ChatGPT, Cursor, or any AI coding tool
  3. Customize as needed - Adjust the prompt based on your specific requirements
  4. Review the output - Always review generated code for security and correctness
💡 Pro Tip: For best results, provide context about your project structure and any specific constraints or preferences you have.

Best Practices

  • ✓ Always review generated code for security vulnerabilities before deploying
  • ✓ Test the OAuth code in a development environment first
  • ✓ Customize the prompt output to match your project's coding standards
  • ✓ Keep your AI assistant's context window in mind for complex requirements
  • ✓ Version control your prompts alongside your code for reproducibility

Frequently Asked Questions

Can I use this OAuth prompt commercially?

Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.

Which AI assistants work best with this prompt?

This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.

How do I customize this prompt for my specific needs?

You can modify the prompt by adding specific requirements, constraints, or preferences. For OAuth projects, consider mentioning your framework version, coding style, and any specific libraries you're using.

Related Prompts

💬 Comments

Loading comments...