http://localhost:3000/api/v1/person_all.json
sorgusu yapan herkeze bu verileri gönderir. Sadece B uygulamasına ait olmasını istersem yanı verilerimi private olarak göndermek istersem aradaki güvenliği access_token ile sağlayabilirim.
A uygulamasına ApiKey Modeli ekleyelim:
$ rails g model api_key access_token
$ rake db:migrate
Model kalsörü altındaki api_key.rb dosyasını aşağıdaki şekilde güncelleyelim.
class ApiKey < ActiveRecord::Base
before_create :generate_access_token
private
def generate_access_token
begin
self.access_token=SecureRandom.hex
end while self.class.exists?(access_token: access_token)
end
end
rails c ile rails consoluna gidip;
> ApiKey.create!
yazdığımızda access_tokenımız oluştu
Geleleim A uygulamasındaki Controllers/persons_controller.rb dosyasına;
class PersonsController < ActionController::Base
before_filter :restrict_access
def person_all
render json: Person.all
.
end
.
.
private
def restrict_access
api_key=ApiKey.find_by_access_token(params[:access_token])
head :unauthorized unless api_key
end
Test edelim:
http://localhost:3000/api/v1/person_all.json yazdığımızda boş bir sayfayla karşılaşıyoruz,
http://localhost:3000/api/v1/person_all?access_token=494fb7c06a14f82d41e83962f89ed8f0
bu şekilde istek yaptıgımızda istediğimiz verileri alıyoruz. access_token kodunu bilmeyen bu verilere erişemez :)