Social Login
- Introduction
- Configuration
- Preparing your users table
- Authentication
- Retrieving user details
- Adding providers
- Testing
Introduction
Someone trying your application for the first time may not want to make up yet another password. For example, a Continue with Google button lets them sign up with an account they already have, and log back in later with one click. The auth/social package lets your users log in with their Google, GitHub, or Microsoft accounts, and you may add other providers, such as GitLab, Okta, or Keycloak. It sends the user to the provider, checks the response that comes back, and gives you the user's ID, name, and email address. You decide what to store, then log the user in with auth.Login, as you would after any other login.
Because social login keeps each login's state in the session, add its routes to routes/web.go, whose routes run 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=34GITHUB_CLIENT_ID=5GITHUB_CLIENT_SECRET=67MICROSOFT_CLIENT_ID=8MICROSOFT_CLIENT_SECRET=1GOOGLE_CLIENT_ID=2GOOGLE_CLIENT_SECRET=34GITHUB_CLIENT_ID=5GITHUB_CLIENT_SECRET=67MICROSOFT_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 host, 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 the request's host:
1GOOGLE_REDIRECT_URI=/login/google/callback1GOOGLE_REDIRECT_URI=/login/google/callback
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 organization uses GitHub Enterprise Server, create the OAuth app on your enterprise instance and set GITHUB_URL to its base URL. Laravel redirects logins to that server and reads user profiles from /api/v3:
1GITHUB_URL=https://github.example.com1GITHUB_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. The claim tells Laravel whether a work or school account's email address belongs to the person logging in. Without it, Laravel reports those addresses as unverified, and your application can't link the accounts to existing users. Personal Microsoft accounts don't need the claim.
Preparing your users table
Your users table needs to record which provider account belongs to each user, so add provider and provider_id columns. Users who sign up through a provider have no password, so make the password column nullable too. This migration changes the users table that new applications create:
1// database/migrations/2026_11_12_000000_add_social_login_to_users_table.go2package migrations34import (5 "context"67 "go.laravel.com/schema"8)910func addSocialLoginToUsersTable(ctx context.Context) error {11 return schema.Alter(ctx, "users", func(table *schema.Blueprint) {12 table.String("password").Nullable().Change()13 table.String("provider").Nullable()14 table.String("provider_id").Nullable()1516 table.Unique("provider", "provider_id")17 })18}1// database/migrations/2026_11_12_000000_add_social_login_to_users_table.go2package migrations34import (5 "context"67 "go.laravel.com/schema"8)910func addSocialLoginToUsersTable(ctx context.Context) error {11 return schema.Alter(ctx, "users", func(table *schema.Blueprint) {12 table.String("password").Nullable().Change()13 table.String("provider").Nullable()14 table.String("provider_id").Nullable()1516 table.Unique("provider", "provider_id")17 })18}
List it in All, in database/migrations/migrations.go, after the migration that creates the table:
1{Name: "2026_11_12_000000_add_social_login_to_users_table", Run: addSocialLoginToUsersTable},1{Name: "2026_11_12_000000_add_social_login_to_users_table", Run: addSocialLoginToUsersTable},
Then add the fields to your User model, and make its password a pointer, which is nil for a user without one. A social.Provider field stores the provider's name, such as google or github. Keep any methods you've added to the model, such as MailAddress, which password reset emails need:
1// models/user.go2package models34import (5 "time"67 "go.laravel.com/auth/social"8)910type User struct {11 ID int64 `json:"id"`12 Name string `json:"name"`13 Email string `json:"email"`14 EmailVerifiedAt *time.Time `json:"email_verified_at"`15 Password *string `json:"-"`16 RememberToken *string `json:"-"`17 Provider *social.Provider `json:"provider"`18 ProviderID *string `json:"-"`19 CreatedAt time.Time `json:"created_at"`20 UpdatedAt time.Time `json:"updated_at"`21}1// models/user.go2package models34import (5 "time"67 "go.laravel.com/auth/social"8)910type User struct {11 ID int64 `json:"id"`12 Name string `json:"name"`13 Email string `json:"email"`14 EmailVerifiedAt *time.Time `json:"email_verified_at"`15 Password *string `json:"-"`16 RememberToken *string `json:"-"`17 Provider *social.Provider `json:"provider"`18 ProviderID *string `json:"-"`19 CreatedAt time.Time `json:"created_at"`20 UpdatedAt time.Time `json:"updated_at"`21}
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 routes/web.go in a RedirectIfAuthenticated group, with your other guest-only pages:
1// routes/web.go2package routes34import (5 "go.laravel.com/auth"6 "go.laravel.com/config"7 "go.laravel.com/routing"89 "app/handlers/sociallogin"10)1112func Web(route *routing.Router, cfg *config.Config) {13 route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {14 route.Get("/auth/{provider}/redirect", sociallogin.Redirect)15 route.Get("/auth/{provider}/callback", sociallogin.Callback)16 })17}1// routes/web.go2package routes34import (5 "go.laravel.com/auth"6 "go.laravel.com/config"7 "go.laravel.com/routing"89 "app/handlers/sociallogin"10)1112func Web(route *routing.Router, cfg *config.Config) {13 route.Middleware(auth.RedirectIfAuthenticated{}).Group(func(route *routing.Router) {14 route.Get("/auth/{provider}/redirect", sociallogin.Redirect)15 route.Get("/auth/{provider}/callback", sociallogin.Callback)16 })17}
The redirect handler, in a sociallogin package of your own, passes the provider to social.Redirect, which sends the user to the provider's login page:
1// handlers/sociallogin/sociallogin.go2package sociallogin34import (5 "go.laravel.com/auth/social"6 "go.laravel.com/web"7)89func Redirect(r *web.Request) *web.Response {10 return social.Redirect(r, social.Provider(r.PathValue("provider")))11}1// handlers/sociallogin/sociallogin.go2package sociallogin34import (5 "go.laravel.com/auth/social"6 "go.laravel.com/web"7)89func Redirect(r *web.Request) *web.Response {10 return social.Redirect(r, social.Provider(r.PathValue("provider")))11}
social.Redirect accepts google, github, microsoft, and the names of the providers you add, so a request for any other provider name in the URL gets a 404. A provider whose client ID and secret you haven't set gets a 404 too, and a warning in your log names the variables to set.
Link to the redirect route from your login page, with Inertia's <Link> or a plain <a> tag. social.Redirect tells Inertia to leave your application with a full page load:
1import { Link } from "@inertiajs/react";23<Link href="/auth/google/redirect">Continue with Google</Link>4<Link href="/auth/microsoft/redirect">Continue with Microsoft</Link>1import { Link } from "@inertiajs/react";23<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 sends them back to your callback route. There, social.User checks that the callback belongs to a login this user's session started, then asks the provider who the user is. This callback handler, in the same file, creates the user's account on their first visit and logs them in:
1package sociallogin23import (4 "cmp"5 "context"6 "database/sql"7 "errors"89 "go.laravel.com/auth"10 "go.laravel.com/auth/social"11 "go.laravel.com/date"12 "go.laravel.com/db"13 "go.laravel.com/inertia"14 "go.laravel.com/model"15 "go.laravel.com/web"1617 "app/models"18)1920func Callback(r *web.Request) *web.Response {21 profile, err := social.User(r, social.Provider(r.PathValue("provider")))22 if err != nil {23 return web.Fail(err)24 }2526 user, err := findOrCreateUser(r, profile)27 if err != nil {28 return web.Fail(err)29 }30 if user == nil {31 inertia.Flash(r, "status", "We couldn't confirm your email address.")3233 return web.Redirect("/login")34 }3536 if err := auth.Login(r, user, true); err != nil {37 return web.Fail(err)38 }3940 return auth.RedirectIntended("/dashboard")41}4243func findOrCreateUser(ctx context.Context, profile *social.Profile) (*models.User, error) {44 linked, err := model.Query[models.User]().45 Where("provider", "=", profile.Provider).46 Where("provider_id", "=", profile.ID).47 First(ctx)48 if err == nil {49 return &linked, nil50 }51 if !errors.Is(err, sql.ErrNoRows) {52 return nil, err53 }5455 email := profile.VerifiedEmail()56 if email == "" {57 return nil, nil58 }5960 user, err := model.Query[models.User]().Where("email", "=", email).First(ctx)61 if errors.Is(err, sql.ErrNoRows) {62 now := date.Now(ctx)63 user = models.User{64 Name: cmp.Or(profile.Name, email),65 Email: email,66 EmailVerifiedAt: &now,67 Provider: &profile.Provider,68 ProviderID: &profile.ID,69 }7071 return &user, model.Create(ctx, &user)72 }73 if err != nil {74 return nil, err75 }7677 if user.EmailVerifiedAt == nil {78 values := db.Values{"password": nil, "email_verified_at": date.Now(ctx)}79 if err := model.Update(ctx, &user, values); err != nil {80 return nil, err81 }82 }83 if user.Provider == nil {84 values := db.Values{"provider": profile.Provider, "provider_id": profile.ID}85 if err := model.Update(ctx, &user, values); err != nil {86 return nil, err87 }88 }8990 return &user, nil91}1package sociallogin23import (4 "cmp"5 "context"6 "database/sql"7 "errors"89 "go.laravel.com/auth"10 "go.laravel.com/auth/social"11 "go.laravel.com/date"12 "go.laravel.com/db"13 "go.laravel.com/inertia"14 "go.laravel.com/model"15 "go.laravel.com/web"1617 "app/models"18)1920func Callback(r *web.Request) *web.Response {21 profile, err := social.User(r, social.Provider(r.PathValue("provider")))22 if err != nil {23 return web.Fail(err)24 }2526 user, err := findOrCreateUser(r, profile)27 if err != nil {28 return web.Fail(err)29 }30 if user == nil {31 inertia.Flash(r, "status", "We couldn't confirm your email address.")3233 return web.Redirect("/login")34 }3536 if err := auth.Login(r, user, true); err != nil {37 return web.Fail(err)38 }3940 return auth.RedirectIntended("/dashboard")41}4243func findOrCreateUser(ctx context.Context, profile *social.Profile) (*models.User, error) {44 linked, err := model.Query[models.User]().45 Where("provider", "=", profile.Provider).46 Where("provider_id", "=", profile.ID).47 First(ctx)48 if err == nil {49 return &linked, nil50 }51 if !errors.Is(err, sql.ErrNoRows) {52 return nil, err53 }5455 email := profile.VerifiedEmail()56 if email == "" {57 return nil, nil58 }5960 user, err := model.Query[models.User]().Where("email", "=", email).First(ctx)61 if errors.Is(err, sql.ErrNoRows) {62 now := date.Now(ctx)63 user = models.User{64 Name: cmp.Or(profile.Name, email),65 Email: email,66 EmailVerifiedAt: &now,67 Provider: &profile.Provider,68 ProviderID: &profile.ID,69 }7071 return &user, model.Create(ctx, &user)72 }73 if err != nil {74 return nil, err75 }7677 if user.EmailVerifiedAt == nil {78 values := db.Values{"password": nil, "email_verified_at": date.Now(ctx)}79 if err := model.Update(ctx, &user, values); err != nil {80 return nil, err81 }82 }83 if user.Provider == nil {84 values := db.Values{"provider": profile.Provider, "provider_id": profile.ID}85 if err := model.Update(ctx, &user, values); err != nil {86 return nil, err87 }88 }8990 return &user, nil91}
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, findOrCreateUser returns no user, and the handler sends the user back to the login page with a message instead. The handler flashes the message with inertia.Flash, so the login page receives it.
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 it links an account whose email address your application never verified, the handler removes the account's password and marks the address verified. Otherwise, someone could sign up with another person's address and a password of their own, and keep using that password after the address's owner links their Google account. Removing the password also logs out every session and remember cookie made with it. If the owner wants a password, they can set one with a password reset.
Only link accounts by an email address that VerifiedEmail 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 address for something else, such as a contact address, read profile.Email. It holds the address even when the provider didn't verify it, and profile.EmailVerified says whether the provider did.
When the user cancels
When the user declines on the provider's consent screen, social.User returns social.ErrDenied. Passed to web.Fail, it responds with a 403. Most applications send the user back to the login page instead, by checking for it first in the callback handler:
1profile, err := social.User(r, social.Provider(r.PathValue("provider")))2if errors.Is(err, social.ErrDenied) {3 return web.Redirect("/login")4}5if err != nil {6 return web.Fail(err)7}1profile, err := social.User(r, social.Provider(r.PathValue("provider")))2if errors.Is(err, social.ErrDenied) {3 return web.Redirect("/login")4}5if err != nil {6 return web.Fail(err)7}
Pass the other errors to web.Fail. social.ErrInvalidState is a 403 for a callback that doesn't belong to a login from this session, such as an old callback URL opened again. A *social.ProviderError is a 502 for a provider that failed, and Laravel reports it, so you'll find the reason in your logs.
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, call social.RedirectWith with the scopes. They add to the defaults:
1func ConnectGitHub(r *web.Request) *web.Response {2 return social.RedirectWith(r, social.GitHub, social.Options{Scopes: []string{"repo"}})3}1func ConnectGitHub(r *web.Request) *web.Response {2 return social.RedirectWith(r, social.GitHub, social.Options{Scopes: []string{"repo"}})3}
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:
1return social.RedirectWith(r, social.Google, social.Options{2 Params: url.Values{"prompt": {"select_account"}},3})1return social.RedirectWith(r, social.Google, social.Options{2 Params: url.Values{"prompt": {"select_account"}},3})
Don't put state, scope, or redirect_uri in Params. Social login sets them itself, and RedirectWith panics on them. Use Scopes to ask for scopes.
Retrieving user details
social.User returns a *social.Profile. These are its fields:
| Field | Type | What it holds |
|---|---|---|
Provider |
social.Provider |
The provider the user logged in with |
ID |
string |
The user's ID at the provider. It never changes |
Name |
string |
The user's full name |
Nickname |
string |
The user's username, such as their GitHub username. Google and Microsoft don't have one |
Email |
string |
The email address, whether or not the provider verified it |
EmailVerified |
bool |
Whether the provider verified that the user owns Email |
Avatar |
string |
The URL of the user's picture. Microsoft doesn't send one |
Token |
social.Token |
The access token, for calling the provider's API on the user's behalf |
Raw |
map[string]any |
Everything the provider said about the user |
A field the provider didn't send is empty. The social.Token in the Token field holds the access token itself in Access. Its Refresh and ExpiresAt fields are set when the provider sends them, and Scopes lists the scopes the user granted. Printing a social.Token hides the access token, but encoding it as JSON doesn't. If you need to call the provider's API later, store the social.Token in an encrypted column, which needs a text column in its migration, such as table.Text("github_token").Nullable():
1// models/user.go2package models34import (5 "go.laravel.com/auth/social"6 "go.laravel.com/crypt"7)89type User struct {10 ID int64 `json:"id"`11 // ...12 GitHubToken *crypt.Encrypted[social.Token] `json:"-" db:"github_token"`13}1// models/user.go2package models34import (5 "go.laravel.com/auth/social"6 "go.laravel.com/crypt"7)89type User struct {10 ID int64 `json:"id"`11 // ...12 GitHubToken *crypt.Encrypted[social.Token] `json:"-" db:"github_token"`13}
The db tag names the column, since the field's name in snake case would be git_hub_token. Save profile.Token in your callback, then read the token's Access whenever you need to call the provider's API through the HTTP client:
1// Store the encrypted token in your callback...2err := model.Update(r, user, db.Values{"github_token": profile.Token})34// Later, read the decrypted token to call the provider's API...5if user.GitHubToken != nil {6 repos, err := httpclient.Token(user.GitHubToken.Value.Access).7 Get(r, "https://api.github.com/user/repos")8}1// Store the encrypted token in your callback...2err := model.Update(r, user, db.Values{"github_token": profile.Token})34// Later, read the decrypted token to call the provider's API...5if user.GitHubToken != nil {6 repos, err := httpclient.Token(user.GitHubToken.Value.Access).7 Get(r, "https://api.github.com/user/repos")8}
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:
1company, _ := profile.Raw["company"].(string)1company, _ := profile.Raw["company"].(string)
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:
1if profile.Provider == social.Google && profile.Raw["hd"] != "example.com" {2 return web.Abort(http.StatusForbidden)3}1if profile.Provider == social.Google && profile.Raw["hd"] != "example.com" {2 return web.Abort(http.StatusForbidden)3}
You may also pass "hd": {"example.com"} in Params, 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
In addition to Google, GitHub, and Microsoft, you may register any OAuth 2.0 provider, such as GitLab, Okta, or Keycloak, under a name of your choice. Once registered, social.Redirect, social.User, and FakeSocial accept that provider name with the same state and PKCE verification as the built-in providers, so your routes, callback handler, and tests work without changes. Register /auth/{provider}/callback as the callback URL in the provider's developer settings, such as /auth/gitlab/callback.
To add a provider, register a social.OAuth2 entry in your options' Register function inside bootstrap/app.go with the provider's authorization URL, token URL, and user info URL. Reading settings from app.Env() respects .env.testing and laraveltest.Env in tests. For example, this registers GitLab and lets you point it at a self-hosted GitLab instance with GITLAB_URL:
1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 gitlab := app.Env().String("GITLAB_URL", "https://gitlab.com")67 app.SocialProvider("gitlab", social.OAuth2{8 AuthorizeURL: gitlab + "/oauth/authorize",9 TokenURL: gitlab + "/oauth/token",10 Scopes: []string{"openid", "profile", "email"},11 ClientID: app.Env().String("GITLAB_CLIENT_ID", ""),12 ClientSecret: app.Env().String("GITLAB_CLIENT_SECRET", ""),13 User: social.UserInfo(gitlab + "/oauth/userinfo"),14 })1516 return nil17 },18 // ...19 }20}1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 gitlab := app.Env().String("GITLAB_URL", "https://gitlab.com")67 app.SocialProvider("gitlab", social.OAuth2{8 AuthorizeURL: gitlab + "/oauth/authorize",9 TokenURL: gitlab + "/oauth/token",10 Scopes: []string{"openid", "profile", "email"},11 ClientID: app.Env().String("GITLAB_CLIENT_ID", ""),12 ClientSecret: app.Env().String("GITLAB_CLIENT_SECRET", ""),13 User: social.UserInfo(gitlab + "/oauth/userinfo"),14 })1516 return nil17 },18 // ...19 }20}
1GITLAB_URL=https://gitlab.example.com2GITLAB_CLIENT_ID=3GITLAB_CLIENT_SECRET=1GITLAB_URL=https://gitlab.example.com2GITLAB_CLIENT_ID=3GITLAB_CLIENT_SECRET=
social.UserInfo reads standard OpenID Connect user info endpoints, which providers such as GitLab, Okta, Keycloak, and Auth0 support. It maps sub to ID, preferred_username to Nickname, picture to Avatar, and name, email, and email_verified to their matching fields on social.Profile. Every field the endpoint returns is also available in Raw, such as GitLab's groups. Include "openid" in Scopes so the provider returns standard OpenID Connect claims.
If a provider's ClientID is empty, its routes return a 404 response. To request additional scopes for a single login, pass them to social.RedirectWith.
If you're distributing a provider in a package, register it inside the package's Register method with app.SocialProvider("gitlab", provider). Providers registered in your application's Register function take precedence over both package providers and Laravel's built-in google, github, and microsoft providers.
VerifiedEmail trusts the provider's email_verified field. On a provider administered by a third party, such as a customer's Okta organization, that administrator controls which addresses count as verified. Only link existing accounts by email address through providers whose administrators you trust.
Reading profiles from the provider's API
Some OAuth 2.0 providers don't return standard OpenID Connect fields. For example, Discord returns the user's handle in username and their email verification status in verified. For these providers, supply a User function that fetches the user's profile using the access token:
1// bootstrap/app.go2Register: func(app *laravel.Registrar) error {3 app.SocialProvider("discord", social.OAuth2{4 AuthorizeURL: "https://discord.com/oauth2/authorize",5 TokenURL: "https://discord.com/api/oauth2/token",6 Scopes: []string{"identify", "email"},7 ClientID: app.Env().String("DISCORD_CLIENT_ID", ""),8 ClientSecret: app.Env().String("DISCORD_CLIENT_SECRET", ""),9 User: sociallogin.DiscordUser,10 })1112 return nil13},1// bootstrap/app.go2Register: func(app *laravel.Registrar) error {3 app.SocialProvider("discord", social.OAuth2{4 AuthorizeURL: "https://discord.com/oauth2/authorize",5 TokenURL: "https://discord.com/api/oauth2/token",6 Scopes: []string{"identify", "email"},7 ClientID: app.Env().String("DISCORD_CLIENT_ID", ""),8 ClientSecret: app.Env().String("DISCORD_CLIENT_SECRET", ""),9 User: sociallogin.DiscordUser,10 })1112 return nil13},
The User function calls Discord's API with the HTTP client and maps the response into a social.Profile:
1// handlers/sociallogin/discord.go2package sociallogin34import (5 "context"67 "go.laravel.com/auth/social"8 "go.laravel.com/httpclient"9)1011func DiscordUser(ctx context.Context, token social.Token) (*social.Profile, error) {12 res, err := httpclient.Token(token.Access).13 EnsureSuccessful().14 Get(ctx, "https://discord.com/api/users/@me")15 if err != nil {16 return nil, err17 }1819 type discordUser struct {20 ID string `json:"id"`21 Username string `json:"username"`22 Name string `json:"global_name"`23 Email string `json:"email"`24 Verified bool `json:"verified"`25 }26 user, err := res.JSON[discordUser]()27 if err != nil {28 return nil, err29 }3031 return &social.Profile{32 ID: user.ID,33 Name: user.Name,34 Nickname: user.Username,35 Email: user.Email,36 EmailVerified: user.Verified,37 }, nil38}1// handlers/sociallogin/discord.go2package sociallogin34import (5 "context"67 "go.laravel.com/auth/social"8 "go.laravel.com/httpclient"9)1011func DiscordUser(ctx context.Context, token social.Token) (*social.Profile, error) {12 res, err := httpclient.Token(token.Access).13 EnsureSuccessful().14 Get(ctx, "https://discord.com/api/users/@me")15 if err != nil {16 return nil, err17 }1819 type discordUser struct {20 ID string `json:"id"`21 Username string `json:"username"`22 Name string `json:"global_name"`23 Email string `json:"email"`24 Verified bool `json:"verified"`25 }26 user, err := res.JSON[discordUser]()27 if err != nil {28 return nil, err29 }3031 return &social.Profile{32 ID: user.ID,33 Name: user.Name,34 Nickname: user.Username,35 Email: user.Email,36 EmailVerified: user.Verified,37 }, nil38}
Laravel populates Provider and Token on the returned profile automatically. If your User function returns an error or an empty ID, the login fails with a *social.ProviderError and returns a 502 response. Only set EmailVerified when the provider explicitly confirms that the user owns the email address, since linking existing accounts relies on it.
Testing
Your tests shouldn't log in to Google. The test client's FakeSocial method returns a client whose logins with a provider skip it. With that client, social.Redirect sends the user to a fake URL, and social.User returns the profile you give it, without asking the provider or checking the session:
1package feature_test23import (4 "testing"56 "go.laravel.com/auth/social"7 "go.laravel.com/db"89 "app/tests"10)1112func TestPeopleCanSignUpWithGoogle(t *testing.T) {13 client := tests.New(t)14 google := client.FakeSocial(social.Google, &social.Profile{15 ID: "google-123",16 Name: "Taylor Otwell",18 EmailVerified: true,19 })2021 google.Get("/auth/google/redirect").AssertRedirect("https://social.fake/google/authorize")22 google.Get("/auth/google/callback").AssertRedirect("/dashboard")2324 client.Get("/dashboard").AssertOK()25 client.AssertDatabaseHas("users", db.Values{27 "provider_id": "google-123",28 })29}1package feature_test23import (4 "testing"56 "go.laravel.com/auth/social"7 "go.laravel.com/db"89 "app/tests"10)1112func TestPeopleCanSignUpWithGoogle(t *testing.T) {13 client := tests.New(t)14 google := client.FakeSocial(social.Google, &social.Profile{15 ID: "google-123",16 Name: "Taylor Otwell",18 EmailVerified: true,19 })2021 google.Get("/auth/google/redirect").AssertRedirect("https://social.fake/google/authorize")22 google.Get("/auth/google/callback").AssertRedirect("/dashboard")2324 client.Get("/dashboard").AssertOK()25 client.AssertDatabaseHas("users", db.Values{27 "provider_id": "google-123",28 })29}
The fake client shares its cookies with client, so the user it logged in stays logged in for client's requests.
A fake profile's Raw is nil, so code that reads it, such as the hd check, finds no claims and refuses the user. Give the fake profile the claims the provider would send in Raw:
1google := client.FakeSocial(social.Google, &social.Profile{2 ID: "google-123",4 EmailVerified: true,5 Raw: map[string]any{"hd": "example.com"},6})1google := client.FakeSocial(social.Google, &social.Profile{2 ID: "google-123",4 EmailVerified: true,5 Raw: map[string]any{"hd": "example.com"},6})
To test a user who arrives with an unverified email address, leave EmailVerified false. To test a user who cancels, use FakeSocialDenied. This test expects the callback from When the user cancels, which sends them back to the login page:
1client.FakeSocialDenied(social.Microsoft).Get("/auth/microsoft/callback").AssertRedirect("/login")1client.FakeSocialDenied(social.Microsoft).Get("/auth/microsoft/callback").AssertRedirect("/login")