Work with authenticity token? Or disable it?

2019-08-12 20:42发布

问题:

My mini-web-appliance will submit data samples to a RoR app, which will add them to a MySQL table.

I figured out how to form the POST data packet, but what I don't get is how to avoid the authenticity-token problem.

Is there a way for my little dumb client to grab the right token and send it back? (I'm guessing not, or it wouldn't be much of a security feature).

This is not a highly security-sensitive application, so should I just tell this page to ignore the authentity-token altogether?

It will hopefully be authenticated by the fact that each client (web appliance) logs in with a unique user ID and password, so it would be protected by the session ID.

If I'm using "loose" language, please feel free to correct me. I'm new to deploying sites.

Keb'm

回答1:

If each client is authenticated then it's ok to disable the authenticity token, that said you should only disable it for that one action.

skip_before_filter :verify_authenticity_token, :only => :create


回答2:

If each client is authenticated then it's ok to disable the authenticity token

This is only true if you're using another authentication mechanism than http cookies. Because you've mentioned 'session_id', i assume this is not the case.

With a standard rails session_id cookie, the user_id stored in a session and this action being accessible by a webbrowser, it will be exposed to csrf attacks.

The best strategy for api's is implementing a custom authentication mechanism, some sort of authentication token, which is send with every http header.

Then either change the csrf protection to null_session or if you are less paranoid disable csrf protection entirely for your api request as described here

If you still want to stick with cookie based authentication for your api, you should set the csrf authenitcation token with the first GET request into an extra cookie. Then you read this cookie and send it's token as 'X-CSRF-Token' header. Rails will check for this header in the protect_from_forgery method and as cookies cannot be read by 3d parties an attacker will not be able to forge this request.

#application_controller.rb
protect_from_forgery with: :exception
after_action :set_csrf

def set_csrf
 cookies['X-CSRF-Token'] = form_authenticity_token if protect_against_forgery?
end

# request session and x-csrf-toke
# the cookies will be stored into cookie.txt
curl -c cookie.txt http://example.com

#curl post command
curl -H "X-CSRF-Token: <token>" -b cookie.txt -d '{"item":{"title":"test"}}' "http://example.com/items.json"

See :verified_request? method to see how rails check for request forgery.