When logging into my application, the Authorization inside the header returns as undefined
enter image description here
But, when checking within the developer tools in ‘Network’ the token is there in the Authorization field of the Header
enter image description here
Does anyone know what can it be? I made several changes, such as using only redux later in conjunction with axios, but without success.
My store.js
import { AuthReducer } from "../Auth/Reducer";
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import logger from "redux-logger";
const rootReducers = combineReducers({
auth: AuthReducer,
});
export const store = configureStore({
reducer: rootReducers,
middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),
});
My action.js
import axios from "axios";
const ROOT_URL = "http://localhost:8080";
export const signinAction = (data) => async (dispatch) => {
try {
const response = await axios.get(`${ROOT_URL}/signin`, {
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
Authorization: "Basic " + btoa(data.email + ":" + data.password),
},
});
if (response.status === 200) {
const authorizationHeader = response.headers.authorization;
console.log(authorizationHeader);
} else {
throw new Error("Falha ao fazer login");
}
} catch (error) {
console.error("Erro:", error.message);
}
};
My Reducer.js
import { SIGN_IN, SIGN_UP } from "./ActionType";
const initialValue = {
signup: null,
signin: null,
};
export const AuthReducer = (store = initialValue, { type, payload }) => {
if (type === SIGN_IN) {
return { ...store, signin: payload };
} else if (type === SIGN_UP) {
return { ...store, signup: payload };
}
return store;
};
My dispatch in Signin.jsx
const dispatch = useDispatch();
const handleSubmit = (values, actions) => {
dispatch(signinAction(values));
actions.setSubmitting(false);
};
My CORS configuration
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
Map<String, String> map = new HashMap<>();
String originHeader = request.getHeader("origin");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3000");
response.setHeader("Access-Control-Allow-Headers", "*");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(req, res);
}
}
My call sigin in Backend
@GetMapping("/signin")
public ResponseEntity<User> signInHandler(Authentication auth) throws BadCredentialsException {
Optional<User> optionalUser = userRepository.findByEmail(auth.getName());
if (optionalUser.isPresent()) {
return new ResponseEntity<>(optionalUser.get(), HttpStatus.OK);
}
throw new BadCredentialsException("Invalid username or password");
}
And I hope I can get the Authorization value
Ero Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
I solved this problem by adding
response.setHeader("Access-Control-Expose-Headers", "Authorization");
in the CORS doFilter method
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
Map<String, String> map = new HashMap<>();
String originHeader = request.getHeader("origin");
response.setHeader("Access-Control-Allow-Origin", originHeader);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
response.setHeader("Access-Control-Max-Age", "3000");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Expose-Headers", "Authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())){
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(req, res);
}
}
Ero Lima is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.