I have a rails api only application [config.api_only = true]
in which I enable the cookies through these following lines:
in application.rb:
config.middleware.insert_after ActionDispatch::ParamsParser, ActionDispatch::Cookies
config.middleware.insert_after ActionDispatch::ParamsParser, ActionDispatch::Session::CookieStore
in application_controller.rb
include ActionController::Helpers
include ActionController::Cookies
I also added secret_token.rb as follows:
Rails.application.config.secret_token = 'token'
in my controller, I am trying to store the session like this:
def index
#other codes
session[:userid] = useridstring
render :text => session[:userid]
end
Note: however, after executing this in chrome, I am examining the cookie and none is set...
then in the same controller, but in another action, I am trying to read the session like this:
def readsession
userId = session[:userid]
render :text => userId
end
and nothing is rendered.. :(
Is there anything I missed?
I tried following the answer here which suggest that I set config.api_only = false
, however the result is the same (I have no cookie set, and when read in another controller, session is still empty
Sorry that it is such a basic question (or initial configuration matter), I am still very new in ruby and rails..
Rails will create a new record in your sessions table with a random session ID (say, 09497d46978bf6f32265fefb5cc52264 ). It'll store {current_user_id: 1} (Base64-encoded) in the data attribute of that record. And it'll return the generated session ID, 09497d46978bf6f32265fefb5cc52264 , to the browser using Set-Cookie .
The session is only available in the controller and the view and can use one of a number of different storage mechanisms: ActionDispatch::Session::CookieStore - Stores everything on the client. ActionDispatch::Session::CacheStore - Stores the data in the Rails cache.
Cookies, Sessions and Flashes are three special objects that Rails gives you in which each behave a lot like hashes. They are used to persist data between requests, whether until just the next request, until the browser is closed, or until a specified expiration has been reached.
REST stands for REpresentational State Transfer and describes resources (in our case URLs) on which we can perform actions. CRUD , which stands for Create, Read, Update, Delete, are the actions that we perform. Although, in Rails, REST and CRUD are bestest buddies, the two can work fine on their own.
Since an API is always client independent, so it's best to use a token for authentication.
Here's how:
token
in users
table.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With