Невозможно отменить безопасность пружинной загрузки - PullRequest
0 голосов
/ 18 июня 2020

Я пытаюсь переопределить настройки безопасности Spring Boot. Но каждый раз, когда я пытаюсь получить доступ к любому URL-адресу, он дает мне страницу входа в систему безопасности Spring по умолчанию. А еще я пытаюсь использовать REST API. Вот моя попытка. Пожалуйста, помогите мне решить проблему. Спасибо.

Вот мой пом. xml

   <parent>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.3.1.RELEASE</version>
       <relativePath/>
   </parent>

    <dependency>
       <groupId>org.springframework.cloud</groupId>
       <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>

   <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-security</artifactId>
   </dependency>

Вот мой главный класс

@SpringBootApplication(exclude = {
        SecurityAutoConfiguration.class
})
public class ApiGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }

}

SecurityConfig.class

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors().and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/greetings").permitAll()
                .and()
                .httpBasic()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}

MyController .class

@RestController
@RequestMapping
public class MyController {

    @GetMapping("/greetings")
    public String greetings(){
        return "Hello World!";
    } 

}

Я также добавляю свойство в properties.yml.

spring:
  main:
    allow-bean-definition-overriding: true

Застрял на странице входа.

localhost: 8080 / приветствия перенаправляют меня на localhost: 8080 / логин каждый раз.

Введите localhost: 8080 / greetings

REdirect to localhost: 8080 / login

Ответы [ 2 ]

0 голосов
/ 18 июня 2020

Поскольку Spring защищает каждый запрос по умолчанию, когда мы включаем безопасность Spring. один раз, если мы переопределим метод конфигурации, каждый запрос должен обрабатываться самим пользователем.

@ Override protected void configure (HttpSecurity http) выдает исключение {

    http.cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/greetings").permitAll()
            .anyRequest().authenticated()
            .and()
            .httpBasic()
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

include .anyRequest (). Authenticated () это может работать.

0 голосов
/ 18 июня 2020

, вы можете использовать конфигурацию на основе java, например,

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity security) throws Exception
 {
  security.httpBasic().disable();
 }
}

, или вы можете просто добавить в свой метод настройки

    .formLogin().disable()

или добавить в свой application.properties файл или application.yml

security.basic.enabled=false
...