graphqlelixirphoenix-frameworkabsinthe

Elixir Phoenix Absinthe GraphQL API authentication in both web and mobile app's


I'm working on an Absinthe GraphQL API for my app. I'm still learning the procedure(so please go easy on me).

I've a Absinthe/GraphQL MyAppWeb.schema.ex file in which I use for my queries and mutations. My question is how do I use this API for authenticating the user on both Mobile and Web app?

How do set a cookie(httpOnly & secure) in my web app and access/refresh tokens in a single Absinthe API to serve my website and mobile app. Basically what I'm trying to learn is how do I authenticate the user based on specific platform.

If my question sounds bit confusing, I would be happy to provide more information related to my question. I would really be grateful if someone could explain the procedure, I've been very stuck on this for a while.


Solution

  • I would avoid using authentication mechanisms provided by absinthe(if there are any). Depending on what front-end you are using, I would go with JSON API authentication. The flow on server goes the following way:

    1. Create a endpoint for login that will receive a user and password and will return a refresh token.
    2. Create a endpoint for exchanging refresh token for access token.
    3. Use a library like guardian to generate your refresh/access tokens.
    4. Create a phoenix plug for authentication that will check your tokens, guardian has some built-in plugs for this.

    Now on device you have to implement:

    1. Ability to save refresh and access token on device.
    2. Have a global handler for injecting access token on authorized requests.
    3. Have a global handler for case when access token is expired. (you usually check if your request returns Unauthorized, then you should request a new access token from the server using your refresh token)

    This seems like a crude implementation, however I would advise in implementing your system instead of using a black box library that you have no idea how it works under the hood.