I am having trouble understanding how to convert a...
# http4k
a
I am having trouble understanding how to convert an access token and csrf to a user object. Here is what I have so far:
Copy code
fun contextFn(request: Request): Principal {
  val cookie = request.header("Cookie")
  val map =
    cookie?.split(";")?.associate {
      val (first, second) = it.split("=").map { s -> s.replace("\"", "") }
      first.trim() to second.trim()
    }
      ?: emptyMap()
  // TODO: take the GoogleCsrf and GoogleAccessToken and create a principal based on that
  val accessToken = map["GoogleAccessToken"]
  val csrf = map["GoogleCsrf"]
  return GoogleUser(UUID.randomUUID())
}
Is there something that I should read up on or what am I missing?
d
First up - you can use request.cookie("name") to get a parsed cookie.
👀 1
What's the context here - are you doing oauth?
a
Yes, I am doing oauth with google as the provider, and I would like to use the cookie that is set in the browser to set a context for my graphql endpoint 🙂
If no cookie is set, then obviously there is nothing to do, and I want to set the principal as a
AnonymousUser
or something to that accord
d
Have you looked at the example ? https://github.com/http4k/examples/tree/master/oauth Are you currently trying to implement the OauthPersistence?
a
I suspect I am asking the wrong question, or at least I am asking it in the wrong place. The core of what I’m trying to do is to take that access token, decode it and convert it into a
User
object of sorts and use that as a context for my GraphQL endpoint. I suspect I might need to use this maybe: https://developers.google.com/identity/sign-in/web/backend-auth
d
Aha - ok. Sorry. What you want is probably a request context. So you have a filter which will decode the cookie for use in a handler later in the chain? https://www.http4k.org/guide/howto/attach_context_to_a_request/
👍 1
a
I don’t think I actually need that tbh. This is how I have thought so far:
Copy code
fun contextFn(request: Request): Principal {
  val accessToken = request.cookie("GoogleAccessToken")
  val csrf = request.cookie("GoogleCsrf")

  // TODO decode the access token
  return GoogleUser(UUID.randomUUID())
}

fun DataFetchingEnvironment.getPrincipal(): Principal? =
  graphQlContext.get<Principal>("principal")
and the
contextFn
is supplied like so:
Copy code
"/graphql" bind graphQL(BaseHandler, ::contextFn, baseExceptionHandler)
So when I am in a query handler, I just need to do this:
Copy code
fun hello(env: DataFetchingEnvironment) = "Hello ${env.getPrincipal() ?: "anonymous user"}"
d
That looks like it will work. But you're right - if want help with a Google java API specifically then that's not something I can help with. 🙃
The access token itself will just be an encoded JWT. But you will alao want to verify that it's legit