简体   繁体   中英

Rails API for fb login with Ionic

I want to build a rails api for fb login using, ionic framework. Till now I've successfully created a web base application and it's successfully authenticating with Facebook.

Now I want to do the same but with ionic based app.

Questions?

  1. Is this possible to write a rails api using omniauth and using the fb authentication api with ionic.
  2. If it's(1) is possible than what kind of json request is to be made or returned.

Couldn't find anything over the web about it, nor any github project of rails with ionic (fb login).

My Current code:

Controller:

  class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url


  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end
end

Model:

class User < ActiveRecord::Base
  def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_initialize do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

Initializers:

OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, "123", "abc"
end

I'm not sure if its possible... but I think you shouldn't use the same logic.

Rails facebook omniauth flow is session based while Ionic apps are mostly "access token" based ie you expose an Rails API with authentication.

Also, in Ionic you have some advantages: you can access to native Facebook Login using Ionic Native Facebook Connect Plugin which provides a better user experience to users who has installed Facebook.

I had the same problem and what I finishing doing was first understand how does authentication works for single page apps. For this, I recommend you to read "Authentication for single single page apps" .

My final solution looks like this:

在此输入图像描述

The tools I used:

You can see an example rails app for retrieving a valid JWT token given a valid facebook auth token at https://github.com/muZk/rails5-api-jwt-facebook-auth

After creating the backend, the Ionic part should be something like this:

this.fb.login(['public_profile', 'user_friends', 'email'])
  .then((res: FacebookLoginResponse) => post('your-rails-backend.com/api/auth/facebook', { access_token: FacebookLoginResponse.accessToken }))
  .then(res => console.log('This is your JWT for your rails API:', res.accessToken))

I know this is not a copy-paste solution but I hope I have helped you a bit with your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM