SpringBoot: CORS Issue - Fetch access blocked by CORS Policy

Viewed 261

I am working with OAuth2, while OAuth works with same domain it doesn't work with other domains thus giving CORS error. I've been using SpringBoot(Version - 2.7.0, Java JDK - 11) for backend

Backend Domain - http://localhost:8080/

Frontend Domain - http://127.0.0.1:5500/

I've encountered these errors: Image of all the errors I'm getting

These are the related codes

SecurityConfig.java

package com.example.oauth_example.security;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS,"http://127.0.0.1:5500/index.html").permitAll()
            .anyRequest().authenticated()
            .and().oauth2Login();
    }
}

CorsConfig.java

package com.example.oauth_example.security;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(Boolean.TRUE);
        config.addAllowedOrigin(CorsConfiguration.ALL);
        config.addAllowedHeader(CorsConfiguration.ALL);
        config.addAllowedMethod("GET");
        config.addExposedHeader("Authorization");

        source.registerCorsConfiguration("/api/v1/**", config);

        return new CorsFilter(source);
    }
}

The main controller file: SocialController.java

package com.example.oauth_example.controller;

import java.security.Principal;
import java.util.Map;


import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.RedirectView;

@RestController
@RequestMapping("/api/v1")
@CrossOrigin(origins = "http://127.0.0.1:5500", maxAge = 3600)
public class SocialController {

    @CrossOrigin
    @GetMapping("/greet")
    public RedirectView greet(){
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://127.0.0.1:5500/home.html");
        return redirectView;
    }
    @CrossOrigin
    @GetMapping("/current-user-principal")
    public Principal currentUser(Principal principal){
        return principal;
    }
    @CrossOrigin
    @GetMapping("/current-user-details")
    public Map<String, Object> authUser(@AuthenticationPrincipal OAuth2User user){
        return user.getAttributes();
    }
    
}

Fetching data in frontend using basic JS: main.js

async function getUserData(){
    fetch('http://localhost:8080/api/v1/current-user-details')
        .then(response => response.json())
        .then(data => {
            console.log(data)
        });
}

I'm not able to figure out where I'm going wrong. Thank you in advance.

0 Answers
Related