Social Login
- Introduction
- Complete Example: Generated OAuth Login
- Configuration
- Authentication
- Retrieving User Details
- Other Providers
- Testing
Introduction
Social login lets users log in with an account they already have, like Laravel Socialite. DotBlaze has GitHub, Google, and Microsoft built in, speaks OAuth 2 for any other provider, and makes its HTTP calls with the Http client, so they can be faked in tests.
Configuration
Create an OAuth app at the provider and put its credentials in config/Services.cs. The callback URL is made absolute with app.url:
public class ServicesConfig : ConfigFile
{
public override object Values() => new
{
github = new
{
client_id = Env("GITHUB_CLIENT_ID"),
client_secret = Env("GITHUB_CLIENT_SECRET"),
redirect = "/auth/github/callback",
},
};
}Socialite.Configured("github") tells whether a client id is set; the sample's login page shows its buttons only then.
Microsoft
Register an application in Microsoft Entra ID, choose its supported account types, and add a Web redirect URI matching your absolute callback URL (for example, https://example.com/auth/microsoft/callback). Create a client secret and configure:
microsoft = new
{
client_id = Env("MICROSOFT_CLIENT_ID"),
client_secret = Env("MICROSOFT_CLIENT_SECRET"),
redirect = "/auth/microsoft/callback",
tenant = Env("MICROSOFT_TENANT", "common"),
},Use the application's client ID and the client secret value in .env:
MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=
MICROSOFT_TENANT=commonThe optional tenant defaults to common (personal Microsoft accounts and work/school accounts). Use consumers for personal accounts, organizations for work/school accounts, or a tenant ID/domain for a single tenant. The app registration's supported account types must match.
public Task<IActionResult> ToMicrosoft() => Socialite.Driver("microsoft").Redirect();
// In the callback:
var microsoft = await Socialite.Driver("microsoft").User();The driver uses Microsoft identity platform v2 endpoints and the delegated User.Read permission to retrieve the profile from Microsoft Graph /v1.0/me. Id is the Graph user ID, Name is displayName, Nickname is userPrincipalName, and Email uses mail, falling back to userPrincipalName. Graph does not return a public avatar URL, so Avatar is null.
Add .Scopes("offline_access") when you need Microsoft to issue a refresh token. RefreshToken and ExpiresIn are populated from the token response; tokens are not refreshed automatically.
Authentication
Routing
Two routes: one sends the user to the provider, the other receives them back. dotblaze make:auth adds them, with SocialiteController:
Route.Get<SocialiteController>("/auth/{provider}/redirect", c => c.ToProvider).Name("socialite.redirect");
Route.Get<SocialiteController>("/auth/{provider}/callback", c => c.Callback).Name("socialite.callback");public Task<IActionResult> ToProvider(string provider) => Socialite.Driver(provider).Redirect();
public async Task<IActionResult> Callback(string provider)
{
var github = await Socialite.Driver(provider).User();
...
}Redirect keeps a random state in the session; User() checks it (an old or forged callback throws InvalidStateException), exchanges the code for an access token, and fetches the user.
Authentication and Storage
Find or create your user and log them in. From the sample app:
var user = await User.Where(u => u.Email == social.Email).First()
?? await User.Create(new { Name = social.Name ?? social.Nickname ?? social.Email, social.Email, Password = Str.Random(40) });
if (user.EmailVerifiedAt is null)
{
user.EmailVerifiedAt = DateTime.UtcNow; // the provider verified the address
await user.Save();
}
if (user is ITwoFactorAuthenticatable twoFactor && TwoFactor.Enabled(twoFactor))
{
await TwoFactor.Challenge(twoFactor, remember: true);
return RedirectRoute("two-factor.login");
}
await Auth.Login(user, remember: true);Users with two-factor authentication should still get the challenge, as the sample's controller does.
Scopes and Parameters
return await Socialite.Driver("github").Scopes("read:org", "repo").Redirect(); // in addition to the defaults
return await Socialite.Driver("github").SetScopes("read:user").Redirect(); // instead of them
return await Socialite.Driver("google").With(new { prompt = "select_account" }).Redirect();GitHub asks for user:email by default (to read a private address), Google for openid profile email, and Microsoft for User.Read.
Stateless Authentication
Stateless() skips the state check, for APIs without a session.
Retrieving User Details
SocialiteUser has Id, Name, Nickname, Email (nullable), Avatar, Token, RefreshToken, ExpiresIn, and Raw, the provider's own JSON.
Other Providers
Subclass SocialiteProvider with the provider's URLs and how to read its user, and register it:
public sealed class GitLabProvider(IConfigurationSection config) : SocialiteProvider(config)
{
protected override string AuthorizeUrl => "https://gitlab.com/oauth/authorize";
protected override string TokenUrl => "https://gitlab.com/oauth/token";
protected override IEnumerable<string> DefaultScopes => ["read_user"];
protected override async Task<SocialiteUser> UserFromToken(string token, JsonNode tokenResponse)
{
var user = (await Http.WithToken(token).Get("https://gitlab.com/api/v4/user")).Throw().Json()!;
return new SocialiteUser { Id = user["id"]!.ToString(), Name = user["name"]?.GetValue<string>(), Email = user["email"]?.GetValue<string>(), Token = token, Raw = user };
}
}
// AppServiceProvider.Boot
Socialite.Extend("gitlab", config => new GitLabProvider(config));Testing
Fake the provider's endpoints with Http.Fake; the fake reaches the requests of the test client:
Http.Fake(new()
{
["github.com/login/oauth/access_token"] = Http.Response(new { access_token = "gho_token" }),
["api.github.com/user"] = Http.Response(new { id = 42, login = "octocat", name = "The Octocat", email = "octo@example.com" }),
});
var browser = app.Client();
var redirect = await browser.Get("/auth/github/redirect");
var state = Regex.Match(redirect.Location!, "state=([^&]+)").Groups[1].Value;
(await browser.Get($"/auth/github/callback?code=abc&state={state}")).AssertRedirect("/posts");Complete Example: Generated OAuth Login
Use dotblaze make:auth in the Blog application. The generated SocialiteController supplies provider allowlisting, missing-email handling, OAuth error handling, user persistence, and the two-factor challenge. Keep those checks when adapting the smaller reference excerpts.
Set the GitHub client ID, client secret, and callback URL read by the existing config/Services.cs (see configuration). Register that exact callback URL with GitHub, including scheme, host, port, and /auth/github/callback. Then run:
dotblaze migrate
dotblaze serveOpen /auth/github/redirect in a browser and authorize the application. Expected: the callback creates or finds the user, then redirects to the application's home or two-factor challenge. An unconfigured provider returns 404; a callback without the matching session state fails. Do not call Stateless() to fix a lost browser cookie.
The complete source is SocialiteController.cs; executable provider-response and state checks are in SocialiteTest.cs and AuthPackagesTest.cs. The generated controller's account matching assumes the configured provider has verified the email; custom provider adapters must enforce that contract before returning a usable email.