Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

javascript - Single Page Application and CSRF Token

I need to use a Single Page Application (React, Ember, Angular, I don't care) with Rails CSRF protection mechanism.

I'm wondering if I need to create a token evey time in the ApplicationController like this:

class ApplicationController < ActionController::Base

  after_action :set_csrf_cookie

  def set_csrf_cookie
    cookies["X-CSRF-Token"] = form_authenticity_token
  end

end

or I can just create a token once.

Per session or per (non-GET) request?

I think the token is still valid until the session is valid, right?

CLARIFY:

I see Rails default application (server-rendered pages) update csrf-token each time I navigate a page. So every time it changes.

So in my situation if I create a new token for each after_action the previous CSRF-Token is still good for that session. So, how to invalidate the previous token? I have to?

Because only if I invalidate it makes sense, right?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Client side (SPA)

You only need to grab the CSRF token once per session. You can hold onto it in the browser and send it on every (non-GET) request.

Rails will appear to generate a new CSRF token on every request, but it will accept any generated token from that session. In reality, it is just masking a single token using a one-time pad per request, in order to protect against SSL BREACH attack. More details at https://stackoverflow.com/a/49783739/2016618. You don't need to track/store these tokens.

Server side

I strongly suggest using Rails's protect_from_forgery directive rather than encoding the CSRF token in a header yourself. It will generate a different masked token per request.

You can certainly reproduce this yourself with not that much code, but I don't see why you'd need to.

Do you need CSRF protection with an API?

Yes! If you are authenticating with a cookie, you need CSRF protection. This is because cookies are sent with every request, so a malicious website could send a POST request to your site and perform requests on behalf of a logged in user. The CSRF token prevents this, because the malicious site won't know the CSRF token.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...