Adding spring security to working spring-boot app

  Kiến thức lập trình

There are two controllers web

@Controller
public class WebController {
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/api")
    public String showForm() {
        return"bars";
    }
}

and rest

@RestController
@RequestMapping("/api")
public class RestBarController {
    @CrossOrigin//(origins = "http://localhost:8080")
    @GetMapping("/app")
    public List<Bar> getBars(){
        LocalDateTime localDateTime = LocalDateTime.now();
        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
        //LocalTime localTime = localDateTime.toLocalTime();
        
        List<Bar> bars = new ArrayList();
        for(int i = 0; i<20; i++) {
            Bar bar = new Bar();
            localDateTime = localDateTime.plusMinutes(1);
            bar.setTime(localDateTime);
            bar.setShortTime(localDateTime.format(formatter));
            bar.setBlack((int)(-Math.random()*1000));
            bar.setWhite((int)(Math.random()*1000));
            bars.add(bar);
        }
        
        
        return bars;
    }
}

and js which render data to chart with chartJS

var shortTimeLabel =[];
var blackData = [];
var whiteData = [];
var chart;
    
const apiUrl = "http://127.0.0.1:8080/api/app";
var response;// = await fetch(apiUrl);
var barChartData;// = await response.json();
var short_time;// = barChartData.map((x) => x.shortTime);
var black_;//_ = barChartData.map((x) => x.black);
var white_;//_ = barChartData.map((x) => x.white);

    
async function dummyChart(){
    await getDummyData();
    let ctx = document.getElementById('myChart');

    chart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: shortTimeLabel,
      datasets: [{
        label: 'Down',
                backgroundColor: 'blue',
        data: blackData,
        borderWidth: 1
      },
            {
        label: 'Up',
                backgroundColor: 'pink',
        data: whiteData,
        borderWidth: 1
      }]
    },
    options: {
            tooltips: {
                mode: 'index'
            },
      responsive: true,
      maintainAspectRatio: false,
    scales: {
      x: {
        stacked: true,
      },
      y: {
        stacked: true
      }
    }
    }
  });
}
dummyChart();

setInterval(updateConfigByMutating, 10000);
console.log("Hello");


async function updateConfigByMutating() {
    await getDummyData();
    chart.options.plugins.title.text = 'new title';
    for (let i = 0; i < chart.data.datasets[0].data.length; i++) {
        chart.data.datasets[0].data[i] = black_[i];
    } 
    
    for (let i = 0; i < chart.data.datasets[1].data.length; i++) {
        chart.data.datasets[1].data[i] = white_[i];
    } 
    
    for (let i = 0; i < chart.data.labels.length; i++) {
        chart.data.labels[i] = short_time[i];
    } 
    
    
    chart.update();
}

    //Fetch data from dummy REST API
    async function getDummyData(){
        response = await fetch(apiUrl);
        barChartData = await response.json();
        short_time = barChartData.map((x) => x.shortTime);
        black_ = barChartData.map((x) => x.black);
        white_ = barChartData.map((x) => x.white);
        console.log(short_time, black_, white_);
        
        shortTimeLabel = short_time;
        blackData = black_;
        whiteData = white_;

    }

And it works fine
enter image description here

But when i try to add spring security it will not work.

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // cross site request forgery
            .csrf(csrf->csrf.disable())
            .authorizeHttpRequests((authorizeHttpRequests) ->
                authorizeHttpRequests
                // access to the root of our app index.html in resources/static (doesn’t work)
                .requestMatchers("/").permitAll()
                // acces to url /api
                .requestMatchers(HttpMethod.GET, "/api/**").hasAnyRole(Role.ADMIN.name(), Role.USER.name())
                // any request should be authenticated
                .anyRequest()
                .authenticated()
            )
            .formLogin(withDefaults());
            //.httpBasic(withDefaults());
        return http.build();
    }
    
    @Bean
    public InMemoryUserDetailsManager inMemoryUserDetailsManager(){

        UserDetails admin = User.builder()
            .username("admin")
            .password(passwordEncoder().encode("admin"))
            .roles("ADMIN")
            .build();
        
         UserDetails user = User.builder()
             .username("user")
             .password(passwordEncoder().encode("user"))
             .roles("USER")
             .build();
            
        System.out.println(user.getPassword());
        System.out.println(admin.getPassword());
        return new InMemoryUserDetailsManager(user, admin);
    }
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

but chart doesn’t load and in browser console i see code 302 Access-Control-Allow-Origin. I’m sure that problem is in spring security configuration.

New contributor

geronimo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT