Sajjad Ali's avatar

Login api request success but doesn't return user object

I'm trying to login via sanctum. This is my Controller method created by breeze in Http\Controllers\Auth\AuthenticatedSessionController.php.

public function store(LoginRequest $request)
    {
        $request->authenticate();

        $request->session()->regenerate();

        return response()->noContent();
    }

This is API route for user.

Route::middleware(['auth:sanctum'])->get('/user', function (Request $request) {
    return $request->user();
});

And this is the request via axios.

// api.ts
import axios from "axios";
const api = axios.create({
	baseURL: "http://127.0.0.1:8000",
	withCredentials: true,
});
export default API;

// login method in pinia store
async login(username: string, password: string) {
    this.loading = true;

    await api("/sanctum/csrf-cookie").then(async (res) => {
        await api
            .post("/login", {
                email: username,
                password: password,
            })
            .then((res: any) => {
                console.log(res.data);
            })
            .catch((error: any) => {
                this.error = error.response;
            });
    });
	this.loading = false;
}

When I try to login. This is the response. https://i.imgur.com/xXggAIL.png https://i.imgur.com/CX7JxVq.png

Why it's trying to redirect. I tried to trace store method in routes\auth.php and seems like that store method is pointing to \vendor\..\breeze\stubs\...\AuthenticatedSessionController.php and not to the one I posted above.

And when I try to fetch user data.

// fetch user method in pinia store
async fetchUser() {
	this.user = await api("/api/user");
	console.log(this.user);
}

// App.vue
onMounted(() => {
	fetchUser();
});

It's showing this error.

GET http://127.0.0.1:8000/api/user 401 (Unauthorized)

Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
xhr.js:220          GET http://127.0.0.1:8000/dashboard 404 (Not Found)

What am I doing wrong? How can I disable redirect for Controller request?

0 likes
5 replies
vincent15000's avatar
Level 63

Have you declared the right stateful domains for Sanctum ?

And you are visibly trying to access the user API and it's not authorized. Is your user API route protected by the auth:sanctum middleware ?

1 like
Sajjad Ali's avatar

@vincent15000 Thank you. Stateful domain was the issue. Vite is starting on port 5173. Adding that to the config solved the problem.

2 likes
Sajjad Ali's avatar

@OUROBOROS_benin I just changed the stateful domain in sanctum configuration file. If I remember correctly, it was set to localhost:3000 while Vite was starting the application on port 5173. So changing that port number fixed the issue.

1 like

Please or to participate in this conversation.