Context
Issue
I want to make a login request from react to get the jsessionid
. I am getting a weird response from Spring Boot. In the response i don't find any cookies. In postman i can just give the username and password in the url as parameters and in the response I am getting a response with the cookie jsessionid
and for more requests I can just use it. But in react I am getting a weird response and I don't know how to get the cookie.
Here is the code that sends the request from React JS to Spring Boot:
const { username, password } = this.state;
const student = { username, password };
fetch("http://localhost:8080/login", {
method: "POST",
body: new URLSearchParams(student)
})
.then(res => {
console.log(res);
const jsessionid = document.cookie;
console.log("id", jsessionid);
//Here I am trying to get the jsessionid
})
.catch(error => console.log(error));
This is the response that I am getting and that I printed out in the console
And here is my Spring Securtiy Configuration Class:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
@Autowired
UserDetailsServiceImpl userDetailsService;
@Bean
DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
return daoAuthenticationProvider;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable().cors().and()
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("*"));
configuration.setAllowedMethods(Arrays.asList("*"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Here I tried with curl and as you can see I am getting the cookie jsessionid
.
You can access your jsessionid
from response.header
for example
fetch("http://localhost:8080/login", {
method: "POST",
body: new URLSearchParams(student)
credentials: 'include',
headers: {
'Content-Type': 'application/json'
}
})
.then(res=>console.log(res.headers.get('set-cookie'));)
.catch(error => console.log(error));