Today tutorial is about how to secure login using tokens. Basically how to confirm login using CSRF token. So imagine we have 2 web pages in our site, one is for client and other one is for server. ( index.php -> Client | server.php -> server )
First of all go to index.php ( Client side ). Start a session and create cookie to store session id. ( This cookie is later use to validate session id with server side )
So, if we run our client side web page now. we have cookie named called "session id" and it contains "ID" of the current session of client.
After that we need to generate CSRF token and store it in the server side (server.php).
So, now we successfully generate CSRF token in server side. The next thing we should do is, we have to request to the server when client page is loaded and get the CSRF token stored in the server side, So to do that we have to use AJAX along with the javascript. ( Using Ajax we can send data to sever in background )
So to do those stuffs, i create a javascript function called " loadDOC ". What this function do is, when the page is loaded it sends request to server side and grab CSRF token and store it in the " hidden " DOM field in the client side.
loadDOC function
Calling loadDOC function in client side
After that we need to create hidden DOM field to store the CSRF token value. This value should send to server side again when user click to Login Button.
When the time user click on this Log In button, all the values in the form will send to the server.php ( our sever ). The next thing we should do is validate those received values in the server side.
What this loginvalidate() function do is, it validate the login credentials coming form the client side. The fist two check the username and password are correct. Third augment checks CSRF token coming form the client side is match with server side CSRF. Fourth one checks user session id ( stored inside cookie called "session id" ) is equal to server's session id. If all those arguments returns true, Server will prompt Login success alert box.
[ Article By : Nisal Priyanka aka COD-HORA ]
No comments:
Post a Comment