Bird
Raised Fist0
Astroframework~20 mins

OAuth integration in Astro - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
OAuth Integration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
OAuth Redirect Behavior in Astro
In an Astro component handling OAuth login, what happens immediately after the user clicks the login button that triggers the OAuth redirect?
Astro
export default function Login() {
  function handleLogin() {
    window.location.href = 'https://oauth.provider.com/auth?client_id=abc&redirect_uri=https://myapp.com/callback';
  }
  return <button onClick={handleLogin}>Login with OAuth</button>;
}
AThe app opens a new tab with the OAuth provider but keeps the current page active.
BThe browser navigates to the OAuth provider's login page, pausing the current app until redirect back.
CThe app sends an API request to the OAuth provider without changing the page.
DThe app immediately shows a success message without redirecting.
Attempts:
2 left
💡 Hint
Think about what happens when you set window.location.href in the browser.
📝 Syntax
intermediate
2:00remaining
Correct OAuth Callback Handler Syntax in Astro
Which Astro code snippet correctly extracts the OAuth authorization code from the URL query parameters in a server-side callback route?
A
export async function get({ url }) {
  const code = url.params.code;
  return new Response(`Code: ${code}`);
}
B
export async function get({ request }) {
  const code = request.query.code;
  return new Response(`Code: ${code}`);
}
C
export async function get({ params }) {
  const code = params.code;
  return new Response(`Code: ${code}`);
}
D
export async function get({ url }) {
  const code = url.searchParams.get('code');
  return new Response(`Code: ${code}`);
}
Attempts:
2 left
💡 Hint
Check how URLSearchParams works in JavaScript for query strings.
🔧 Debug
advanced
2:30remaining
Fixing OAuth Token Exchange Error
An Astro server route tries to exchange the OAuth code for a token but always gets a 400 Bad Request error. Which code snippet correctly sends the POST request with JSON body and headers?
Astro
async function exchangeToken(code) {
  const response = await fetch('https://oauth.provider.com/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ code, client_id: 'abc', client_secret: 'xyz' })
  });
  return response.json();
}
ARemove headers and send body as JSON string.
BKeep 'application/json' header but send body as plain object without JSON.stringify.
CUse 'application/x-www-form-urlencoded' header and encode body as URL params string.
DChange method to 'GET' and send code in URL query.
Attempts:
2 left
💡 Hint
OAuth token endpoints usually expect URL encoded form data, not JSON.
❓ state_output
advanced
2:00remaining
OAuth State Parameter Usage in Astro
Why is the 'state' parameter important in OAuth flows implemented in Astro, and what happens if it is missing or mismatched after redirect?
AIt prevents CSRF attacks; if missing or mismatched, the app should reject the OAuth response.
BIt stores the user's login name; if missing, the app logs in anonymously.
CIt contains the OAuth token; if mismatched, the token is refreshed automatically.
DIt is optional and has no effect on security or flow.
Attempts:
2 left
💡 Hint
Think about how apps protect against fake OAuth responses.
🧠 Conceptual
expert
3:00remaining
OAuth Token Storage Best Practice in Astro
After successfully obtaining an OAuth access token in an Astro app, what is the safest way to store it for use in authenticated API calls?
AStore the token in an HttpOnly, Secure cookie to prevent JavaScript access and protect against XSS.
BStore the token in localStorage for easy access from any client-side script.
CEmbed the token directly in the HTML as a JavaScript variable.
DStore the token in a global JavaScript variable accessible in all components.
Attempts:
2 left
💡 Hint
Consider security risks like cross-site scripting (XSS) when choosing storage.

Practice

(1/5)
1. What is the main purpose of OAuth integration in an Astro app?
easy
A. Store user passwords securely in the app database
B. Automatically update the app without user permission
C. Allow users to log in without sharing their password directly
D. Encrypt all user data on the client side

Solution

  1. Step 1: Understand OAuth's role

    OAuth allows users to authenticate using a third-party service without sharing their password with your app.
  2. Step 2: Identify the correct purpose

    Among the options, only allowing login without sharing passwords matches OAuth's main goal.
  3. Final Answer:

    Allow users to log in without sharing their password directly -> Option C
  4. Quick Check:

    OAuth = secure login without password sharing [OK]
Hint: OAuth means login without giving your password away [OK]
Common Mistakes:
  • Thinking OAuth stores passwords in your app
  • Confusing OAuth with data encryption
  • Assuming OAuth updates the app automatically
2. Which of the following is the correct way to import OAuth2Client in an Astro component?
easy
A. import OAuth2Client from '@astrojs/oauth2client';
B. import OAuth2Client from 'astro/oauth2';
C. const OAuth2Client = require('@astrojs/oauth');
D. import { OAuth2Client } from '@astrojs/oauth';

Solution

  1. Step 1: Recall Astro OAuth import syntax

    Astro uses named imports from '@astrojs/oauth' for OAuth2Client.
  2. Step 2: Check each option

    Only import { OAuth2Client } from '@astrojs/oauth'; uses correct named import syntax and package name.
  3. Final Answer:

    import { OAuth2Client } from '@astrojs/oauth'; -> Option D
  4. Quick Check:

    Correct import = import { OAuth2Client } from '@astrojs/oauth'; [OK]
Hint: Use named import from '@astrojs/oauth' for OAuth2Client [OK]
Common Mistakes:
  • Using require() instead of import
  • Wrong package name or path
  • Default import instead of named import
3. Given this Astro code snippet, what will be the output if the user successfully logs in?
const client = new OAuth2Client({
  clientId: 'abc123',
  clientSecret: 'secret',
  redirectUri: 'https://myapp.com/callback'
});

const token = await client.getToken('auth_code_here');
console.log(token.access_token);
medium
A. Undefined because token is not returned
B. An access token string printed to the console
C. An error because getToken is not async
D. The client secret printed instead of token

Solution

  1. Step 1: Understand getToken usage

    getToken is an async method that returns a token object with access_token on success.
  2. Step 2: Analyze console.log output

    Logging token.access_token prints the access token string if login succeeds.
  3. Final Answer:

    An access token string printed to the console -> Option B
  4. Quick Check:

    Successful getToken = access token output [OK]
Hint: getToken returns token object with access_token property [OK]
Common Mistakes:
  • Assuming getToken is synchronous
  • Expecting token to be undefined
  • Confusing clientSecret with access token
4. Identify the error in this OAuth integration snippet:
const client = new OAuth2Client({
  clientId: 'abc123',
  redirectUri: 'https://myapp.com/callback'
});

const token = await client.getToken('auth_code_here');
medium
A. Missing clientSecret in OAuth2Client configuration
B. redirectUri should be a relative path, not full URL
C. getToken should not be awaited
D. clientId should be a number, not string

Solution

  1. Step 1: Check required OAuth2Client config

    OAuth2Client requires clientId, clientSecret, and redirectUri to work properly.
  2. Step 2: Identify missing property

    The snippet lacks clientSecret, which is mandatory for token exchange.
  3. Final Answer:

    Missing clientSecret in OAuth2Client configuration -> Option A
  4. Quick Check:

    clientSecret missing = error [OK]
Hint: Always include clientSecret with clientId and redirectUri [OK]
Common Mistakes:
  • Omitting clientSecret
  • Misusing redirectUri format
  • Not awaiting async getToken
5. You want to implement OAuth login in Astro that supports multiple providers (Google, GitHub). Which approach best handles this using OAuth2Client?
hard
A. Create separate OAuth2Client instances for each provider with their own configs
B. Use one OAuth2Client instance with combined clientId and clientSecret
C. Manually build OAuth URLs without OAuth2Client for flexibility
D. Store all provider secrets in a single environment variable

Solution

  1. Step 1: Understand provider-specific configs

    Each OAuth provider requires its own clientId, clientSecret, and redirectUri.
  2. Step 2: Choose best practice for multiple providers

    Creating separate OAuth2Client instances per provider keeps configs clean and manageable.
  3. Final Answer:

    Create separate OAuth2Client instances for each provider with their own configs -> Option A
  4. Quick Check:

    Separate clients per provider = best practice [OK]
Hint: Use one OAuth2Client per provider for clean config [OK]
Common Mistakes:
  • Combining credentials into one client
  • Avoiding OAuth2Client for no reason
  • Mixing secrets in one variable
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard