简体   繁体   中英

ruby on rails rest api with ruby for login page

我想在 Android 移动应用程序中使用 ruby​​ on rails 后端为登录页面实现一个 ruby​​ api,因为我是新手,请帮助我完成我的任务,请告诉我实现 API 的方法提前致谢

Firstly there is no point to put -ve mark on this question, he is new in ruby, we can help him.

step 1: To make an api you have to deal with controllers and models there is no view for an api.

step 2: since you are new in rails read about rails routing, let me give you a brief idea, the router simply decide if a request comes on a url which controller and which action should trigger.

step 3: Once your action in the controller is trigger write your logic their or call a method in a model.

Step 4: Once you have done CRUD operation from the model return the response to the controller.

step 5 : Depending on the format weather the client want a xml or json encode it in xml/json and render it from the controller.

dats it :) hope it helps you

I don't want to quote the great thinkers, but the answer is: It depends!

You can either go it simple and use BASIC AUTHENTICATION for your app, or you can go the more-complex road of using other technologies, such as JWT (Json Web Token) or OAuth or whatnot...

I assume you are at just starting web development so I would suggest you start simple by using BASIC AUTH (over some https connection).

For the Rails part you just include the following directive in the controller you want protected:

http_basic_authenticate_with name: "username", password: "secret", except: :index

So a simple controller would look like this:

class PostsController < ApplicationController
  http_basic_authenticate_with name: "dhh", password: "secret", except:  :index

  def index
    render plain: "Everyone can see me!"
  end

  def edit
    render plain: "I'm only accessible if you know the password"
  end
end

This example is directly copied from here: http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html

On the client side you need to provide the basic authentication credentials in the HTTP header like this:

"Authorization: Basic dXNlcm5hbWU6c2VjcmV0"

using BASE64 to encode username and password like this (in javascript):

encoded = btoa(username + ":" + password); 

The basics are covered here: https://en.wikipedia.org/wiki/Basic_access_authentication

From there you can go and implement a simple username/password screen and provide the so generated header in all subsequent calls.

I hope this gets you started into the right direction. Don't shy away from asking and keep learning!

Eventually you may want to move on to more sophisticated access-token based authentication methods.

Best regards, Steviee

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