Skip to content

Social Login

Security

Social Login

Introduction

Letting users sign in with an existing Google, GitHub, or Microsoft account removes the friction of creating yet another password. You may also add other providers, such as GitLab, Discord, or your company's own OAuth server. The laravel::auth::social module handles the OAuth redirect, state verification, and profile lookup, returning the user's provider ID, name, and email address so your application can store whatever it needs and sign the user in with Auth.

Because social login stores OAuth state in the session, register its routes in the web middleware group.

Configuration

Before your users can log in with a provider, create an OAuth application in that provider's developer console. The console gives you a client ID and a client secret, which you add to your .env file. Add only the providers your application offers:

1GOOGLE_CLIENT_ID=
2GOOGLE_CLIENT_SECRET=
3 
4GITHUB_CLIENT_ID=
5GITHUB_CLIENT_SECRET=
6 
7MICROSOFT_CLIENT_ID=
8MICROSOFT_CLIENT_SECRET=
1GOOGLE_CLIENT_ID=
2GOOGLE_CLIENT_SECRET=
3 
4GITHUB_CLIENT_ID=
5GITHUB_CLIENT_SECRET=
6 
7MICROSOFT_CLIENT_ID=
8MICROSOFT_CLIENT_SECRET=

When you create the application, the console also asks for a callback URL. That's where the provider sends the user after they approve your application. Laravel expects /auth/{provider}/callback on your application's URL, such as https://example.com/auth/google/callback. For local development, register http://localhost:8000/auth/google/callback too.

To use another callback URL, set GOOGLE_REDIRECT_URI, GITHUB_REDIRECT_URI, or MICROSOFT_REDIRECT_URI to the URL you registered with the provider, and give your callback route the same path. A path on its own is relative to your application's URL:

1GOOGLE_REDIRECT_URI=/login/google/callback
1GOOGLE_REDIRECT_URI=/login/google/callback

Google

In the Google Cloud console, create an OAuth client ID of type Web application, and add your callback URL under Authorized redirect URIs.

GitHub

In your GitHub settings, open Developer settings, then OAuth Apps, and create a new application. Its Authorization callback URL is your callback URL.

If your company runs GitHub Enterprise Server, create the OAuth app on that server instead and set GITHUB_URL to your server's address. Laravel will send users there to log in and read their profile from its /api/v3 API:

1GITHUB_URL=https://github.example.com
1GITHUB_URL=https://github.example.com

Microsoft

In the Microsoft Entra admin center, open App registrations and register a new application. Add your callback URL as a Web redirect URI, then create a client secret under Certificates & secrets.

The Supported account types you pick must match MICROSOFT_TENANT:

MICROSOFT_TENANT Who can log in
common Anyone with a work, school, or personal Microsoft account. The default
organizations Anyone with a work or school account
consumers Anyone with a personal Microsoft account
A tenant ID Only people in that one organization

Under Token configuration, add the xms_edov optional claim to the ID token. This claim confirms that a work or school account's email address is verified by Microsoft; without it, Laravel treats those addresses as unverified and will not link the accounts to existing users. Personal Microsoft accounts do not need this claim.

Preparing your users table

Your users table needs provider and provider_id columns to store each user's linked social account, and a nullable password column for users who sign up without a password. This migration updates the default users table:

1// database/migrations/2026_11_06_120000_add_social_login_to_users_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .alter("users", |table| {
7 table.string("password").nullable().change();
8 table.string("provider").nullable();
9 table.string("provider_id").nullable();
10 
11 table.unique(["provider", "provider_id"]);
12 })
13 .await
14}
1// database/migrations/2026_11_06_120000_add_social_login_to_users_table.rs
2use laravel::db::AnyTransaction;
3 
4pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
5 tx.schema()
6 .alter("users", |table| {
7 table.string("password").nullable().change();
8 table.string("provider").nullable();
9 table.string("provider_id").nullable();
10 
11 table.unique(["provider", "provider_id"]);
12 })
13 .await
14}

Then add the fields to your User model, and make its password an Option. A Provider field stores the provider's name, such as google or github:

1// src/models/user.rs
2use laravel::auth::social::Provider;
3use laravel::auth::{Authenticatable, RememberToken};
4use laravel::hash::PasswordHash;
5use laravel::model::model;
6use laravel::time::Timestamp;
7 
8#[model]
9#[derive(Authenticatable)]
10pub struct User {
11 pub id: i64,
12 pub name: String,
13 pub email: String,
14 pub email_verified_at: Option<Timestamp>,
15 #[serde(skip)]
16 pub password: Option<PasswordHash>,
17 #[serde(skip)]
18 pub remember_token: Option<RememberToken>,
19 pub provider: Option<Provider>,
20 pub provider_id: Option<String>,
21 pub created_at: Timestamp,
22 pub updated_at: Timestamp,
23}
1// src/models/user.rs
2use laravel::auth::social::Provider;
3use laravel::auth::{Authenticatable, RememberToken};
4use laravel::hash::PasswordHash;
5use laravel::model::model;
6use laravel::time::Timestamp;
7 
8#[model]
9#[derive(Authenticatable)]
10pub struct User {
11 pub id: i64,
12 pub name: String,
13 pub email: String,
14 pub email_verified_at: Option<Timestamp>,
15 #[serde(skip)]
16 pub password: Option<PasswordHash>,
17 #[serde(skip)]
18 pub remember_token: Option<RememberToken>,
19 pub provider: Option<Provider>,
20 pub provider_id: Option<String>,
21 pub created_at: Timestamp,
22 pub updated_at: Timestamp,
23}

Your login form keeps working for users who have a password. A user who signed up through a provider can't log in through the form until they set a password with a password reset.

Authentication

Routing

To log users in with a provider, you need two routes: one that sends the user to the provider, and one that receives them when they come back. A {provider} parameter lets one pair of routes serve every provider. Add them to src/routes/web.rs in a RedirectIfAuthenticated group, with your other guest-only pages:

1use laravel::auth::RedirectIfAuthenticated;
2use laravel::prelude::*;
3 
4use crate::http::handlers::social;
5 
6pub fn routes(route: &mut Router) {
7 route.middleware(RedirectIfAuthenticated).group(|route| {
8 route.get("/auth/{provider}/redirect", social::redirect);
9 route.get("/auth/{provider}/callback", social::callback);
10 });
11}
1use laravel::auth::RedirectIfAuthenticated;
2use laravel::prelude::*;
3 
4use crate::http::handlers::social;
5 
6pub fn routes(route: &mut Router) {
7 route.middleware(RedirectIfAuthenticated).group(|route| {
8 route.get("/auth/{provider}/redirect", social::redirect);
9 route.get("/auth/{provider}/callback", social::callback);
10 });
11}

The redirect handler passes the provider to social::redirect, which sends the user to the provider's login page:

1// src/http/handlers/social.rs
2use laravel::auth::social::{self, Provider};
3use laravel::prelude::*;
4 
5pub async fn redirect(Params(provider): Params<Provider>) -> laravel::Result<Redirect> {
6 social::redirect(provider)
7}
1// src/http/handlers/social.rs
2use laravel::auth::social::{self, Provider};
3use laravel::prelude::*;
4 
5pub async fn redirect(Params(provider): Params<Provider>) -> laravel::Result<Redirect> {
6 social::redirect(provider)
7}

social::redirect accepts google, github, microsoft, and the names of the providers you add. Any other name in the URL returns a 404. A provider whose client ID and secret are not configured also returns 404 and logs a warning naming the missing environment variables.

Link to the redirect route from your login page. Inertia's <Link> works as well as a plain <a> tag. For a <Link> visit, social::redirect tells Inertia to leave your application with a full page load, since a background request can't follow the redirect to the provider:

1import { Link } from "@inertiajs/react";
2 
3<Link href="/auth/google/redirect">Continue with Google</Link>
4<Link href="/auth/microsoft/redirect">Continue with Microsoft</Link>
1import { Link } from "@inertiajs/react";
2 
3<Link href="/auth/google/redirect">Continue with Google</Link>
4<Link href="/auth/microsoft/redirect">Continue with Microsoft</Link>

Logging the user in

When the user approves your application, the provider redirects them back to your callback route. social::user verifies that the callback state matches the current session's login attempt and fetches the user's profile from the provider. This callback handler creates the account on first login and signs the user in:

1use laravel::auth::Auth;
2use laravel::auth::social::{self, Provider};
3use laravel::model::{create, update};
4use laravel::prelude::*;
5 
6use crate::http::handlers::{dashboard, login};
7use crate::models::User;
8 
9pub async fn callback(
10 Params(provider): Params<Provider>,
11 auth: Auth<User>,
12) -> laravel::Result<Redirect> {
13 let profile = social::user(provider).await?;
14 
15 let Some(user) = find_or_create_user(&profile).await? else {
16 return Ok(
17 redirect!(login::show)
18 .with("status", "We couldn't confirm your email address."),
19 );
20 };
21 
22 auth.login(&user).remember(true).await?;
23 
24 Ok(Redirect::intended(dashboard::show, ()))
25}
26 
27async fn find_or_create_user(profile: &social::User) -> laravel::Result<Option<User>> {
28 let linked = User::first_where(
29 User::provider.eq(&profile.provider) & User::provider_id.eq(&profile.id),
30 )
31 .await?;
32 
33 if linked.is_some() {
34 return Ok(linked);
35 }
36 
37 let Some(email) = profile.verified_email() else {
38 return Ok(None);
39 };
40 
41 if let Some(mut user) = User::first_where(User::email.eq(email)).await? {
42 if user.email_verified_at.is_none() {
43 update!(user { password: None, email_verified_at: laravel::now() }).await?;
44 }
45 
46 if user.provider.is_none() {
47 update!(user { provider: &profile.provider, provider_id: &profile.id }).await?;
48 }
49 
50 return Ok(Some(user));
51 }
52 
53 let user = create!(User {
54 name: profile.name.as_deref().unwrap_or(email),
55 email,
56 email_verified_at: laravel::now(),
57 provider: &profile.provider,
58 provider_id: &profile.id,
59 })
60 .await?;
61 
62 Ok(Some(user))
63}
1use laravel::auth::Auth;
2use laravel::auth::social::{self, Provider};
3use laravel::model::{create, update};
4use laravel::prelude::*;
5 
6use crate::http::handlers::{dashboard, login};
7use crate::models::User;
8 
9pub async fn callback(
10 Params(provider): Params<Provider>,
11 auth: Auth<User>,
12) -> laravel::Result<Redirect> {
13 let profile = social::user(provider).await?;
14 
15 let Some(user) = find_or_create_user(&profile).await? else {
16 return Ok(
17 redirect!(login::show)
18 .with("status", "We couldn't confirm your email address."),
19 );
20 };
21 
22 auth.login(&user).remember(true).await?;
23 
24 Ok(Redirect::intended(dashboard::show, ()))
25}
26 
27async fn find_or_create_user(profile: &social::User) -> laravel::Result<Option<User>> {
28 let linked = User::first_where(
29 User::provider.eq(&profile.provider) & User::provider_id.eq(&profile.id),
30 )
31 .await?;
32 
33 if linked.is_some() {
34 return Ok(linked);
35 }
36 
37 let Some(email) = profile.verified_email() else {
38 return Ok(None);
39 };
40 
41 if let Some(mut user) = User::first_where(User::email.eq(email)).await? {
42 if user.email_verified_at.is_none() {
43 update!(user { password: None, email_verified_at: laravel::now() }).await?;
44 }
45 
46 if user.provider.is_none() {
47 update!(user { provider: &profile.provider, provider_id: &profile.id }).await?;
48 }
49 
50 return Ok(Some(user));
51 }
52 
53 let user = create!(User {
54 name: profile.name.as_deref().unwrap_or(email),
55 email,
56 email_verified_at: laravel::now(),
57 provider: &profile.provider,
58 provider_id: &profile.id,
59 })
60 .await?;
61 
62 Ok(Some(user))
63}

The handler finds a returning user by their ID at the provider, which stays the same when they change their email address there. Always look users up by profile.provider and profile.id first, and never by email alone.

The provider confirmed the new user's email address, so the handler marks it verified, and the user doesn't get a verification email. When the provider sends no verified address, the handler sends the user back to the login page with a message instead.

Linking existing accounts

Someone who signed up with a password may later click Continue with Google. The handler above finds their account by email address, links it to their Google account, and logs them in.

Before linking an account whose email address was never verified, the handler clears the account's password. Without that step, an attacker could register with someone else's email and a chosen password, wait for the real owner to sign in with Google, and then sign in using that password. Clearing the password also invalidates all existing sessions and remember cookies. Because the provider has verified ownership of the email address, the handler marks it verified; if the user later wants a password, they can set one via password reset.

Only link accounts by an email address that verified_email returns. It returns the address only when the provider confirmed that the user controls it. An unverified address could be anyone's. For example, the administrator of any Microsoft organization can give one of their accounts your user's email address. Linking by that address would let them log in as your user.

When you need the email for display or contact purposes rather than account linking, read profile.email. It provides the address even when unverified, and verified indicates whether the provider confirmed ownership.

When the user cancels

When a user declines on the provider's consent screen, social::user returns social::Error::Denied, which responds with 403 if propagated with ?. To redirect the user back to the login page instead, match on the result in your callback handler:

1let profile = match social::user(provider).await {
2 Ok(profile) => profile,
3 Err(social::Error::Denied) => return Ok(redirect!(login::show)),
4 Err(error) => return Err(error.into()),
5};
1let profile = match social::user(provider).await {
2 Ok(profile) => profile,
3 Err(social::Error::Denied) => return Ok(redirect!(login::show)),
4 Err(error) => return Err(error.into()),
5};

Propagate the remaining errors with ?. Error::InvalidState returns a 403 when the callback state does not match a login started in this session, such as reopening an old callback URL. Error::Provider returns a 502 when the provider returns an error or an untrusted response, and Laravel logs the details automatically.

Access scopes and optional parameters

Each provider asks for the user's profile and email address by default. To ask for more, such as access to the user's GitHub repositories, start with social::provider and add scopes before redirecting. The scopes add to the defaults:

1use laravel::auth::social::{self, Provider};
2use laravel::prelude::*;
3 
4pub async fn connect_github() -> laravel::Result<Redirect> {
5 social::provider(Provider::GITHUB).scopes(["repo"]).redirect()
6}
1use laravel::auth::social::{self, Provider};
2use laravel::prelude::*;
3 
4pub async fn connect_github() -> laravel::Result<Redirect> {
5 social::provider(Provider::GITHUB).scopes(["repo"]).redirect()
6}

Some providers accept other parameters on the redirect. For example, prompt=select_account makes Google and Microsoft show their account chooser, even when the user is logged in to only one account:

1social::provider(Provider::GOOGLE).with([("prompt", "select_account")]).redirect()
1social::provider(Provider::GOOGLE).with([("prompt", "select_account")]).redirect()

Social login sets state, scope, redirect_uri, and a few other parameters itself, and with panics if you pass one of them. Use scopes to ask for scopes.

Retrieving user details

social::user returns a social::User containing the profile fields returned by the provider:

Field Type Description
provider Provider The provider the user signed in with
id String The user's stable provider ID
name Option<String> The user's full name
nickname Option<String> The user's username, such as their GitHub username (None for Google and Microsoft)
email Option<Email> The email address (email.address) and whether the provider verified it (email.verified)
avatar Option<String> The user's avatar URL (None for Microsoft)
token Token The OAuth access token for calling the provider's API on the user's behalf
raw serde_json::Value Raw claims or profile payload returned by the provider

Token holds the OAuth credentials: access (String), refresh (Option<String>), expires_at (Option<Timestamp>), and scopes (Vec<String>). If you need to call the provider's API later, store the Token in an encrypted column:

1// src/models/user.rs
2use laravel::auth::social::Token;
3use laravel::crypt::Encrypted;
4use laravel::model::model;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 #[serde(skip)]
11 pub github_token: Option<Encrypted<Token>>,
12}
1// src/models/user.rs
2use laravel::auth::social::Token;
3use laravel::crypt::Encrypted;
4use laravel::model::model;
5 
6#[model]
7pub struct User {
8 pub id: i64,
9 // ...
10 #[serde(skip)]
11 pub github_token: Option<Encrypted<Token>>,
12}

Save profile.token during your callback, then read token.access whenever you need to call the provider's API:

1use laravel::http::client;
2use laravel::model::update;
3 
4// Store the encrypted token in your callback...
5update!(user { github_token: profile.token }).await?;
6 
7// Later, read the decrypted token to call the provider's API...
8if let Some(token) = &user.github_token {
9 let repos = client::get("https://api.github.com/user/repos")
10 .token(&token.access)
11 .await?;
12}
1use laravel::http::client;
2use laravel::model::update;
3 
4// Store the encrypted token in your callback...
5update!(user { github_token: profile.token }).await?;
6 
7// Later, read the decrypted token to call the provider's API...
8if let Some(token) = &user.github_token {
9 let repos = client::get("https://api.github.com/user/repos")
10 .token(&token.access)
11 .await?;
12}

For anything else the provider sends, read raw in your callback. For Google and Microsoft, raw holds the claims of the user's ID token. For GitHub, it holds the response of GitHub's /user API, which includes the user's company:

1let company = profile.raw["company"].as_str();
1let company = profile.raw["company"].as_str();

Restricting logins to your organization

To let only your own organization's Microsoft accounts log in, set MICROSOFT_TENANT to your tenant ID. Microsoft then refuses everyone else.

Google needs a check in your callback handler, right after social::user returns the profile. Google Workspace accounts carry their domain in the hd claim, which personal accounts don't have:

1laravel::abort_if(profile.provider == Provider::GOOGLE && profile.raw["hd"] != "example.com", 403)?;
1laravel::abort_if(profile.provider == Provider::GOOGLE && profile.raw["hd"] != "example.com", 403)?;

You may also pass ("hd", "example.com") to with, so Google's account chooser offers only your organization's accounts. Keep the check anyway, since anyone can remove the parameter from the URL.

Adding providers

If your users sign in through a service Laravel doesn't include out of the box, such as GitLab, Okta, or Keycloak, you may register your own OAuth 2.0 provider under any name you choose. Once registered, social::redirect, social::user, and social::fake accept that name alongside google, so the routes, callback handler, and tests on this page work without changes. Register /auth/gitlab/callback as the provider's callback URL, as you would for Google.

Laravel handles OAuth state, PKCE, session verification, and token exchange for custom providers automatically.

To add a provider, implement the social::Driver trait. Your driver supplies the provider's authorization URL, token URL, and default scopes, and its user method loads the user's profile from the issued tokens. For example, this GitLab driver reads its server's address from a field so it works with both gitlab.com and a self-hosted GitLab instance:

1// src/social.rs
2use laravel::auth::social::{self, Driver, Profile, Tokens};
3 
4pub struct GitLab {
5 pub url: String,
6}
7 
8impl Driver for GitLab {
9 fn authorize_url(&self) -> String {
10 format!("{}/oauth/authorize", self.url)
11 }
12 
13 fn token_url(&self) -> String {
14 format!("{}/oauth/token", self.url)
15 }
16 
17 fn scopes(&self) -> &[&str] {
18 &["openid", "profile", "email"]
19 }
20 
21 async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
22 tokens.user_info(format!("{}/oauth/userinfo", self.url)).await
23 }
24}
1// src/social.rs
2use laravel::auth::social::{self, Driver, Profile, Tokens};
3 
4pub struct GitLab {
5 pub url: String,
6}
7 
8impl Driver for GitLab {
9 fn authorize_url(&self) -> String {
10 format!("{}/oauth/authorize", self.url)
11 }
12 
13 fn token_url(&self) -> String {
14 format!("{}/oauth/token", self.url)
15 }
16 
17 fn scopes(&self) -> &[&str] {
18 &["openid", "profile", "email"]
19 }
20 
21 async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
22 tokens.user_info(format!("{}/oauth/userinfo", self.url)).await
23 }
24}

tokens.user_info fetches the profile from an OpenID Connect user info endpoint, which GitLab, Okta, Keycloak, and Auth0 all provide. It maps sub to id, preferred_username to nickname, picture to avatar, and name, email, and email_verified to the fields of the same name, while keeping every claim in raw so you may read extras such as GitLab's groups. Include the openid scope in scopes so the provider returns these standard claims.

Give the server's address a configuration section of its own, next to your other services, so each environment may set it in .env:

1// src/config/services.rs
2use laravel::config::Section;
3 
4#[derive(Debug, Clone, Section)]
5pub struct GitLabConfig {
6 #[env("GITLAB_URL", default = "https://gitlab.com")]
7 pub url: String,
8}
1// src/config/services.rs
2use laravel::config::Section;
3 
4#[derive(Debug, Clone, Section)]
5pub struct GitLabConfig {
6 #[env("GITLAB_URL", default = "https://gitlab.com")]
7 pub url: String,
8}

Then register the driver under its name in src/app.rs. The closure you pass to social().extend receives your application's configuration, so it may read the section:

1// src/app.rs
2use crate::config::services::GitLabConfig;
3use crate::social::GitLab;
4 
5pub fn configure() -> ApplicationBuilder {
6 Application::configure()
7 .with_services(|app| {
8 app.social().extend("gitlab", |config| GitLab {
9 url: config.section::<GitLabConfig>().url.clone(),
10 });
11 })
12 // ...
13}
1// src/app.rs
2use crate::config::services::GitLabConfig;
3use crate::social::GitLab;
4 
5pub fn configure() -> ApplicationBuilder {
6 Application::configure()
7 .with_services(|app| {
8 app.social().extend("gitlab", |config| GitLab {
9 url: config.section::<GitLabConfig>().url.clone(),
10 });
11 })
12 // ...
13}

Laravel reads the provider's client ID and secret from environment variables named after the provider (replacing - with _, so gitlab-work reads GITLAB_WORK_CLIENT_ID):

1GITLAB_URL=https://gitlab.example.com
2GITLAB_CLIENT_ID=
3GITLAB_CLIENT_SECRET=
1GITLAB_URL=https://gitlab.example.com
2GITLAB_CLIENT_ID=
3GITLAB_CLIENT_SECRET=

Until both credentials are set, the provider's routes return 404 and log a warning naming the missing variables. To request additional scopes for a single login, pass them to scopes.

Registering a provider under google, github, or microsoft replaces Laravel's built-in driver. If you are shipping a provider in a package, call app.social().extend(..) from your service provider's register method instead. Application registrations run after packages, so an application may always override a package's provider by registering its own under the same name.

verified_email trusts the provider's email_verified claim. On a provider that someone else administers, such as a customer's Okta organization, that administrator decides which addresses count as verified. Link existing accounts by email address only through providers whose administrators you trust.

Reading profiles from the provider's API

Some providers return their own JSON format instead of OpenID Connect's standard claims. For example, Discord stores the handle in username and reports email verification in verified. For a provider like Discord, fetch the user's profile with the HTTP client inside user and map the fields onto a social::Profile:

1// src/social.rs
2use laravel::auth::social::{self, Driver, Email, Profile, Tokens};
3use laravel::http::client;
4use serde_json::Value;
5 
6pub struct Discord;
7 
8impl Driver for Discord {
9 fn authorize_url(&self) -> String {
10 "https://discord.com/oauth2/authorize".to_owned()
11 }
12 
13 fn token_url(&self) -> String {
14 "https://discord.com/api/oauth2/token".to_owned()
15 }
16 
17 fn scopes(&self) -> &[&str] {
18 &["identify", "email"]
19 }
20 
21 async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
22 let user: Value = client::get("https://discord.com/api/users/@me")
23 .token(tokens.access_token())
24 .ensure_successful()
25 .await
26 .and_then(|response| response.json())
27 .map_err(|error| social::Error::Provider(error.to_string()))?;
28 
29 Ok(Profile {
30 id: user["id"].as_str().unwrap_or_default().to_owned(),
31 name: user["global_name"].as_str().map(str::to_owned),
32 nickname: user["username"].as_str().map(str::to_owned),
33 email: user["email"].as_str().map(|address| Email {
34 address: address.to_owned(),
35 verified: user["verified"] == true,
36 }),
37 avatar: None,
38 raw: user,
39 })
40 }
41}
1// src/social.rs
2use laravel::auth::social::{self, Driver, Email, Profile, Tokens};
3use laravel::http::client;
4use serde_json::Value;
5 
6pub struct Discord;
7 
8impl Driver for Discord {
9 fn authorize_url(&self) -> String {
10 "https://discord.com/oauth2/authorize".to_owned()
11 }
12 
13 fn token_url(&self) -> String {
14 "https://discord.com/api/oauth2/token".to_owned()
15 }
16 
17 fn scopes(&self) -> &[&str] {
18 &["identify", "email"]
19 }
20 
21 async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
22 let user: Value = client::get("https://discord.com/api/users/@me")
23 .token(tokens.access_token())
24 .ensure_successful()
25 .await
26 .and_then(|response| response.json())
27 .map_err(|error| social::Error::Provider(error.to_string()))?;
28 
29 Ok(Profile {
30 id: user["id"].as_str().unwrap_or_default().to_owned(),
31 name: user["global_name"].as_str().map(str::to_owned),
32 nickname: user["username"].as_str().map(str::to_owned),
33 email: user["email"].as_str().map(|address| Email {
34 address: address.to_owned(),
35 verified: user["verified"] == true,
36 }),
37 avatar: None,
38 raw: user,
39 })
40 }
41}

Laravel attaches the provider name and access token to your Profile to build the social::User returned by social::user. If user returns an error or an empty id, Laravel fails the login with a 502 response and reports the error. Only set verified: true when the provider explicitly reports that it verified the email address, since account linking relies on it.

If a provider returns an OpenID Connect ID token alongside the access token, as Google does, you may decode its claims with tokens.id_token() instead of calling an API. Laravel verifies that the ID token was issued to your client ID, and your user method should verify its iss (issuer) claim.

Testing

Your tests shouldn't log in to Google. social::fake() replaces every provider for as long as you hold the handle it returns. While it does, social::redirect sends the user to a fake URL, and social::user returns the user you give it, without asking the provider or checking the session.

Build that user with social::User::fake, which takes the provider's ID for the user:

1use laravel::auth::social::{self, Provider};
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn people_can_sign_up_with_google(app: Application) {
6 let social = social::fake().with(
7 Provider::GOOGLE,
8 social::User::fake("google-123")
9 .name("Taylor Otwell")
10 .verified_email("[email protected]"),
11 );
12 
13 app.get("/auth/google/redirect").await.assert_redirect();
14 
15 social.assert_redirected(Provider::GOOGLE);
16 
17 let response = app.get("/auth/google/callback").await;
18 
19 response.assert_redirect_to("/dashboard");
20 
21 app.get("/dashboard").with_cookies_from(&response).await.assert_ok();
22 
23 app.assert_database_has(
24 "users",
25 json!({ "email": "[email protected]", "provider_id": "google-123" }),
26 ).await;
27}
1use laravel::auth::social::{self, Provider};
2use laravel::testing::prelude::*;
3 
4#[laravel::test]
5async fn people_can_sign_up_with_google(app: Application) {
6 let social = social::fake().with(
7 Provider::GOOGLE,
8 social::User::fake("google-123")
9 .name("Taylor Otwell")
10 .verified_email("[email protected]"),
11 );
12 
13 app.get("/auth/google/redirect").await.assert_redirect();
14 
15 social.assert_redirected(Provider::GOOGLE);
16 
17 let response = app.get("/auth/google/callback").await;
18 
19 response.assert_redirect_to("/dashboard");
20 
21 app.get("/dashboard").with_cookies_from(&response).await.assert_ok();
22 
23 app.assert_database_has(
24 "users",
25 json!({ "email": "[email protected]", "provider_id": "google-123" }),
26 ).await;
27}

A fake user's raw is null, so code that reads it, such as the hd check, finds no claims and refuses the user. Give the fake user the claims the provider would send with raw:

1let _social = social::fake().with(
2 Provider::GOOGLE,
3 social::User::fake("google-123")
4 .verified_email("[email protected]")
5 .raw(json!({ "hd": "example.com" })),
6);
1let _social = social::fake().with(
2 Provider::GOOGLE,
3 social::User::fake("google-123")
4 .verified_email("[email protected]")
5 .raw(json!({ "hd": "example.com" })),
6);

To test a user who arrives with an unverified email address, use unverified_email instead of verified_email. To test a user who cancels, use denied. This test expects the callback from When the user cancels, which sends them back to the login page:

1let _social = social::fake().denied(Provider::MICROSOFT);
2 
3app.get("/auth/microsoft/callback").await.assert_redirect_to("/login");
1let _social = social::fake().denied(Provider::MICROSOFT);
2 
3app.get("/auth/microsoft/callback").await.assert_redirect_to("/login");

social::fake() also accepts the names of any providers you add, such as .with("gitlab", social::User::fake("1234")).