/
OAuthProcedure.kt
167 lines (147 loc) · 5.78 KB
/
OAuthProcedure.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
/*
* Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.auth
import io.ktor.client.*
import io.ktor.server.application.*
import org.slf4j.*
import java.io.*
private val Logger: Logger = LoggerFactory.getLogger("io.ktor.auth.oauth")
/**
* An OAuth provider key.
*/
public val OAuthKey: Any = "OAuth"
/**
* An `OAuth` [Authentication] provider.
*
* @see [oauth]
*/
public class OAuthAuthenticationProvider internal constructor(config: Config) : AuthenticationProvider(config) {
internal val client: HttpClient = config.client
internal val providerLookup: ApplicationCall.() -> OAuthServerSettings? = config.providerLookup
internal val urlProvider: ApplicationCall.(OAuthServerSettings) -> String = config.urlProvider
override suspend fun onAuthenticate(context: AuthenticationContext) {
oauth1a(name, context)
oauth2(name, context)
}
/**
* A configuration for the [oauth] authentication provider.
*/
public class Config internal constructor(name: String?) : AuthenticationProvider.Config(name) {
/**
* An HTTP client instance used to make requests to the OAuth server.
*/
public lateinit var client: HttpClient
/**
* A lookup function to find OAuth server settings for the particular call.
*/
public lateinit var providerLookup: ApplicationCall.() -> OAuthServerSettings?
/**
* Specifies a redirect route that is opened when authorization is completed.
*/
public lateinit var urlProvider: ApplicationCall.(OAuthServerSettings) -> String
internal fun build() = OAuthAuthenticationProvider(this)
}
}
/**
* Installs the OAuth [Authentication] provider.
* OAuth can be used to authorize users of your application by using external providers,
* such as Google, Facebook, Twitter, and so on.
* To learn how to configure it, see [OAuth](https://ktor.io/docs/oauth.html).
*/
public fun AuthenticationConfig.oauth(
name: String? = null,
configure: OAuthAuthenticationProvider.Config.() -> Unit
) {
val provider = OAuthAuthenticationProvider.Config(name).apply(configure).build()
register(provider)
}
internal suspend fun OAuthAuthenticationProvider.oauth2(authProviderName: String?, context: AuthenticationContext) {
val call = context.call
val provider = call.providerLookup()
if (provider !is OAuthServerSettings.OAuth2ServerSettings) return
val token = call.oauth2HandleCallback()
val callbackRedirectUrl = call.urlProvider(provider)
val cause: AuthenticationFailedCause? = if (token == null) {
AuthenticationFailedCause.NoCredentials
} else {
oauth2RequestToken(authProviderName, provider, callbackRedirectUrl, token, context)
}
cause ?: return
@Suppress("NAME_SHADOWING")
context.challenge(OAuthKey, cause) { challenge, call ->
val state = provider.nonceManager.newNonce()
provider.onStateCreated(call, state)
call.redirectAuthenticateOAuth2(
provider,
callbackRedirectUrl,
state = state,
scopes = provider.defaultScopes,
extraParameters = provider.extraAuthParameters,
interceptor = provider.authorizeUrlInterceptor
)
challenge.complete()
}
}
internal suspend fun OAuthAuthenticationProvider.oauth1a(authProviderName: String?, context: AuthenticationContext) {
val call = context.call
val provider = call.providerLookup()
if (provider !is OAuthServerSettings.OAuth1aServerSettings) return
val token = call.oauth1aHandleCallback()
val cause: AuthenticationFailedCause? = if (token == null) {
AuthenticationFailedCause.NoCredentials
} else {
oauth1RequestToken(authProviderName, provider, token, context)
}
if (cause != null) {
@Suppress("NAME_SHADOWING")
context.challenge(OAuthKey, cause) { challenge, call ->
try {
val t = simpleOAuth1aStep1(client, provider, call.urlProvider(provider))
call.redirectAuthenticateOAuth1a(provider, t)
challenge.complete()
} catch (ioe: IOException) {
context.error(OAuthKey, AuthenticationFailedCause.Error(ioe.message ?: "IOException"))
}
}
}
}
private suspend fun OAuthAuthenticationProvider.oauth1RequestToken(
authProviderName: String?,
provider: OAuthServerSettings.OAuth1aServerSettings,
token: OAuthCallback.TokenPair,
context: AuthenticationContext
) = try {
val accessToken = requestOAuth1aAccessToken(client, provider, token)
context.principal(authProviderName, accessToken)
null
} catch (cause: OAuth1aException.MissingTokenException) {
AuthenticationFailedCause.InvalidCredentials
} catch (cause: Throwable) {
context.error(
OAuthKey,
AuthenticationFailedCause.Error("OAuth1a failed to get OAuth1 access token")
)
null
}
private suspend fun OAuthAuthenticationProvider.oauth2RequestToken(
authProviderName: String?,
provider: OAuthServerSettings.OAuth2ServerSettings,
callbackRedirectUrl: String,
token: OAuthCallback.TokenSingle,
context: AuthenticationContext
) = try {
val accessToken = oauth2RequestAccessToken(client, provider, callbackRedirectUrl, token)
context.principal(authProviderName, accessToken)
null
} catch (cause: OAuth2Exception.InvalidGrant) {
Logger.trace("OAuth invalid grant reported: {}", cause.message)
AuthenticationFailedCause.InvalidCredentials
} catch (cause: Throwable) {
Logger.trace("OAuth2 request access token failed", cause)
context.error(
OAuthKey,
AuthenticationFailedCause.Error("Failed to request OAuth2 access token due to $cause")
)
null
}