LARAVEL - Get a CSRF token to connect to a user using my API

advertisements

I am trying to login a user using laravel and the api I made for it, I made the post code with the email and password but it returns me a token mismatch error,i guess that's because I don't pass any csrf and my doubt is how to get it.

If I understood correctly I just need to do a GET on my main domain and grab the csrf from there, from the cookies (?).

I found this, but classes are deprecated and Ii dont know how to implement with my updated code:

Found:

    CookieStore cookieStore = httpClient.getCookieStore();
List <Cookie> cookies =  cookieStore.getCookies();
for (Cookie cookie: cookies) {
    if (cookie.getName().equals("XSRF-TOKEN")) {
        CSRFTOKEN = cookie.getValue();
    }
}

Need to implement the grab csrf part on my code:

url = new URL(AppConfig.BaseURL);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");

        // CookieStore cookieStore = connection.getCookieStore();
        // List<HttpCookie> cookies =  cookieStore.getCookies();
        // for (Cookie cookie: cookies) {
        //    if (cookie.getName().equals("XSRF-TOKEN")) {
        //        CSRFTOKEN = cookie.getValue();
        //    }
        // }

The commented is either wrong or deprecated but can't figure out how to solve it !


In every page request we pass csrf token as a meta value in the head

<meta name="csrf-token" content="{{ csrf_token() }}" />

After that we simply use this meta value in javascript to set the X-CSRF-TOKEN header

var request = new XMLHttpRequest();
request.open('POST', url);
request.setRequestHeader("X-CSRF-TOKEN", $('meta[name="csrf-token"]').attr('content'));
request.send(data);

Hope this helps for you


Edit: The header you are populating is probably wrong. For us it is X-CSRF-TOKEN instead of XSRF-TOKEN