Auth0 SDK for Vue

repository·main·Indexed 41 days ago

https://github.com/auth0/auth0-vue

Auth0 SDK for Vue 3 Single Page Applications (SPAs) using Authorization Code Grant Flow with PKCE. Version 2.10.0 provides integration for authentication and authorization via the Composition API (useAuth0 hook) and Options API (this.$auth0), including features like route protection with authGuard, user profile management, and silent access token retrieval.

Tokens
31.7K
Snippets
93
Records
124
Agent score
49%

What's inside Auth0 Vue

  1. Define Methods for Auth0Plugin via Prototype

    main
    New methods added to Auth0Plugin are automatically bound to this by the bindPluginMethods utility in the constructor. To ensure this binding works correctly, do not define methods as arrow function properties (which attaches them to the instance); instead, define them as standard class methods on the prototype.
  2. Browser support and polyfills in Auth0-Vue v2

    main

    Auth0-Vue v2 no longer supports Internet Explorer 11 (IE11) because the underlying Auth0-SPA-JS library has removed all IE11-specific polyfills to reduce bundle size by 60%.

    If your application must support older browsers (like IE11, Opera Mini, or specific mobile browsers) that require the following features, you must manually include them in your application:

    • AbortController
    • Promise
    • Core-js (for string/startsWith, string/includes, set, symbol, array/from, array/includes)
    • fast-text-encoding (for TextEncoder and TextDecoder)
    • unfetch (for fetch)
  3. Use the Proxy Pattern for State Refresh

    main

    When implementing methods that mutate authentication state, you must route the operation through the __proxy() method. This ensures that isAuthenticated, user, and idTokenClaims are updated correctly and that any errors are captured into the error ref. Bypassing __proxy() will result in stale reactive state and unhandled errors.

    // ✅ Good: state is refreshed and errors are captured
    async loginWithPopup(options?: PopupLoginOptions) {
      return this.__proxy(() => this._client.loginWithPopup(options));
    }
    
    // ❌ Bad: reactive state stays stale; error ref never updates
    async loginWithPopup(options?: PopupLoginOptions) {
      return this._client.loginWithPopup(options);
    }
  4. Use Reactive State for Auth0Plugin

    main

    All public state on Auth0Plugin must be defined as a Vue Ref<T> to ensure template reactivity. Using primitive types instead of Ref will prevent Vue components from automatically updating when authentication state changes.

    // ✅ Good: ensures components re-render when state changes
    public isAuthenticated: Ref<boolean> = ref(false);
    
    // ❌ Bad: components will not update when this value changes
    public isAuthenticated: boolean = false;
  5. Understand `__proxy()` and reactive state updates

    main

    The Auth0Plugin uses a __proxy() mechanism to ensure that any method mutating authentication state also refreshes reactive properties like isAuthenticated, user, and idTokenClaims, and captures errors into the error ref.

    If you are extending the plugin or implementing new auth methods, ensure they call __proxy() after state mutations. If you call this._client directly without __proxy(), the reactive state will remain stale and Vue components will not re-render.

    Exceptions: loginWithRedirect and logout (when not using openUrl) do not require __proxy() because they either navigate away or complete inline.

  6. Ensure Auth0 methods are correctly bound for Vue `provide/inject`

    main

    When using useAuth0() in child components via Vue's provide/inject pattern, methods can lose their this context. While the Auth0Plugin automatically binds its prototype methods, you must avoid defining new methods as arrow-function class fields (e.g., myMethod = () => ...).

    Arrow-function class fields are assigned to the instance rather than the prototype, which bypasss the automatic binding mechanism and will cause errors when the method is called from an injected reference.

  7. Log in to an organization

    main
    Use the organization features to allow users to log in specifically to an Auth0 Organization. (Note: The provided segment contains the heading but the implementation details for this specific task were not included in this segment of the file).
  8. Access Auth0 SDK information outside of a Vue component

    main

    The SDK is built using Vue's reactive API. When accessing SDK properties (like user) outside of a component's setup() or lifecycle hooks, you must unwrap the reactive values.

    Use Vue's toRaw function to get the underlying object, and access the value via .value if it is a Ref.

    const user = toRaw(auth0.user).value;
    console.log(user.name);
  9. Use Step-Up Authentication with Popups

    main

    Step-Up Authentication is a low-code way to handle MFA. Instead of building custom UI, you can configure the SDK to automatically open a Universal Login popup when MFA is required.

    To use this, set interactiveErrorHandler: 'popup' in your createAuth0 configuration. When getAccessTokenSilently() encounters an MFA requirement, it will trigger the popup. Once the user completes MFA in the popup, the token is returned to your code transparently.

    Possible Errors: If the popup fails, getAccessTokenSilently will throw:

    • PopupOpenError
    • PopupCancelledError
    • PopupTimeoutError
    app.use(
      createAuth0({
        domain: '<AUTH0_DOMAIN>',
        clientId: '<AUTH0_CLIENT_ID>',
        useRefreshTokens: true,
        interactiveErrorHandler: 'popup'
      })
    );
  10. Enroll new authentication methods using MyAccount

    main

    Enrollment follows a two-step pattern: enrollmentChallenge() to request the challenge, followed by enrollmentVerify() to complete the process.

    Passkey

    Requires handling WebAuthn credentials. You must convert base64url strings to ArrayBuffer and serialize the PublicKeyCredential into a plain object.

    Email

    Requires an email and the otpCode received by the user.

    Phone

    Requires a phone_number and the otpCode received via SMS or voice.

    TOTP (Authenticator App)

    Requires the otpCode generated by the user's app after scanning the provided barcode_uri.

    <script>
      import { useAuth0 } from '@auth0/auth0-vue';
    
      export default {
        setup() {
          const { myAccount } = useAuth0();
    
          // Example: Email Enrollment
          const enrollEmail = async (email, otpCode) => {
            const challenge = await myAccount.enrollmentChallenge({
              type: 'email',
              email
            });
            await myAccount.enrollmentVerify({
              type: 'email',
              location: challenge.location,
              auth_session: challenge.auth_session,
              otp_code: otpCode
            });
          };
    
          // Example: TOTP Enrollment
          const enrollTotp = async (otpCode) => {
            const challenge = await myAccount.enrollmentChallenge({ type: 'totp' });
            // challenge.barcode_uri can be rendered as a QR code
            await myAccount.enrollmentVerify({
              type: 'totp',
              location: challenge.location,
              auth_session: challenge.auth_session,
              otp_code: otpCode
            });
          };
    
          return { enrollEmail, enrollTotp };
        }
      };
    </script>
  11. Use `authorizationParams` for Auth0 parameters in v2

    main

    Auth0-Vue v2 separates SDK configuration properties from properties sent to Auth0. Properties intended for Auth0 (like redirect_uri or audience) must now be placed inside the authorizationParams object. This affects the following methods:

    • loginWithRedirect
    • loginWithPopup
    • getAccessTokenWithPopup
    • getAccessTokenSilently
    // v1
    app.use(
      createAuth0({
        domain: '<AUTH0_DOMAIN>',
        client_id: '<AUTH0_CLIENT_ID>',
        redirect_uri: '<MY_CALLBACK_URL>',
        audience: '<AUTH0_API_IDENTIFIER>'
      })
    );
    
    // v2
    app.use(
      createAuth0({
        domain: '<AUTH0_DOMAIN>',
        clientId: '<AUTH0_CLIENT_ID>',
        authorizationParams: {
          redirect_uri: '<MY_CALLBACK_URL>',
          audience: '<AUTH0_API_IDENTIFIER>'
        }
      })
    );
  12. Enable and Use Multi-Resource Refresh Tokens (MRRT)

    main

    Multi-Resource Refresh Tokens (MRRT) allow a single refresh token to be exchanged for access tokens for different API audiences without requiring a new user login.

    Setup:

    1. Ensure your Auth0 tenant is configured with MRRT policies.
    2. Set useRefreshTokens: true and useMrrt: true in the createAuth0 configuration.

    Usage: To get a token for a different audience, call getAccessTokenSilently with the new audience in authorizationParams. The SDK will use the existing refresh token to perform the exchange.

    // Configuration
    app.use(
      createAuth0({
        domain: '<AUTH0_DOMAIN>',
        clientId: '<AUTH0_CLIENT_ID>',
        useRefreshTokens: true,
        useMrrt: true,
        authorizationParams: {
          redirect_uri: '<MY_CALLBACK_URL>',
          audience: 'https://api.example.com' // primary audience
        }
      })
    );
    
    // Usage in a component
    const { getAccessTokenSilently } = useAuth0();
    const token = await getAccessTokenSilently({
      authorizationParams: { audience: 'https://api2.example.com' }
    });