Ktor 1.6.7 Help

OAuth

OAuth is an open standard for access delegation. OAuth can be used to authorize users of your application by using external providers, such as Google, Facebook, Twitter, and so on.

The oauth provider supports the authorization code flow. You can configure OAuth parameters in one place, and Ktor will automatically make a request to a specified authorization server with the necessary parameters.

Add dependencies

To enable OAuth support, you need to include the ktor-auth artifact in the build script:

implementation "io.ktor:ktor-auth:$ktor_version"
implementation("io.ktor:ktor-auth:$ktor_version")
<dependency> <groupId>io.ktor</groupId> <artifactId>ktor-auth</artifactId> <version>${ktor_version}</version> </dependency>

OAuth authorization flow

The OAuth authorization flow in a Ktor application might look as follows:

  1. A user opens a login page in a Ktor application.

  2. Ktor makes an automatic redirect to the authorization page for a specific provider and passes the necessary parameters:

    • a client ID used to access APIs of the selected provider;

    • a callback or redirect URL specifying a Ktor application page that will be opened after authorization is completed;

    • scopes of third-party resources required for a Ktor application;

    • a grant type used to get an access token (Authorization Code in our case).

  3. The authorization page shows a consent screen with the level of permissions required for a Ktor application. These permissions depend on scopes passed in step 2.

  4. If a user approves the requested permissions, the authorization server redirects back to a redirect URL and sends the authorization code.

  5. Ktor makes one more automatic request to the specified access token URL and passes the following parameters:

    • an authorization code;

    • a client ID and client secret.

    The authorization server returns an access token.

  6. A client can now use a token to make a request to the required service of the selected provider. In most cases, a token will be sent in the Authorization header using the Bearer schema.

  7. A service validates a token, uses its scope for authorization, and returns the requested data.

Install OAuth

To install the oauth authentication provider, call the oauth function inside the install block:

install(Authentication) { oauth { // Configure oauth authentication } }

You can optionally specify a provider name.

Configure OAuth

This section demonstrates how to configure the oauth provider for authorizing users of your application using Google. You can find the complete runnable example here: auth-oauth-google.

Step 1: Create the HTTP client

Before configuring the oauth provider, you need to initialize the HttpClient that will be used by the server to make requests to the OAuth server. You can learn how to add the HttpClient dependencies and configure it from Client overview.

val httpClient = HttpClient(CIO) { install(JsonFeature) { serializer = KotlinxSerializer() } }

Note that the client also has the Json plugin installed. This is required to deserialize received JSON data after a request to API.

Step 2: Configure the OAuth provider

The code snippet below shows how to create and configure the oauth provider with the auth-oauth-google name.

install(Authentication) { oauth("auth-oauth-google") { urlProvider = { "http://localhost:8080/callback" } providerLookup = { OAuthServerSettings.OAuth2ServerSettings( name = "google", authorizeUrl = "https://accounts.google.com/o/oauth2/auth", accessTokenUrl = "https://accounts.google.com/o/oauth2/token", requestMethod = HttpMethod.Post, clientId = System.getenv("GOOGLE_CLIENT_ID"), clientSecret = System.getenv("GOOGLE_CLIENT_SECRET"), defaultScopes = listOf("https://www.googleapis.com/auth/userinfo.profile") ) } client = httpClient } }
  • The urlProvider specifies a redirect route that will be opened when authorization is completed.

  • providerLookup allows you to specify OAuth settings for a required provider. These settings allow Ktor to make automatic requests to the OAuth server.

  • The client property specifies the HttpClient used by Ktor to make requests to the OAuth server.

Step 3: Add a login route

After configuring the oauth provider, you need to create a protected login route inside the authenticate function that accepts the name of the oauth provider. When Ktor receives a request to this route, it will be automatically redirected to authorizeUrl defined in providerLookup.

routing { authenticate("auth-oauth-google") { get("/login") { // Redirects to 'authorizeUrl' automatically } } }

A user will see the authorization page with the level of permissions required for a Ktor application. These permissions depend on defaultScopes specified in providerLookup.

Step 4: Add a redirect route

Apart from the login route, you need to create a redirect route that will be invoked after authorization is completed. The address of this route was specified using the urlProvider property.

Inside this route you can retrieve the OAuthAccessTokenResponse object using the call.principal function. OAuthAccessTokenResponse allows you to access a token and other parameters returned by the OAuth server.

routing { authenticate("auth-oauth-google") { get("/login") { // Redirects to 'authorizeUrl' automatically } get("/callback") { val principal: OAuthAccessTokenResponse.OAuth2? = call.principal() call.sessions.set(UserSession(principal?.accessToken.toString())) call.respondRedirect("/hello") } } }

In this example, the following actions are performed after receiving a token:

  • a token is saved to a cookie session, whose content can be accessed inside other routes;

  • a user is redirected to the next route where a request to Google API is made.

Step 5: Make a request to API

After receiving a token inside the redirect route and saving it to a session, you can make the request to external APIs using this token. The code snippet below shows how to use the HttpClient to make such a request and get a user's information by sending this token in the Authorization header.

get("/hello") { val userSession: UserSession? = call.sessions.get<UserSession>() if (userSession != null) { val userInfo: UserInfo = httpClient.get("https://www.googleapis.com/oauth2/v2/userinfo") { headers { append(HttpHeaders.Authorization, "Bearer ${userSession.token}") } } call.respondText("Hello, ${userInfo.name}!") } else { call.respondRedirect("/") } }

You can find the complete runnable example here: auth-oauth-google.

Last modified: 03 August 2021