Guilherme Delgado
04/26/2021, 4:38 PMinstall(Sessions) {
cookie<Session>(SESSION_COOKIE) {
cookie.extensions["SameSite"] = "lax"
transform(SessionTransportTransformerMessageAuthentication(hex(...)))
}
}
install(Authentication) {
session<Session>(SESSION_AUTH) {
challenge { throw AuthenticationException() }
validate { session -> if (session.accessToken.isEmpty()) null else session }
}
oauth(GOOGLE_OAUTH) {
client = httpClient
providerLookup = {
OAuthServerSettings.OAuth2ServerSettings(
name = "google",
authorizeUrl = "<https://accounts.google.com/o/oauth2/auth>",
accessTokenUrl = "<https://www.googleapis.com/oauth2/v3/token>",
requestMethod = <http://HttpMethod.Post|HttpMethod.Post>,
...
)
}
urlProvider = { p -> redirectUrl(Login(p.name), false) }
}
}
webApp/Auth.kt
@KtorExperimentalLocationsAPI
@Location("/login/{provider?}")
class Login(val provider: String = "google")
@KtorExperimentalLocationsAPI
fun Route.login(client: HttpClient) {
authenticate(GOOGLE_OAUTH) {
location<Login> {
param("error") { handle {...} }
handle {
val principal = call.authentication.principal<OAuthAccessTokenResponse>()
if (principal != null) {
val oauth = call.authentication.principal<OAuthAccessTokenResponse.OAuth2>()!!
val response = client.get<UserInfo>("<https://www.googleapis.com/oauth2/v1/userinfo>") {
header(HttpHeaders.Authorization, "Bearer ${oauth.accessToken}")
}
call.sessions.set(Session(response, oauth.accessToken, oauth.refreshToken?: ""))
call.redirect(Home())
} else {
call.respond(status = HttpStatusCode.Unauthorized, "Unauthorized, no token issued")
}
}
}
}
}
webApp/Data.kt
@KtorExperimentalLocationsAPI
@Location("/data")
class Data
@KtorExperimentalLocationsAPI
fun Route.data(client: HttpClient) {
authenticate(SESSION_AUTH) {
get<Data> {
val response = client.get<Info>("<http://localhost:8080>${application.locationToUrl(DataApi())}") {
header(HttpHeaders.Authorization, "Bearer ${call.getSession()?.accessToken}")
...
}
...
}
post<Data> {...}
}
}
api/DataApi.kt
@KtorExperimentalLocationsAPI
@Location("$API_VERSION/data")
class DataApi
@KtorExperimentalLocationsAPI
fun Route.dataApi(client: HttpClient) {
// authenticate(SESSION_AUTH) {
get<DataApi> {
...
val response = client.get<SomeApiData>("<https://www.googleapis.com/>...") {
parameter("key", params.apiKey)
header(HttpHeaders.Authorization, call.request.headers[HttpHeaders.Authorization])
}
...
}
post<DataApi> {...}
// }
}
Big Chungus
04/28/2021, 8:59 AMGuilherme Delgado
04/28/2021, 9:01 AMBig Chungus
04/28/2021, 9:01 AMGuilherme Delgado
04/28/2021, 9:02 AMBig Chungus
04/28/2021, 9:02 AM