Jwt token

I am not able to extract the header from my spring boot app controller Spring boot backend
@PostMapping("login")
public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// Collect all errors into a list of strings
List<String> errors = bindingResult.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getRejectedValue())
.collect(Collectors.toList());
throw new ValidationException(errors);
}
String jwt = jwtService.authentication(authRequest);
return ResponseEntity.status(HttpStatus.OK)
.header("Authorization", "Bearer " + jwt) // Add the token as a Bearer token
.body("Login successful. JWT token added in the header." + jwt); }
@PostMapping("login")
public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// Collect all errors into a list of strings
List<String> errors = bindingResult.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getRejectedValue())
.collect(Collectors.toList());
throw new ValidationException(errors);
}
String jwt = jwtService.authentication(authRequest);
return ResponseEntity.status(HttpStatus.OK)
.header("Authorization", "Bearer " + jwt) // Add the token as a Bearer token
.body("Login successful. JWT token added in the header." + jwt); }
React frontend
const response = await axios.post("http://localhost:8080/api/auth/login" , data , {
withCredentials: true, // Ensure credentials are included if required by the server
});

console.log(response.data);
const token = response.headers["authorization"];
if (token) {

localStorage.setItem("jwtToken", token);

alert("Successfully logged in!");
} else {
alert("Token not found in the response.");
}
const response = await axios.post("http://localhost:8080/api/auth/login" , data , {
withCredentials: true, // Ensure credentials are included if required by the server
});

console.log(response.data);
const token = response.headers["authorization"];
if (token) {

localStorage.setItem("jwtToken", token);

alert("Successfully logged in!");
} else {
alert("Token not found in the response.");
}
61 Replies
JavaBot
JavaBotā€¢4d ago
āŒ› This post has been reserved for your question.
Hey @Danix! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant 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.
ayylmao123xdd
ayylmao123xddā€¢4d ago
um you are checking if your header has authorization but the server makes a header named Authorization
Danix
DanixOPā€¢4d ago
yeh it have
ayylmao123xdd
ayylmao123xddā€¢4d ago
or did you fix that
Danix
DanixOPā€¢4d ago
You mean i have to check for the Authorization not for the authorization ?
ayylmao123xdd
ayylmao123xddā€¢4d ago
yes try that and see if it helps
Danix
DanixOPā€¢4d ago
let me'
ayylmao123xdd
ayylmao123xddā€¢4d ago
ok
Danix
DanixOPā€¢4d ago
no still the same
ayylmao123xdd
ayylmao123xddā€¢4d ago
show the code how u changed it
Danix
DanixOPā€¢4d ago
const onSubmit = async(data) => {
try{
const response = await axios.post("http://localhost:8080/api/auth/login" , data , {
withCredentials: true, // Ensure credentials are included if required by the server
});

console.log(response.data);
const token = response.headers["Authorization"];
if (token) {

localStorage.setItem("jwtToken", token);

alert("Successfully logged in!");
} else {
alert("Token not found in the response.");
}
const onSubmit = async(data) => {
try{
const response = await axios.post("http://localhost:8080/api/auth/login" , data , {
withCredentials: true, // Ensure credentials are included if required by the server
});

console.log(response.data);
const token = response.headers["Authorization"];
if (token) {

localStorage.setItem("jwtToken", token);

alert("Successfully logged in!");
} else {
alert("Token not found in the response.");
}
ayylmao123xdd
ayylmao123xddā€¢4d ago
do you have a cors config class
Danix
DanixOPā€¢4d ago
yeh in my spring boot package
ayylmao123xdd
ayylmao123xddā€¢4d ago
did you expose the authorization header can you show it
Danix
DanixOPā€¢4d ago
yeh
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addExposedHeader("Set-Cookie");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.addExposedHeader("Set-Cookie");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(cors -> corsFilter())
.csrf(csrf -> csrf.disable()) // Disable CSRF for stateless APIs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("ADMIN")
.requestMatchers("/api/**", "/api/scriptenhancer/**").permitAll()
.anyRequest().authenticated() // Protect all other endpoints
)
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions
).exceptionHandling(e -> {
e.authenticationEntryPoint((req, res, ex) -> {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
});
})
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter

return http.build();
}

@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsServicImp).passwordEncoder(config.passwordEncoder());
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.cors(cors -> corsFilter())
.csrf(csrf -> csrf.disable()) // Disable CSRF for stateless APIs
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/admin/**").hasAuthority("ADMIN")
.requestMatchers("/api/**", "/api/scriptenhancer/**").permitAll()
.anyRequest().authenticated() // Protect all other endpoints
)
.sessionManagement(sess -> sess
.sessionCreationPolicy(SessionCreationPolicy.STATELESS) // No sessions
).exceptionHandling(e -> {
e.authenticationEntryPoint((req, res, ex) -> {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, ex.getMessage());
});
})
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class); // Add JWT filter

return http.build();
}

@Bean
AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}

@Autowired
protected void configureAuthentication(AuthenticationManagerBuilder auth)
throws Exception {
auth.userDetailsService(userDetailsServicImp).passwordEncoder(config.passwordEncoder());
}
ayylmao123xdd
ayylmao123xddā€¢4d ago
add this
config.addExposedHeader("Authorization");
config.addExposedHeader("Authorization");
and check if it works
Danix
DanixOPā€¢4d ago
yeh sure nahh still the same
ayylmao123xdd
ayylmao123xddā€¢4d ago
interesting can you try to add another random header and try to read it like idk "abc123" and try to read it in your front end
Danix
DanixOPā€¢4d ago
hm let me
ayylmao123xdd
ayylmao123xddā€¢4d ago
you can also print all the header attributes
response.headers.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
response.headers.forEach((value, key) => {
console.log(`${key}: ${value}`);
});
see what it says
Danix
DanixOPā€¢4d ago
still undefined for the new header aswell
ayylmao123xdd
ayylmao123xddā€¢4d ago
does this print any headers
Danix
DanixOPā€¢4d ago
no
The new header is undefined
LoginForm.jsx:33 The Token is here ! undefined
The new header is undefined
LoginForm.jsx:33 The Token is here ! undefined
ayylmao123xdd
ayylmao123xddā€¢4d ago
quite interesting
Danix
DanixOPā€¢4d ago
yeh\
ayylmao123xdd
ayylmao123xddā€¢4d ago
hmmmmmmmmmm for testing purposes
Danix
DanixOPā€¢4d ago
No description
ayylmao123xdd
ayylmao123xddā€¢4d ago
do add allowed origin and your app port instead of the
Danix
DanixOPā€¢4d ago
Abc is not considered as a header here !
ayylmao123xdd
ayylmao123xddā€¢4d ago
* šŸ˜±
Danix
DanixOPā€¢4d ago
what
ayylmao123xdd
ayylmao123xddā€¢4d ago
show the code that u use to check if there is abc header
Danix
DanixOPā€¢4d ago
@PostMapping("login")
public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// Collect all errors into a list of strings
List<String> errors = bindingResult.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getRejectedValue())
.collect(Collectors.toList());
throw new ValidationException(errors);
}
String jwt = jwtService.authentication(authRequest);
return ResponseEntity.status(HttpStatus.OK)
.header("Authorization", "Bearer " + jwt) // Add the token as a Bearer token
.header("abc", "I am a random header")
.body("Login successful. JWT token added in the header." + jwt);
@PostMapping("login")
public ResponseEntity<?> login(@Valid @RequestBody AuthRequest authRequest, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
// Collect all errors into a list of strings
List<String> errors = bindingResult.getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getRejectedValue())
.collect(Collectors.toList());
throw new ValidationException(errors);
}
String jwt = jwtService.authentication(authRequest);
return ResponseEntity.status(HttpStatus.OK)
.header("Authorization", "Bearer " + jwt) // Add the token as a Bearer token
.header("abc", "I am a random header")
.body("Login successful. JWT token added in the header." + jwt);
ayylmao123xdd
ayylmao123xddā€¢4d ago
yea and show frontend
Danix
DanixOPā€¢4d ago
const onSubmit = async(data) => {
try{
const response = await axios.post("http://localhost:8080/api/auth/login" , data );

console.log(response.data);
const headerToken = response.headers["abc"];
console.log("The new header is " , headerToken);

const onSubmit = async(data) => {
try{
const response = await axios.post("http://localhost:8080/api/auth/login" , data );

console.log(response.data);
const headerToken = response.headers["abc"];
console.log("The new header is " , headerToken);

ayylmao123xdd
ayylmao123xddā€¢4d ago
hmmmmmmmm
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedHeader("*");
config.addExposedHeader("Authorization");
config.addExposedHeader("abc");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:3000");
config.addAllowedHeader("*");
config.addExposedHeader("Authorization");
config.addExposedHeader("abc");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}
can you try this config
Danix
DanixOPā€¢4d ago
yeh sure
ayylmao123xdd
ayylmao123xddā€¢4d ago
did it help btw
Danix
DanixOPā€¢4d ago
i am trying it
Access to XMLHttpRequest at 'http://localhost:8080/api/auth/login' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
LoginForm.jsx:38 Signup Failed: undefined
onSubmit @ LoginForm.jsx:38
await in onSubmit
(anonymous) @ createFormControl.ts:1195
await in (anonymous)
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26179
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
LoginForm.jsx:17


POST http://localhost:8080/api/auth/login net::ERR_FAILED
Access to XMLHttpRequest at 'http://localhost:8080/api/auth/login' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
LoginForm.jsx:38 Signup Failed: undefined
onSubmit @ LoginForm.jsx:38
await in onSubmit
(anonymous) @ createFormControl.ts:1195
await in (anonymous)
callCallback2 @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26179
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
LoginForm.jsx:17


POST http://localhost:8080/api/auth/login net::ERR_FAILED
ayylmao123xdd
ayylmao123xddā€¢4d ago
o so your app runs at 5173 put 5173 here instead of 3000
Danix
DanixOPā€¢4d ago
i did but i think i need to restart the server
ayylmao123xdd
ayylmao123xddā€¢4d ago
yes
Danix
DanixOPā€¢4d ago
ok so now i got abc header but not the authorization one! we are progressing
ayylmao123xdd
ayylmao123xddā€¢4d ago
amazing
Danix
DanixOPā€¢4d ago
but the thing is the abc header isn't in the headers list !
No description
ayylmao123xdd
ayylmao123xddā€¢4d ago
it is well it kind of is
Danix
DanixOPā€¢4d ago
yeh i can see the header abc in the headers panel in postman if i will change the header named from authorization to just auth so that might work ?
ayylmao123xdd
ayylmao123xddā€¢4d ago
hm try it and make sure to swap the name in the server in the exposed headers
Danix
DanixOPā€¢4d ago
nahh still the same undefined shit !
ayylmao123xdd
ayylmao123xddā€¢4d ago
truly a disaster ok show both codes again the one with corsfilter and frontend
Danix
DanixOPā€¢4d ago
let me show u my github so i might be better
ayylmao123xdd
ayylmao123xddā€¢4d ago
ok lol what if you try to do the auth attribute now wait nevermind
Danix
DanixOPā€¢4d ago
I have a secret api tokejn in my app.properties and git is not allowing me to push the code so what can i do to commit it ?
ayylmao123xdd
ayylmao123xddā€¢4d ago
oh dont push it then what if you rename the abc header to auth check if you can read it then and try to pass to that header the jwt token
Danix
DanixOPā€¢4d ago
yeh let me with the name of auth i am getting it ! 1 sec I am able to get it via post man
Danix
DanixOPā€¢4d ago
No description
Danix
DanixOPā€¢4d ago
bro we got it :boohoo:
const token = response.headers.get("Authorization");
const token = response.headers.get("Authorization");
ayylmao123xdd
ayylmao123xddā€¢4d ago
niceeeeeeeeeeeeeee
Danix
DanixOPā€¢4d ago
real
JavaBot
JavaBotā€¢4d ago
šŸ’¤ Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived. If your question was not answered yet, feel free to re-open this post or create a new one. In case your post is not getting any attention, you can try to use /help ping. Warning: abusing this will result in moderative actions taken against you.

Did you find this page helpful?