DEV Community


Flutter - securing http requests

ahmaddarwesh profile image Ahmad Darwesh ・2 min read

What is CSRF token?

A CSRF token is a unique, secret, unpredictable value that is generated by the server-side application and transmitted to the client in such a way that it is included in a subsequent HTTP request made by the client. When the later request is made, the server-side application validates that the request includes the expected token and rejects the request if the token is missing or invalid.

CSRF tokens can prevent CSRF attacks by making it impossible for an attacker to construct a fully valid HTTP request suitable for feeding to a victim user. Since the attacker cannot determine or predict the value of a user's CSRF token, they cannot construct a request with all the parameters that are necessary for the application to honor the request.

How I can generate csrf-tokens in my Flutter App?

1- Firstly let us use new dependency in pubspec.yaml file :
dart_jsonwebtoken: ^2.1.0

2- Now we need to generate valid token to send it with our request

String generateToken() {  
  var jwt = JWT(  
      "exp": 10)).millisecondsSinceEpoch,  
      "custom_data": "some data",
  //secret key is our secret passphrase 
  var token = jwt.sign(SecretKey(SECRIT_KEY));  
  return token;  
Enter fullscreen mode Exit fullscreen mode

Now this token is valid for 10 seconds then will be expired.

Server Side

When a CSRF token is generated, it should be stored server-side within the user's session data. When a subsequent request is received that requires validation, the server-side application should verify that the request includes a token which matches the value that was stored in the user's session.

more info about csrf-tokens:

Discussion (0)

Forem Open with the Forem app