ivymasterman's avatar

How to redirect from a public api endpoint, to an endpoint that requires authentification?

Hello, I am having an issue with redirections.

I Have a public route, to which I make a GET request, and pass the "plaintTextToken" as the parameter in the URL. In the public endpoint, I want to redirect to an endpoint that requires authentification. But the app does not take into consideration the bearer token that I passed. Used auth middleware is "sanctum".

return redirect()->route("protected_route", [
        "filteName" => $request->query("filteName"),
    ])->with([
        "Accept" => "application/json",
        "Authorization" => "Bearer " . $request->query("plainTextToken"),
    ]);

It is a local redirection. Pls help :)

0 likes
6 replies
kokoshneta's avatar

The ->with() function attaches session data to the request; your authentication stuff should go in the request headers, for which you’d use ->header() or ->withHeaders().

ivymasterman's avatar

@kokoshneta I forgot to mention that I have tried that to as well. Still redirects to the login route. Do I need to pass some additional header myb?

martinbean's avatar

@ivymasterman If the URL you’re redirecting to requires authentication then you should attach the token to that URL as well. But you wouldn’t normally use token-based authentication in browser-based apps, so sounds like you’re using an API in an unintended manner.

ivymasterman's avatar

@martinbean It is a messy situation. I have a front-end app, and an API. I wanted to download file in the front-end app, from the API , that is calling a 3 party service from the controller.

Somebody suggested to add anchor that would directly open the API route, since you can not download file, via axios call in the front-end app, apparently.

But the problem is how to add authentification to the back-end endpoint, that uses "auth:sanctum" middleware. So I tried with redirects, but it keeps redirect me to login, as if the header Authorization is not even set in the redirection.

ivymasterman's avatar

@martinbean Also, when I call the route, from Postman, with the same bearer token as in the redirection, it works fine. Are you aware of some API middlewares that would cause this behavior, myb something needs to be included?

Please or to participate in this conversation.