Your setup is mostly correct, but the root cause of your “Invalid username or password” error lies in how your backend and frontend are handling the login response format and password encoding together.
Let’s go step by step:
🧩 1. The actual backend issue
Your backend’s login method:
works fine logically — it:
-
finds the user by username
-
checks the password using
passwordEncoder.matches()
-
returns a JWT token
BUT you are returning just a String
(the token).
Your frontend’s AuthContext.js
is expecting this:
That means it expects the backend to return an object like:
But your backend returns just a plain token string, so res.data.token
becomes undefined
.
That’s why the frontend can’t handle the response properly and the login “fails.”
🧱 2. The password part (encoded vs raw)
Your registration uses:
so the password is encoded in the database.
During login:
correctly compares raw password with encoded — ✅
No issue here, as long as the same encoder is used.
So password matching works fine.
The only reason you see “Invalid username or password” is likely because the user isn’t being found (wrong username) or you’re testing with unencoded passwords in DB from older runs.
You can verify quickly:
If you see plain text passwords (not starting with $2a$
or $2b$
), then re-register the user — those won’t match.
🩹 3. The required backend fix
Change your loginUser()
and AuthController
to return a JSON object containing token, username, and role.
✅ Update in AuthService.java
✅ Update in AuthController.java
Now, the response from backend will look like:
and your frontend’s line:
will correctly pick token
and store the rest in localStorage.
✅ 4. Double-check these final details
a. Register a fresh user
Since passwords are encoded, old users (from before encoding) won’t work.
b. Confirm .env
or application.properties
Your jwt.secret
must be a valid Base64 string (at least 32 bytes long). Example:
c. Ensure your frontend points to the right auth base URL
In constants.js
:
✅ Final Summary
Problem | Fix |
---|---|
Backend returns plain string instead of JSON | Return { token, username, role } object |
Password check fails for old users | Re-register so passwords are encoded |
Frontend expecting structured JSON | Now matches backend output |
JWT key not Base64 encoded | Ensure proper secret format |
Would you like me to show how to modify your frontend login logic slightly to show better error messages and persist both token + role in context cleanly?
0 Comments