Überauth Google

repository·master·Indexed 41 days ago

https://github.com/ueberauth/ueberauth_google

A Google OAuth2 strategy for the Überauth authentication framework in Elixir. It enables Google sign-in integration, providing tools to manage client credentials, configure scopes, and extract user information such as email, name, and profile images via the Ueberauth.Strategy.Google module.

Tokens
2.5K
Snippets
9
Records
11
Agent score
52%

What's inside Überauth Google

  1. Initiate Google authentication requests

    master

    You can initiate the authentication flow by navigating to the request path.

    Basic request: /auth/google (defaults to email scope).

    Request with specific scopes: /auth/google?scope=email%20profile

    Advanced configuration via provider options: You can configure default scopes and other parameters (like hd, prompt, access_type, and include_granted_scopes) in your application configuration.

    # Configure advanced options in your config file
    config :ueberauth, Ueberauth,
      providers: [
        google: {Ueberauth.Strategy.Google, [
          default_scope: "email profile plus.me",
          hd: "example.com",
          prompt: "select_account",
          access_type: "offline",
          include_granted_scopes: true
        ]}
      ]
  2. Install Überauth Google

    master

    To use Google OAuth2 with Überauth, follow these steps:

    1. Set up your application in the Google Developer Console.
    2. Add :ueberauth_google to your mix.exs dependencies.
    3. Register the Google provider in your ueberauth configuration.
    4. Configure your Google client credentials.
    5. Add the Ueberauth plug to your controller.
    6. Define the /auth/:provider and /auth/:provider/callback routes in your router.
    # 1. Add dependency
    def deps do
      [
        {:ueberauth_google, "~> 0.10"}
      ]
    end
    
    # 2. Configure provider
    config :ueberauth, Ueberauth,
      providers: [
        google: {Ueberauth.Strategy.Google, []}
      ]
    
    # 3. Configure credentials (Runtime approach recommended)
    config :ueberauth, Ueberauth.Strategy.Google.OAuth,
      client_id: {System, :get_env, ["GOOGLE_CLIENT_ID"]},
      client_secret: {System, :get_env, ["GOOGLE_CLIENT_SECRET"]}
    
    # 4. Add plug to controller
    defmodule MyApp.AuthController do
      use MyApp.Web, :controller
      plug Ueberauth
      ...
    end
    
    # 5. Define routes
    scope "/auth", MyApp do
      pipe_through :browser
      get "/:provider", AuthController, :request
      get "/:provider/callback", AuthController, :callback
    end
  3. Override the Google callback URL

    master

    By default, the callback URL is automatically generated from the current request. If you are running behind a reverse proxy, using a custom domain, or handling SSL termination, you may need to set the callback_url explicitly in the provider configuration.

    config :ueberauth, Ueberauth,
      providers: [
        google: {Ueberauth.Strategy.Google, [
          callback_url: "https://example.com/auth/google/callback"
        ]}
      ]
  4. Configure the Google userinfo endpoint

    master

    If you are deploying to a region where the default Google user info endpoint is blocked, you can override it.

    You can set this via static configuration or via runtime environment variables using a specific tuple format: {:system, "ENV_VAR_NAME", "DEFAULT_VALUE"}.

    # Static configuration
    config :ueberauth, Ueberauth,
      providers: [
        google: {Ueberauth.Strategy.Google, [userinfo_endpoint: "https://www.googleapis.cn/oauth2/v3/userinfo"]}
      ]
    
    # Runtime configuration with environment variable and default
    config :ueberauth, Ueberauth,
      providers: [
        google: {Ueberauth.Strategy.Google, [
          userinfo_endpoint: {:system, "GOOGLE_USERINFO_ENDPOINT", "https://www.googleapis.cn/oauth2/v3/userinfo"}
        ]}
      ]
  5. Configure Google OAuth2 credentials

    master

    You can provide client_id and client_secret to Ueberauth.Strategy.Google.OAuth using either compile-time or run-time environment variable lookups.

    Compile-time lookup: Use System.get_env/1. Note that these values are fixed when the application is compiled.

    Run-time lookup (Recommended): Use a tuple {System, :get_env, ["VAR_NAME"]}. This allows the application to read the environment variables when it starts up, which is more flexible for different environments.

    # Compile-time
    config :ueberauth, Ueberauth.Strategy.Google.OAuth,
      client_id: System.get_env("GOOGLE_CLIENT_ID"),
      client_secret: System.get_env("GOOGLE_CLIENT_SECRET")
    
    # Run-time
    config :ueberauth, Ueberauth.Strategy.Google.OAuth,
      client_id: {System, :get_env, ["GOOGLE_CLIENT_ID"]},
      client_secret: {System, :get_env, ["GOOGLE_CLIENT_SECRET"]}
  6. Configure Ueberauth Google credentials

    master

    To use the Google strategy, you must provide your client_id and client_secret in your application configuration. It is recommended to use environment variables for these sensitive values.

    Add the following to your configuration file (e.g., config/config.exs):

    config :ueberauth, Ueberauth.Strategy.Google.OAuth,
            client_id: System.get_env("GOOGLE_APP_ID"),
            client_secret: System.get_env("GOOGLE_APP_SECRET")
  7. Override the Google userinfo_endpoint

    master

    By default, the strategy uses https://www.googleapis.com/oauth2/v3/userinfo to fetch user details. If you need to use a different endpoint (for example, from a different OpenID configuration), you can override it using the :userinfo_endpoint option.

    You can provide the endpoint directly in the options or use a system environment variable by passing {:system, "ENV_VAR_NAME"}.

  8. Extract user information from Google authentication

    master

    Once a successful callback is processed, you can use the following methods on the conn to retrieve the authenticated user's data:

    • Ueberauth.Strategy.Google.uid(conn): Returns the unique identifier for the user (defaults to the :sub field from Google).
    • Ueberauth.Strategy.Google.info(conn): Returns a %Ueberauth.Auth.Info{} struct containing:
      • email: User's email address.
      • first_name: User's given name.
      • last_name: User's family name.
      • name: Full name.
      • image: URL to the user's profile picture.
      • birthday: User's birthday.
      • urls: A map containing profile and website (mapped from Google's hd field).
    • Ueberauth.Strategy.Google.credentials(conn): Returns a %Ueberauth.Auth.Credentials{} struct containing the access token, refresh token, expiration details, and scopes.
    • Ueberauth.Strategy.Google.extra(conn): Returns a %Ueberauth.Auth.Extra{} struct containing the raw_info, which includes both the full token and the raw user response from Google.
  9. Use Ueberauth.Strategy.Google.OAuth.client/1

    master

    The client/1 function constructs an OAuth2.Client specifically configured for Google's endpoints (https://accounts.google.com and https://www.googleapis.com/oauth2/v4/token).

    While this is automatically set up for use within the standard Ueberauth callback phase, you can call it manually if you need to perform requests outside the normal flow. It merges application configuration with any provided opts.

    # Example of manual client construction
    client = Ueberauth.Strategy.Google.OAuth.client([:some_option, "value"])
  10. Perform authenticated GET requests with get/4

    master

    The get/4 function allows you to make authenticated GET requests to Google APIs using the strategy's client. It automatically includes the client_secret as a parameter in the request.

    # token: the access token
    # url: the Google API endpoint
    # headers: list of HTTP headers
    # opts: additional OAuth2 client options
    Ueberauth.Strategy.Google.OAuth.get(token, "https://www.googleapis.com/oauth2/v3/userinfo", [], [])
  11. Get an access token with get_access_token/2

    master

    The get_access_token/2 function exchanges authorization parameters for an access token. It handles various error responses from Google, including error descriptions and OAuth2-specific error reasons.

    Returns:

    • {:ok, token}: On success.
    • {:error, {error, description}}: On failure, where error is the error type and description is the human-readable reason.
    case Ueberauth.Strategy.Google.OAuth.get_access_token(params) do
      {:ok, token} -> 
        # Handle success
      {:error, {error, description}} -> 
        # Handle error
    end