hassox / phoenix_guardian

A demo application showing usage of guardian and ueberauth
MIT License
299 stars 70 forks source link

Simulate callback for JSON API requests #25

Open Lazarus404 opened 8 years ago

Lazarus404 commented 8 years ago

I need to forgo the request/callback process in order to login and register using JSON requests. However, there doesn't seem to be a way to populate the Auth object. Is there a general flow for achieving this?

Thanks, Lee

Lazarus404 commented 8 years ago

So, I think I've cracked this. It might be good to add a snippet to the README for anyone else who wants to do this. Firstly, you MUST specify the path to the callback (which is also the request) in the config. This caught me out for a couple of hours. Secondly, for my login function, I'm currently using (but it will change):

def login(conn, params, current_user, _claims) do
  conn = Ueberauth.Strategy.run_callback(conn, Ueberauth.Strategy.Identity)
  %Plug.Conn{assigns: %{ueberauth_auth: auth}} = conn
  case UserFromAuth.get(auth, current_user, Repo) do
    {:ok, user} ->
      conn = Guardian.Plug.api_sign_in(conn, user, :api)
      jwt = Guardian.Plug.current_token(conn)
      conn
      |> put_resp_header("authorization", "Bearer #{jwt}")
      |> json %{user: user, jwt: jwt}
    {:error, reason} ->
      conn
      |> put_status(422)
      |> json %{error: "Could not authenticate. Error: #{reason}"}
  end
end
hassox commented 8 years ago

hey @Lazarus404. The ueberauth_identity library doesn't require the request part and just accepts the direct post. There shouldn't be a reason that you need to run the callback directly. Is there a reason you can't just post the params directly to the callback url?

luckyraul commented 8 years ago

@hassox near the same problem. I have implemented my app base on this repo and now I am trying to create an api with a json controller which accepts email and password as a parametrs and should respond with a token.

If I am sending data to /auth/indentity/callback - I need CSRF token at least. Which is not good for api. Can you help with an actual sample ?