Send authenticated AJAX request to Phoenix API(secured by auth plug) Phoenix front end application

HI, I am developing a phoenix front end application where i am required to send ajax request to phoenix api but i am finding it difficult- how to send the request along with the auth token - As the api endpoint is protected by auth plug.

so what is the best way to send ajax request when i am logged in to the browser.

I tried writing a custom plug which will first check if the request is coming via api -> then i am parsing from conn
if the request is from browser then i am fetching the user from sesssion and validating it
but the issue is it is showing invalid token
so i tried to add the same jwt token in the session, but the response is same as it is showing invalid token.
I am using browser auth method as per phx_gen_auth and using methods like that one.

How should i really go about it to successfully send a ajax request from browser to an api endpoint that needs jwt to verify in normal usecases.

1 Like

For the api I use a simple phoenix token, and pass it in the header.

You might have different ways to get the token, but as it is described, it seems passing the token to javascript via data attribute is possible. The api side will know who You are, without hitting the database (unless You use db to unvalidate token).

1 Like

hi , here i want to cal the same api, that we call with token from a mobile or front end framework, from html phoenix template pages via ajax, so my only concern is where to store the token most effectively and securely so that no one can read it? or any other way to actually send same api request via ajax?

Isn’t ajax obsolete? I thought fetch was the successor…

Anyway if it is in template, You can pass the token as a data attribute of an element, and read it in JS.
If it is an SPA, You can store a refresh token in a cookie.
If it is mobile… there should be a secure storage somewhere (I don’t remember which is the best)

but if i store the token as a data attribute in my page wont it be visible to anyone with knowledge and wont it be non secure?

You are the only one to receive this token… but You need to use https.

yes but as you mentioned , if i store the token as a data attribute in the html template, t will be visible , if anyone inspects , that was my concern