#How to access authenticated user/authentication object on react frontend after logging in?
21 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @queen kindle! Please use
/closeor theClose Postbutton above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
Your main Component onto load (in useEffect) should connect to backend and the backend should return the role. The backend checks if a user is Authenticated. If yes then it should return lets say role name. Your React should get this data as a response data and dispatch as a payload for reducer.
if server (Spring Boot) returns 200 with the body of role then useEffect can get it and the type of dispatch is LOGIN, otherwise ERROR
It depends how you made it. You can either have a global state and keep ther user data and then create special router which acts based on that state values
and you can do so it would not always sent the request
Those states that are inside component are cleared out. But states that are outside it - not
or if you save this data to browser local storage then it will not be lost
If you are affraid then redux.
Though I used import React, { useEffect, useReducer, useState } from "react"; useReducer
acts similarly
I don't know of csrf. You decide
If you are finished with your post, please close it.
If you are not, please ignore this message.
Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
I will show you what I used:
import React, { useEffect, useReducer, useState } from "react";
import { Switch, Route, Redirect } from "react-router-dom";
import Login from "./components/01Login/LoginContainer";
//......
var initState = {
isAuthenticated: null,
username: null,
role: null,
error: null,
};
const reducer = (state, action) => {
switch (action.type) {
case "LOGIN":
return {
...state,
isAuthenticated: true,
username: action.payload.username,
role: action.payload.role,
error: null,
};
case "LOGOUT":
return {
...state,
isAuthenticated: false,
username: null,
role: null,
error: null,
};
case "ERROR":
return {
...state,
isAuthenticated: false,
username: null,
role: null,
error: action.payload,
};
default:
return state;
}
};
function App() {
const [state, dispatch] = useReducer(reducer, initState);
const [compState, setCompState] = useState([]);
useEffect(() => {
if (state.isAuthenticated === null) {
http
.get(`${apiEndpoint}/api/loggedUserRole`)
.then((resp) => {
dispatch({
type: "LOGIN",
payload: { role: resp.data },
});
})
.catch((error) => {
const unexpectedError =
error.response &&
error.response.status >= 400 &&
error.response.status < 500;
if (
!unexpectedError ||
(error.response && error.response.status === 404)
) {
swal("The source is unavailable");
dispatch({
type: "ERROR",
});
} else
dispatch({
type: "ERROR",
payload: error.response.status,
});
});
}
}, [state.isAuthenticated]);
If I'll be around I can answer
And router goes like:
if (state.isAuthenticated) {
switch (state.role) {
case "ADMIN":
return (
<AuthContext.Provider value={{ state, dispatch }}>
<CommonErrorHandler>
<div className="container-fluid px-0">
<AdminNavBar>
<Switch>
<Route exact path="/" component={Admin} />
<Route exact path="/home" component={Admin} />
//.....
<Route path="*" component={NotFound} />
</Switch>
</AdminNavBar>
</div>
</CommonErrorHandler>
</AuthContext.Provider>
);
case "MANAGER":
Never heard. maybe will check some day
I don't know if you have to bombard the server everytime you visit protected page. it's a bad idea. I think the router structure should be role based. ADMIN can visit pages that are protected. USER role not. And the role should be in a global state that doesn't change on your page re-renders and walking through routes.
So instead of everytime calling the server to check the user keep an object in global state. And based on its data allow or not to access certain pages.
On logout change this state
yea