Quickstart
Add Google and GitHub login with a backend router and simple frontend SDK helpers.
1. Create your project
Create an AnyOAuth project, enable Google and GitHub,
and register http://localhost:3000/auth/callback. Save the client ID and client
secret in your backend environment. You do not need your own Google or GitHub app.
Use the current SDK source for the helpers
below. The published 0.1.0 packages predate these methods.
2. Mount your backend router
Choose your backend language or Node.js server below. Configure AnyOAuth with your
project credentials and register your app’s exact /auth/callback URL:
Mount in your existing Express app.
import { createAuth } from "@anyoauth/node/express";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
app.use("/auth", auth.router());
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Mount in your existing Hono app.
import { createAuth } from "@anyoauth/node/auth";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
app.all("/auth/*", (c) => auth.handle(c.req.raw));
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Mount in your existing Fastify app. The SDK’s Node HTTP middleware writes to the raw response; hijack() hands response ownership to it.
import { createAuth } from "@anyoauth/node/express";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
const router = auth.router();
app.all("/auth/*", async (request, reply) => {
reply.hijack();
await router(request.raw, reply.raw);
});
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Save in app/auth/[...route]/route.js.
import { createAuth } from "@anyoauth/node/auth";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
// app/auth/[...route]/route.js
export const GET = auth.handle;
export const POST = auth.handle;
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Save in src/pages/auth/[...route].js and configure an Astro server adapter.
import { createAuth } from "@anyoauth/node/auth";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
// src/pages/auth/[...route].js (Astro with a server adapter)
export const prerender = false;
export const GET = ({ request }) => auth.handle(request);
export const POST = ({ request }) => auth.handle(request);
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Run this module with Node.js 22 or newer. The SDK middleware serves the /auth routes.
import { createServer } from 'node:http';
import { createAuth } from "@anyoauth/node/express";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
createServer(auth.router()).listen(3000);
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
Register this blueprint in your Flask app. Configure Flask-Session with a server-side store and HttpOnly, SameSite=Lax cookies; do not use Flask’s signed-cookie session for the private login attempt. Callback and session examples
import os
from flask import Blueprint, abort, current_app, jsonify, redirect, request, session
from anyoauth import Client, Error
auth = Blueprint("auth", __name__)
origin = "http://localhost:3000"
client = Client(os.environ["ANYOAUTH_CLIENT_ID"], os.environ["ANYOAUTH_CLIENT_SECRET"])
@auth.get("/login/<provider>")
def login(provider):
if provider not in ("google", "github"):
abort(400)
login = client.start_login({"provider": provider, "redirectUri": origin + "/auth/callback"})
session["pendingLogin"] = login["loginAttempt"]
return redirect(login["url"], 303)
@auth.get("/callback")
def callback():
if request.query_string or "pendingLogin" not in session:
abort(400)
attempt = session.pop("pendingLogin")
try:
result = client.complete_login({"loginAttempt": attempt})
except Error:
return jsonify(error="sign_in_failed"), 502
if result["status"] == "pending":
session["pendingLogin"] = attempt
return jsonify(status="pending"), 202
if result["status"] != "succeeded":
return redirect("/?auth_error=sign_in_failed", 303)
session.clear()
session["profile"] = result["profile"]
current_app.session_interface.regenerate(session)
return redirect("/", 303)
@auth.get("/profile")
def profile():
user = session.get("profile")
response = jsonify(user if user else {"error": "unauthorized"})
response.status_code = 200 if user else 401
response.headers["Cache-Control"] = "no-store"
return response
@auth.post("/logout")
def logout():
if request.headers.get("Origin") != origin:
abort(403)
session.clear()
return "", 204
# In your configured Flask app:
app.register_blueprint(auth, url_prefix="/auth")
python -m pip install anyoauth-sdkBackend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Mount in your Gin app using an scs.SessionManager. Serve Gin through sessions.LoadAndSave(router), backed by your session store. Callback and session examples
package main
import (
"encoding/json"
"net/http"
"os"
"github.com/alexedwards/scs/v2"
"github.com/gin-gonic/gin"
anyoauth "github.com/AnyOAuth/anyoauth-go"
)
func mountAuth(router *gin.Engine, sessions *scs.SessionManager) {
origin := "http://localhost:3000"
client, err := anyoauth.NewClient("https://api.anyoauth.com", os.Getenv("ANYOAUTH_CLIENT_ID"), os.Getenv("ANYOAUTH_CLIENT_SECRET"))
if err != nil { panic(err) }
auth := router.Group("/auth")
auth.GET("/login/:provider", func(c *gin.Context) {
provider := c.Param("provider")
if provider != "google" && provider != "github" { c.AbortWithStatus(400); return }
value, err := client.StartLogin(map[string]any{"provider": provider, "redirectUri": origin + "/auth/callback"})
if err != nil { c.AbortWithStatus(502); return }
login := value.(map[string]any)
attempt, err := json.Marshal(login["loginAttempt"])
if err != nil { c.AbortWithStatus(500); return }
sessions.Put(c.Request.Context(), "pendingLogin", string(attempt))
c.Redirect(http.StatusSeeOther, login["url"].(string))
})
auth.GET("/callback", func(c *gin.Context) {
if c.Request.URL.RawQuery != "" || c.Request.URL.ForceQuery { c.AbortWithStatus(400); return }
saved := sessions.PopString(c.Request.Context(), "pendingLogin")
var attempt map[string]any
if saved == "" || json.Unmarshal([]byte(saved), &attempt) != nil { c.AbortWithStatus(400); return }
value, err := client.CompleteLogin(map[string]any{"loginAttempt": attempt})
if err != nil { c.AbortWithStatus(502); return }
result := value.(map[string]any)
if result["status"] == "pending" {
sessions.Put(c.Request.Context(), "pendingLogin", saved)
c.JSON(202, gin.H{"status": "pending"}); return
}
if result["status"] != "succeeded" { c.Redirect(303, "/?auth_error=sign_in_failed"); return }
if sessions.RenewToken(c.Request.Context()) != nil { c.AbortWithStatus(500); return }
profile, err := json.Marshal(result["profile"])
if err != nil { c.AbortWithStatus(500); return }
sessions.Put(c.Request.Context(), "profile", string(profile))
c.Redirect(303, "/")
})
auth.GET("/profile", func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
profile := sessions.GetString(c.Request.Context(), "profile")
if profile == "" { c.JSON(401, gin.H{"error": "unauthorized"}); return }
c.Data(200, "application/json", []byte(profile))
})
auth.POST("/logout", func(c *gin.Context) {
if c.GetHeader("Origin") != origin { c.AbortWithStatus(403); return }
if sessions.Destroy(c.Request.Context()) != nil { c.AbortWithStatus(500); return }
c.Status(204)
})
}
go get github.com/AnyOAuth/anyoauth-goBackend SDK · application-owned routesCurrent source example
Add to routes/web.php, which already uses Laravel’s session middleware. Set services.anyoauth.client_id and client_secret in your configuration. Callback and session examples
<?php
// routes/web.php
use AnyOAuth\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
$client = new Client(config('services.anyoauth.client_id'), config('services.anyoauth.client_secret'));
$origin = 'http://localhost:3000';
Route::prefix('auth')->group(function () use ($client, $origin) {
Route::get('login/{provider}', function (Request $request, string $provider) use ($client, $origin) {
abort_unless(in_array($provider, ['google', 'github'], true), 400);
$login = $client->startLogin(['provider' => $provider, 'redirectUri' => $origin . '/auth/callback']);
$request->session()->put('pendingLogin', $login->loginAttempt);
return redirect()->away($login->url, 303);
});
Route::get('callback', function (Request $request) use ($client) {
abort_if(str_contains($request->getRequestUri(), '?'), 400);
$attempt = $request->session()->pull('pendingLogin');
abort_if($attempt === null, 400);
try { $result = $client->completeLogin(['loginAttempt' => $attempt]); }
catch (\AnyOAuth\Error $error) { return response()->json(['error' => 'sign_in_failed'], 502); }
if ($result->status === 'pending') {
$request->session()->put('pendingLogin', $attempt);
return response()->json(['status' => 'pending'], 202);
}
if ($result->status !== 'succeeded') return redirect('/?auth_error=sign_in_failed', 303);
$request->session()->regenerate();
$request->session()->put('profile', $result->profile);
return redirect('/', 303);
});
Route::get('profile', function (Request $request) {
$profile = $request->session()->get('profile');
return response()->json($profile ?? ['error' => 'unauthorized'], $profile ? 200 : 401)
->header('Cache-Control', 'no-store');
});
Route::post('logout', function (Request $request) use ($origin) {
abort_unless($request->header('Origin') === $origin, 403);
$request->session()->invalidate();
$request->session()->regenerateToken();
return response()->noContent();
})->withoutMiddleware(\Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class);
});
composer require anyoauth/anyoauthBackend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Add this Spring MVC controller to your Spring Boot app. Servlet HttpSession keeps the private login attempt on the server. Permit these auth routes in your Spring Security configuration, with the shown Origin check for logout. Callback and session examples
import com.anyoauth.AnyOAuth;
import com.google.gson.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.net.URI;
@RestController
@RequestMapping("/auth")
public class AuthController {
private final String origin = "http://localhost:3000";
private final AnyOAuth client = new AnyOAuth("https://api.anyoauth.com",
System.getenv("ANYOAUTH_CLIENT_ID"), System.getenv("ANYOAUTH_CLIENT_SECRET"));
@GetMapping("/login/{provider}")
public ResponseEntity<?> login(@PathVariable("provider") String provider, HttpServletRequest request) {
if (!provider.equals("google") && !provider.equals("github")) return ResponseEntity.badRequest().build();
var input = new JsonObject();
input.addProperty("provider", provider);
input.addProperty("redirectUri", origin + "/auth/callback");
var login = client.startLogin(input);
request.getSession().setAttribute("pendingLogin", login.getAsJsonObject("loginAttempt"));
return ResponseEntity.status(303).location(URI.create(login.get("url").getAsString())).build();
}
@GetMapping("/callback")
public ResponseEntity<?> callback(HttpServletRequest request) {
var session = request.getSession(false);
if (request.getQueryString() != null || session == null || session.getAttribute("pendingLogin") == null)
return ResponseEntity.badRequest().build();
var input = new JsonObject();
input.add("loginAttempt", (JsonObject) session.getAttribute("pendingLogin"));
session.removeAttribute("pendingLogin");
JsonObject result;
try { result = client.completeLogin(input); }
catch (AnyOAuth.SDKException error) { return ResponseEntity.status(502).build(); }
String status = result.get("status").getAsString();
if (status.equals("pending")) {
session.setAttribute("pendingLogin", input.getAsJsonObject("loginAttempt"));
return ResponseEntity.status(202).body(java.util.Map.of("status", "pending"));
}
if (!status.equals("succeeded")) return ResponseEntity.status(303).location(URI.create("/?auth_error=sign_in_failed")).build();
request.changeSessionId();
session.setAttribute("profile", result.getAsJsonObject("profile").toString());
return ResponseEntity.status(303).location(URI.create("/")).build();
}
@GetMapping("/profile")
public ResponseEntity<String> profile(HttpServletRequest request) {
var session = request.getSession(false);
String profile = session == null ? null : (String) session.getAttribute("profile");
return ResponseEntity.status(profile == null ? 401 : 200).header("Cache-Control", "no-store")
.header("Content-Type", "application/json").body(profile == null ? "{\"error\":\"unauthorized\"}" : profile);
}
@PostMapping("/logout")
public ResponseEntity<?> logout(HttpServletRequest request) {
if (!origin.equals(request.getHeader("Origin"))) return ResponseEntity.status(403).build();
var session = request.getSession(false);
if (session != null) session.invalidate();
return ResponseEntity.noContent().build();
}
}
Gradle: implementation("com.anyoauth:anyoauth:0.1.0")Backend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Add the routes and controller shown below. Use Rails’ encrypted cookie session or a server-side session store; the private attempt must not go in a signed-only cookie. Callback and session examples
# config/routes.rb
Rails.application.routes.draw do
get '/auth/login/:provider', to: 'auth#login'
get '/auth/callback', to: 'auth#callback'
get '/auth/profile', to: 'auth#profile'
post '/auth/logout', to: 'auth#logout'
end
# app/controllers/auth_controller.rb
require 'anyoauth'
class AuthController < ApplicationController
skip_forgery_protection only: :logout # The logout action checks Origin below.
ORIGIN = 'http://localhost:3000'
def login
return head(:bad_request) unless %w[google github].include?(params[:provider])
login = client.start_login('provider' => params[:provider], 'redirectUri' => ORIGIN + '/auth/callback')
session[:pendingLogin] = login['loginAttempt']
redirect_to login['url'], status: :see_other, allow_other_host: true
end
def callback
return head(:bad_request) unless request.query_string.empty? && session[:pendingLogin]
attempt = session.delete(:pendingLogin)
result = client.complete_login('loginAttempt' => attempt)
if result['status'] == 'pending'
session[:pendingLogin] = attempt
return render json: {status: 'pending'}, status: :accepted
end
return redirect_to('/?auth_error=sign_in_failed', status: :see_other) unless result['status'] == 'succeeded'
reset_session
session[:profile] = result['profile']
redirect_to '/', status: :see_other
rescue AnyOAuth::Error
head :bad_gateway
end
def profile
response.headers['Cache-Control'] = 'no-store'
render json: session[:profile] || {error: 'unauthorized'}, status: session[:profile] ? :ok : :unauthorized
end
def logout
return head(:forbidden) unless request.headers['Origin'] == ORIGIN
reset_session
head :no_content
end
private
def client
@client ||= AnyOAuth::Client.new(ENV.fetch('ANYOAUTH_CLIENT_ID'), ENV.fetch('ANYOAUTH_CLIENT_SECRET'))
end
end
gem install anyoauth-sdkBackend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Add these endpoints after UseSession(), UseAuthentication() and UseAuthorization(). Configure a distributed session store and AddAuthentication("anyoauth").AddCookie("anyoauth") in your app’s services. Callback and session examples
using System.Security.Claims;
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Authentication;
using AnyOAuth;
// In Program.cs, after configuring sessions and the "anyoauth" cookie scheme.
var origin = "http://localhost:3000";
var client = new Client(clientId: builder.Configuration["ANYOAUTH_CLIENT_ID"]!,
clientSecret: builder.Configuration["ANYOAUTH_CLIENT_SECRET"]!);
var auth = app.MapGroup("/auth").AllowAnonymous();
auth.MapGet("/login/{provider}", async Task<IResult> (string provider, HttpContext context) => {
if (provider is not ("google" or "github")) return Results.BadRequest();
var login = (await client.StartLogin(new JsonObject {
["provider"] = provider, ["redirectUri"] = origin + "/auth/callback"
}))!;
context.Session.SetString("pendingLogin", login["loginAttempt"]!.ToJsonString());
await context.Session.CommitAsync();
context.Response.StatusCode = 303;
context.Response.Headers.Location = login["url"]!.GetValue<string>();
return Results.Empty;
});
auth.MapGet("/callback", async Task<IResult> (HttpContext context) => {
var attempt = context.Session.GetString("pendingLogin");
if (context.Request.QueryString.HasValue || attempt is null) return Results.BadRequest();
context.Session.Remove("pendingLogin");
await context.Session.CommitAsync();
JsonNode result;
try { result = (await client.CompleteLogin(new JsonObject { ["loginAttempt"] = JsonNode.Parse(attempt) }))!; }
catch (SDKException) { return Results.StatusCode(502); }
if (result["status"]!.GetValue<string>() == "pending") {
context.Session.SetString("pendingLogin", attempt);
return Results.Json(new { status = "pending" }, statusCode: 202);
}
if (result["status"]!.GetValue<string>() != "succeeded") return Results.Redirect("/?auth_error=sign_in_failed");
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, result["profile"]!["subject"]!.GetValue<string>()),
new Claim("profile", result["profile"]!.ToJsonString())
};
await context.SignInAsync("anyoauth", new ClaimsPrincipal(new ClaimsIdentity(claims, "anyoauth")));
context.Response.StatusCode = 303;
context.Response.Headers.Location = "/";
return Results.Empty;
});
auth.MapGet("/profile", IResult (HttpContext context) => {
context.Response.Headers.CacheControl = "no-store";
var profile = context.User.FindFirst("profile")?.Value;
return profile is null ? Results.Unauthorized() : Results.Json(JsonNode.Parse(profile));
});
auth.MapPost("/logout", async Task<IResult> (HttpContext context) => {
if (context.Request.Headers.Origin != origin) return Results.StatusCode(403);
context.Session.Clear();
await context.SignOutAsync("anyoauth");
return Results.NoContent();
});
dotnet add reference /path/to/anyoauth/sdks/dotnet/AnyOAuth.SDK.csprojBackend SDK · application-owned routesCurrent source example
Merge auth_routes() into your Axum app and apply a tower-sessions SessionManagerLayer with your session store. Set SameSite=Lax and Secure on HTTPS. SDK HTTP calls run in spawn_blocking, including client construction and destruction. Callback and session examples
use axum::{extract::{OriginalUri, Path}, http::{HeaderMap, StatusCode},
response::{IntoResponse, Redirect, Response}, routing::{get, post}, Json, Router};
use serde_json::{json, Value};
use tower_sessions::Session;
use anyoauth_sdk::Client;
const ORIGIN: &str = "http://localhost:3000";
fn client() -> Client {
Client::new("https://api.anyoauth.com", &std::env::var("ANYOAUTH_CLIENT_ID").unwrap(),
&std::env::var("ANYOAUTH_CLIENT_SECRET").unwrap()).unwrap()
}
pub fn auth_routes() -> Router {
Router::new()
.route("/auth/login/{provider}", get(login))
.route("/auth/callback", get(callback))
.route("/auth/profile", get(profile))
.route("/auth/logout", post(logout))
}
async fn login(Path(provider): Path<String>, session: Session) -> Result<Response, StatusCode> {
if provider != "google" && provider != "github" { return Err(StatusCode::BAD_REQUEST); }
let login = tokio::task::spawn_blocking(move || client().start_login(&json!({
"provider": provider, "redirectUri": format!("{ORIGIN}/auth/callback")
}))).await.map_err(|_| StatusCode::BAD_GATEWAY)?.map_err(|_| StatusCode::BAD_GATEWAY)?;
session.insert("pendingLogin", &login["loginAttempt"]).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Redirect::to(login["url"].as_str().unwrap()).into_response())
}
async fn callback(OriginalUri(uri): OriginalUri, session: Session) -> Result<Response, StatusCode> {
if uri.query().is_some() { return Err(StatusCode::BAD_REQUEST); }
let attempt: Value = session.remove("pendingLogin").await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?.ok_or(StatusCode::BAD_REQUEST)?;
session.save().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let saved = attempt.clone();
let result = tokio::task::spawn_blocking(move || client().complete_login(&json!({"loginAttempt": attempt})))
.await.map_err(|_| StatusCode::BAD_GATEWAY)?.map_err(|_| StatusCode::BAD_GATEWAY)?;
if result["status"] == "pending" {
session.insert("pendingLogin", saved).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
return Ok((StatusCode::ACCEPTED, Json(json!({"status": "pending"}))).into_response());
}
if result["status"] != "succeeded" { return Ok(Redirect::to("/?auth_error=sign_in_failed").into_response()); }
session.cycle_id().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
session.insert("profile", &result["profile"]).await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Redirect::to("/").into_response())
}
async fn profile(session: Session) -> Result<Response, StatusCode> {
let user: Option<Value> = session.get("profile").await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut response = match user {
Some(user) => Json(user).into_response(),
None => (StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"}))).into_response(),
};
response.headers_mut().insert("cache-control", "no-store".parse().unwrap());
Ok(response)
}
async fn logout(headers: HeaderMap, session: Session) -> Result<StatusCode, StatusCode> {
if headers.get("origin").and_then(|h| h.to_str().ok()) != Some(ORIGIN) { return Err(StatusCode::FORBIDDEN); }
session.flush().await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(StatusCode::NO_CONTENT)
}
cargo add anyoauth-sdkBackend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Add the router scope and controller to your Phoenix app. Configure encrypted Plug sessions (encryption_salt plus signing_salt) or a server-side store. The auth_session pipeline uses the explicit Origin check for logout. Callback and session examples
# lib/my_app_web/router.ex — inside MyAppWeb.Router
pipeline :auth_session do
plug :fetch_session
end
scope "/auth", MyAppWeb do
pipe_through :auth_session
get "/login/:provider", AuthController, :login
get "/callback", AuthController, :callback
get "/profile", AuthController, :profile
post "/logout", AuthController, :logout
end
# lib/my_app_web/controllers/auth_controller.ex
defmodule MyAppWeb.AuthController do
use MyAppWeb, :controller
@origin "http://localhost:3000"
def login(conn, %{"provider" => provider}) when provider in ["google", "github"] do
login = AnyOAuth.start_login(client(), %{"provider" => provider, "redirectUri" => @origin <> "/auth/callback"})
conn |> put_session(:pendingLogin, login["loginAttempt"]) |> redirect(external: login["url"])
end
def login(conn, _), do: send_resp(conn, 400, "Invalid provider")
def callback(conn, _) do
attempt = get_session(conn, :pendingLogin)
if conn.query_string != "" or is_nil(attempt) do
send_resp(conn, 400, "Invalid callback")
else
finish(delete_session(conn, :pendingLogin), attempt)
end
end
defp finish(conn, attempt) do
case AnyOAuth.complete_login(client(), %{"loginAttempt" => attempt}) do
%{"status" => "pending"} -> conn |> put_session(:pendingLogin, attempt) |> put_status(202) |> json(%{status: "pending"})
%{"status" => "succeeded", "profile" => profile} ->
conn |> clear_session() |> configure_session(renew: true) |> put_session(:profile, profile) |> redirect(to: "/")
_ -> redirect(conn, to: "/?auth_error=sign_in_failed")
end
rescue
_ in AnyOAuth.Error -> send_resp(conn, 502, "Sign-in failed")
end
def profile(conn, _) do
conn = put_resp_header(conn, "cache-control", "no-store")
case get_session(conn, :profile) do
nil -> conn |> put_status(401) |> json(%{error: "unauthorized"})
profile -> json(conn, profile)
end
end
def logout(conn, _) do
if get_req_header(conn, "origin") == [@origin] do
conn |> clear_session() |> configure_session(drop: true) |> send_resp(204, "")
else
send_resp(conn, 403, "Invalid origin")
end
end
defp client, do: AnyOAuth.new(System.fetch_env!("ANYOAUTH_CLIENT_ID"), System.fetch_env!("ANYOAUTH_CLIENT_SECRET"))
end
mix.exs: {:anyoauth_sdk, "~> 0.1"}Backend SDK · application-owned routesCurrent source example · published 0.1.0 predates these helpers
Node.js tabs cover Express, Hono, Fastify, Next.js, Astro and plain HTTP. The managed router handles login, callbacks, profile retrieval and session cookies for you. Use your app’s public origin in its configuration.
During /auth/callback, the managed SDK completes login, retrieves the verified
profile, creates the authenticated session, and redirects to / (or your configured
returnTo). You do not need to add a separate profile-fetch call to this router.
If your backend needs to find or create a user at that point, use the
onLogin(profile, request) hook.
The other tabs show Flask, Gin, Laravel, Spring Boot, Rails, ASP.NET Core, Axum and Phoenix routes using their language’s SDK. Each example mounts login, callback, profile and logout endpoints in your existing application. Configure the framework’s session middleware as described above its sample; the SDK verifies the login and your framework stores the application session.
3. Add your login buttons
Call anyoauth.startLogin('google') or anyoauth.startLogin('github') from a button.
Choose your frontend in the tabs; no client secret belongs here:
import * as anyoauth from '@anyoauth/client';
export default function Login() {
return <button onClick={() => anyoauth.startLogin('google')}>
Sign in with Google
</button>;
}
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script setup>
import * as anyoauth from '@anyoauth/client';
</script>
<template>
<button @click="anyoauth.startLogin('google')">Sign in with Google</button>
</template>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<button id="google">Sign in with Google</button>
<script>
import * as anyoauth from '@anyoauth/client';
document.querySelector('#google').addEventListener('click', () => {
anyoauth.startLogin('google');
});
</script>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<button id="google">Sign in with Google</button>
<script type="module">
import * as anyoauth from '/auth-client.js';
document.querySelector('#google').addEventListener('click', () => {
anyoauth.startLogin('google');
});
</script>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script>
import * as anyoauth from '@anyoauth/client';
</script>
<button onclick={() => anyoauth.startLogin('google')}>Sign in with Google</button>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
'use client';
import * as anyoauth from '@anyoauth/client';
export default function Login() {
return <button onClick={() => anyoauth.startLogin('google')}>
Sign in with Google
</button>;
}
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script setup>
import * as anyoauth from '@anyoauth/client';
</script>
<template>
<button @click="anyoauth.startLogin('google')">Sign in with Google</button>
</template>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
startLogin() navigates away from your page. The user signs in through AnyOAuth,
then your backend handles the callback and redirects back to your app. Read the
profile after that return, when your frontend loads again.
4. Show the profile
Call getProfile() when your page or component mounts. It reads the existing
authenticated session through your backend’s /auth/profile route:
- Before login: it returns
null; show your login buttons. - After the successful callback and redirect: it returns the profile; show your signed-in UI.
- If the request fails: show a loading error rather than treating it as signed out.
Yes, if (!profile) is the check for choosing the signed-out UI. Each example below
waits for that check to finish before showing the login buttons:
import { useEffect, useState } from 'react';
import * as anyoauth from '@anyoauth/client';
export default function Profile() {
const [profile, setProfile] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
// Runs on page load, including after the sign-in redirect.
useEffect(() => {
anyoauth.getProfile()
.then(setProfile)
.catch(() => setError('Could not load your session.'))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading your session…</p>;
if (error) return <p role="alert">{error}</p>;
if (!profile) return <>
<button onClick={() => anyoauth.startLogin('google')}>Sign in with Google</button>
<button onClick={() => anyoauth.startLogin('github')}>Sign in with GitHub</button>
</>;
return <p>Signed in as {profile.name ?? profile.username ?? profile.subject}</p>;
}
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script setup>
import { onMounted, ref } from 'vue';
import * as anyoauth from '@anyoauth/client';
const profile = ref(null);
const loading = ref(true);
const error = ref('');
// Runs after hydration, including after the sign-in redirect.
onMounted(async () => {
try { profile.value = await anyoauth.getProfile(); }
catch { error.value = 'Could not load your session.'; }
finally { loading.value = false; }
});
</script>
<template>
<p v-if="loading">Loading your session…</p>
<p v-else-if="error" role="alert">{{ error }}</p>
<div v-else-if="!profile">
<button @click="anyoauth.startLogin('google')">Sign in with Google</button>
<button @click="anyoauth.startLogin('github')">Sign in with GitHub</button>
</div>
<p v-else>Signed in as {{ profile.name ?? profile.username ?? profile.subject }}</p>
</template>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<p id="auth-status">Loading your session…</p>
<div id="login-buttons" hidden>
<button id="google">Sign in with Google</button>
<button id="github">Sign in with GitHub</button>
</div>
<p id="profile" hidden></p>
<script>
import * as anyoauth from '@anyoauth/client';
const status = document.getElementById('auth-status');
const buttons = document.getElementById('login-buttons');
const user = document.getElementById('profile');
document.getElementById('google').addEventListener('click', () => anyoauth.startLogin('google'));
document.getElementById('github').addEventListener('click', () => anyoauth.startLogin('github'));
// Runs on page load, including after the sign-in redirect.
try {
const profile = await anyoauth.getProfile();
status.hidden = true;
if (!profile) {
buttons.hidden = false;
} else {
user.textContent = 'Signed in as ' + (profile.name ?? profile.username ?? profile.subject);
user.hidden = false;
}
} catch {
status.textContent = 'Could not load your session.';
status.setAttribute('role', 'alert');
}
</script>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<p id="auth-status">Loading your session…</p>
<div id="login-buttons" hidden>
<button id="google">Sign in with Google</button>
<button id="github">Sign in with GitHub</button>
</div>
<p id="profile" hidden></p>
<script type="module">
import * as anyoauth from '/auth-client.js';
const status = document.getElementById('auth-status');
const buttons = document.getElementById('login-buttons');
const user = document.getElementById('profile');
document.getElementById('google').addEventListener('click', () => anyoauth.startLogin('google'));
document.getElementById('github').addEventListener('click', () => anyoauth.startLogin('github'));
// Runs on page load, including after the sign-in redirect.
try {
const profile = await anyoauth.getProfile();
status.hidden = true;
if (!profile) {
buttons.hidden = false;
} else {
user.textContent = 'Signed in as ' + (profile.name ?? profile.username ?? profile.subject);
user.hidden = false;
}
} catch {
status.textContent = 'Could not load your session.';
status.setAttribute('role', 'alert');
}
</script>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script>
import { onMount } from 'svelte';
import * as anyoauth from '@anyoauth/client';
let profile = $state(null);
let loading = $state(true);
let error = $state('');
// Runs on page load, including after the sign-in redirect.
onMount(() => {
anyoauth.getProfile()
.then(value => { profile = value; })
.catch(() => { error = 'Could not load your session.'; })
.finally(() => { loading = false; });
});
</script>
{#if loading}
<p>Loading your session…</p>
{:else if error}
<p role="alert">{error}</p>
{:else if !profile}
<button onclick={() => anyoauth.startLogin('google')}>Sign in with Google</button>
<button onclick={() => anyoauth.startLogin('github')}>Sign in with GitHub</button>
{:else}
<p>Signed in as {profile.name ?? profile.username ?? profile.subject}</p>
{/if}
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
'use client';
import { useEffect, useState } from 'react';
import * as anyoauth from '@anyoauth/client';
export default function Profile() {
const [profile, setProfile] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
// Runs on page load, including after the sign-in redirect.
useEffect(() => {
anyoauth.getProfile()
.then(setProfile)
.catch(() => setError('Could not load your session.'))
.finally(() => setLoading(false));
}, []);
if (loading) return <p>Loading your session…</p>;
if (error) return <p role="alert">{error}</p>;
if (!profile) return <>
<button onClick={() => anyoauth.startLogin('google')}>Sign in with Google</button>
<button onClick={() => anyoauth.startLogin('github')}>Sign in with GitHub</button>
</>;
return <p>Signed in as {profile.name ?? profile.username ?? profile.subject}</p>;
}
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
<script setup>
import { onMounted, ref } from 'vue';
import * as anyoauth from '@anyoauth/client';
const profile = ref(null);
const loading = ref(true);
const error = ref('');
// Runs after hydration, including after the sign-in redirect.
onMounted(async () => {
try { profile.value = await anyoauth.getProfile(); }
catch { error.value = 'Could not load your session.'; }
finally { loading.value = false; }
});
</script>
<template>
<p v-if="loading">Loading your session…</p>
<p v-else-if="error" role="alert">{{ error }}</p>
<div v-else-if="!profile">
<button @click="anyoauth.startLogin('google')">Sign in with Google</button>
<button @click="anyoauth.startLogin('github')">Sign in with GitHub</button>
</div>
<p v-else>Signed in as {{ profile.name ?? profile.username ?? profile.subject }}</p>
</template>
npm install @anyoauth/clientBrowser helpers · uses your backend sessionCurrent source example · published 0.1.0 predates these helpers
Use profile.subject as the stable user ID; names and emails may be null.
Serve the frontend and /auth on the same origin, or use a development proxy.
For plain HTML, bundle the browser SDK.
Optional customization
The basic sign-in flow is complete. The following examples are optional, for apps that need protected backend routes, database integration or custom session handling.
Read the profile on your backend
If you add your own protected backend routes, read the authenticated session before
serving their resources. Your frontend check controls what your UI displays; it does
not replace the session check on a protected backend route. Choose your language and
server in the tabs below. Node.js uses auth.getProfile(request); the other frameworks
read the verified profile saved by their callback handler in step 2:
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// Use the auth instance configured in step 2.
app.get('/account', async (req, res) => {
const profile = await auth.getProfile(req);
if (!profile) return res.sendStatus(401);
res.setHeader('Cache-Control', 'no-store');
res.json(profile);
});
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// Use the auth instance configured in step 2.
app.get('/account', async (c) => {
const profile = await auth.getProfile(c.req.raw);
if (!profile) return c.json({ error: 'unauthorized' }, 401);
c.header('Cache-Control', 'no-store');
return c.json(profile);
});
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// Use the auth instance configured in step 2.
app.get('/account', async (request, reply) => {
const profile = await auth.getProfile(request.raw);
if (!profile) return reply.code(401).send({ error: 'unauthorized' });
reply.header('Cache-Control', 'no-store');
return profile;
});
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// app/account/route.js — use your shared, configured auth instance.
export async function GET(request) {
const profile = await auth.getProfile(request);
if (!profile) return Response.json({ error: 'unauthorized' }, { status: 401 });
return Response.json(profile, { headers: { 'Cache-Control': 'no-store' } });
}
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// src/pages/account.json.js — use your shared, configured auth instance.
export const prerender = false;
export async function GET({ request }) {
const profile = await auth.getProfile(request);
if (!profile) return Response.json({ error: 'unauthorized' }, { status: 401 });
return Response.json(profile, { headers: { 'Cache-Control': 'no-store' } });
}
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Use the configured auth instance from step 2 to protect your own application route. For Next.js and Astro, move that configuration into a shared server module.
// Wrap the auth router to add your own protected endpoint.
const router = auth.router();
createServer(async (req, res) => {
if (req.url === '/account') {
const profile = await auth.getProfile(req);
res.statusCode = profile ? 200 : 401;
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-store');
res.end(JSON.stringify(profile ?? { error: 'unauthorized' }));
return;
}
await router(req, res);
}).listen(3000);
npm install @anyoauth/nodeAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the Flask router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
@auth.get("/profile")
def profile():
user = session.get("profile")
response = jsonify(user if user else {"error": "unauthorized"})
response.status_code = 200 if user else 401
response.headers["Cache-Control"] = "no-store"
return response
python -m pip install anyoauth-sdkAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the Gin router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
auth.GET("/profile", func(c *gin.Context) {
c.Header("Cache-Control", "no-store")
profile := sessions.GetString(c.Request.Context(), "profile")
if profile == "" { c.JSON(401, gin.H{"error": "unauthorized"}); return }
c.Data(200, "application/json", []byte(profile))
})
go get github.com/AnyOAuth/anyoauth-goAuthenticated backend sessionCurrent source example
This is the profile handler already included in the Laravel router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
Route::get('profile', function (Request $request) {
$profile = $request->session()->get('profile');
return response()->json($profile ?? ['error' => 'unauthorized'], $profile ? 200 : 401)
->header('Cache-Control', 'no-store');
});
composer require anyoauth/anyoauthAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the Spring Boot router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
@GetMapping("/profile")
public ResponseEntity<String> profile(HttpServletRequest request) {
var session = request.getSession(false);
String profile = session == null ? null : (String) session.getAttribute("profile");
return ResponseEntity.status(profile == null ? 401 : 200).header("Cache-Control", "no-store")
.header("Content-Type", "application/json").body(profile == null ? "{\"error\":\"unauthorized\"}" : profile);
}
Gradle: implementation("com.anyoauth:anyoauth:0.1.0")Authenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the Rails router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
def profile
response.headers['Cache-Control'] = 'no-store'
render json: session[:profile] || {error: 'unauthorized'}, status: session[:profile] ? :ok : :unauthorized
end
gem install anyoauth-sdkAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the ASP.NET Core router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
auth.MapGet("/profile", IResult (HttpContext context) => {
context.Response.Headers.CacheControl = "no-store";
var profile = context.User.FindFirst("profile")?.Value;
return profile is null ? Results.Unauthorized() : Results.Json(JsonNode.Parse(profile));
});
dotnet add reference /path/to/anyoauth/sdks/dotnet/AnyOAuth.SDK.csprojAuthenticated backend sessionCurrent source example
This is the profile handler already included in the Axum router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
async fn profile(session: Session) -> Result<Response, StatusCode> {
let user: Option<Value> = session.get("profile").await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let mut response = match user {
Some(user) => Json(user).into_response(),
None => (StatusCode::UNAUTHORIZED, Json(json!({"error": "unauthorized"}))).into_response(),
};
response.headers_mut().insert("cache-control", "no-store".parse().unwrap());
Ok(response)
}
cargo add anyoauth-sdkAuthenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
This is the profile handler already included in the Phoenix router in step 2. It reads the profile saved in your framework session after a successful callback. Callback and session examples
def profile(conn, _) do
conn = put_resp_header(conn, "cache-control", "no-store")
case get_session(conn, :profile) do
nil -> conn |> put_status(401) |> json(%{error: "unauthorized"})
profile -> json(conn, profile)
end
end
mix.exs: {:anyoauth_sdk, "~> 0.1"}Authenticated backend sessionCurrent source example · published 0.1.0 predates these helpers
Save profiles to your database
If your app stores user records, the managed Node.js flow’s onLogin hook receives
the verified profile before the authenticated session is created:
const auth = createAuth({
...config,
onLogin: async (profile) => {
await users.upsert(profile.subject, profile);
},
});Here config is your backend configuration from step 2, and users is your
application’s database service. Use profile.subject to find or create the user.
With Flask, Gin, Laravel and the other backend frameworks, save the profile in your
callback after completeLogin returns succeeded and before establishing the session.
Customize sessions and routing
- Use your existing sessions: supply the managed SDK’s
sessionadapter, or keep your framework’s session store. - Change paths and redirects: configure
authPath,returnToandsessionMaxAgein the managed router; keep the callback registered exactly. - Own the routes: use
startLoginandcompleteLogindirectly when you need more control over the callback or storage.
See the Custom integration guide for database hooks, session adapters and custom routes.