oauth2Session

Creates a typed OAuth 2.0 authorization-code flow with session-backed route authentication.

The OAuth callback stores a session value and principal. Protected routes use OAuth2SessionFlow.session with authenticateWith, not the OAuth scheme directly.

Routes installed at a callback path and OAuthFlowConfigBase.loginPath redirect unauthenticated requests to the OAuth provider.

Routes protected with authenticateWith using OAuth2SessionFlow.session respond with 401 Unauthorized when no valid session exists. They do not automatically start the OAuth flow; direct users to OAuthFlowConfigBase.loginPath to sign in, or customize TypedSessionAuthConfig.onUnauthorized to redirect there.

Type parameters are declared as <P, S> where P is the route principal type and S is the stored session type.

data class User(val id: String)
data class UserSession(val accessToken: String)

val googleAuth = oauth2Session<User, UserSession>("google") {
client = HttpClient()
settings = OAuthServerSettings.OAuth2ServerSettings(
name = "google",
authorizeUrl = "https://accounts.google.com/o/oauth2/auth",
accessTokenUrl = "https://oauth2.googleapis.com/token",
clientId = "...",
clientSecret = "...",
requestMethod = HttpMethod.Post,
)
loginPath = "/login"
callback("/callback") {
call.respondRedirect("/home")
}
sessions {
sessionCreator = { token -> UserSession(token.accessToken) }
validate { session -> User(id = lookupUserId(session.accessToken)) }
}
}

routing {
install(googleAuth)
authenticateWith(googleAuth.session) {
get("/profile") {
call.respondText(call.principal.id)
}
}
}

Report a problem

Parameters

name

name that identifies the OAuth flow.

configure

configures the OAuth provider, callback route, and session authentication.

Type Parameters

P

the principal type available in protected route handlers.

S

the session type stored by the Sessions plugin.