I have hosted a html webpage with js backend that sends a post request to my spring boot server, however I keep getting the same error.
I tried to remove CORS completely in my backend but I have not succeeded. I keep getting 401 forbidden when I inspect element the page and look at the network section. I am running the webpage on a server in vs code and the java in Intellij.
Here is the error I am getting:
Access to fetch at 'http://localhost:8080/auth/login' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
login.js:37 POST http://localhost:8080/auth/login net::ERR_FAILED
loginUser @ login.js:37
onclick @ VM245 index.html:1
login.js:57 Login failed: TypeError: Failed to fetch
at loginUser (login.js:37:5)
at HTMLButtonElement.onclick (VM245 index.html:1:1)
Here is my javascript file:
document.addEventListener('DOMContentLoaded', function () {
const loginForm = document.getElementById('loginForm');
const registrationForm = document.getElementById('registrationForm');
const addressForm = document.getElementById('addressForm');
const switchToRegistration = document.getElementById('switchToRegistration');
const switchToLogin = document.getElementById('switchToLogin');
switchToRegistration.addEventListener('click', function (e) {
e.preventDefault();
loginForm.style.display = 'none';
registrationForm.style.display = 'block';
});
switchToLogin.addEventListener('click', function (e) {
e.preventDefault();
registrationForm.style.display = 'none';
loginForm.style.display = 'block';
});
loginForm.addEventListener('submit', function (e) {
e.preventDefault();
// Correctly access the username and password values from input fields
const username = document.getElementById('loginUsername').value;
const password = document.getElementById('loginPassword').value;
loginUser(username, password);
});
});
function loginUser(username, password) {
const loginData = {
username: username,
password: password
};
fetch('http://localhost:8080/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(loginData)
})
.then(response => response.json())
.then(data => {
// Assuming the authentication key is returned as 'authKey'
const authKey = data.authKey;
localStorage.setItem('authKey', authKey);
window.location.href = 'index.html';
})
.catch(error => {
// Handle login errors (e.g., display an error message)
console.error('Login failed:', error);
});
}
function registerUser() {
}
function submitAddress() {
}
Here is my web security class in my Spring boot backend:
package com.nea.ecommerceBackend.api.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.web.cors.CorsConfiguration;
import java.util.Arrays;
@Configuration
public class WebSecurityConfig {
private JWTRequestFilter jwtRequestFilter;
public WebSecurityConfig(JWTRequestFilter jwtRequestFilter) {
this.jwtRequestFilter = jwtRequestFilter;
}
@Bean(name = "security")
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf((csrf) -> csrf.disable())
.cors((cors) -> cors
.configurationSource(request -> {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*")); // Allow requests from any origin
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
return config;
})
)
.addFilterBefore(jwtRequestFilter, AuthorizationFilter.class)
.authorizeHttpRequests((authorize) -> authorize
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // Permit HTTP OPTIONS requests
.requestMatchers("/product", "/auth/register", "/auth/login").permitAll()
.anyRequest().authenticated()
);
return http.build();
}
}