有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么Spring安全应用程序重定向到登录页面,尽管我们没有提供Spring安全配置?

我不提供任何Spring安全配置,每个请求URL都重定向到登录页面。我已经使用“Spring Initializer”创建了一个Spring启动应用程序,它具有所需的Spring安全依赖项

为什么它会将每个请求重定向到登录页面?如何禁用此功能

我尝试删除所有安全配置

@SpringBootApplication
public class SpringbootJwtExampleApplication {

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

}

public interface VehicleRepository extends JpaRepository<Vehicle, Long> {
}


@Data
@Entity
public class Vehicle {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}


@RestController
@RequestMapping("/v1/vehicles")
public class VehicleController {

    @Autowired
    private VehicleRepository vehicleRepository;

    @GetMapping("")
    public ResponseEntity getAll(){
        return ok(vehicleRepository.findAll());
    }
}

当我请求http://localhost:8080/v1/vehicles 它将重定向到登录页面。它应该请求实际的请求


共 (2) 个答案

  1. # 1 楼答案

    根据Spring Security documentation,WebSecurityConfigureAdapter类提供以下默认配置:

    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .and()
            .httpBasic();
    }
    

    要覆盖这些默认值,请编写自己的WebSecurityConfig,例如:

    @Configuration
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            // Your own rules
        }
    }
    
  2. # 2 楼答案

    • 如果要禁用临时spring安全性,请在spring主类中添加注释@SpringBootApplication(exclude={SecurityAutoConfiguration.class})

      @SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
      public class DemoApplication
      {
      public static void main(String[] args)
      {
          SpringApplication.run(DemoApplication.class, args);
      }
      }
      
    • 另一种解决方案是通过扩展 阶级

      @Configuration
      @EnableWebSecurity
      public class BasicConfiguration extends WebSecurityConfigurerAdapter {
      @Override
      protected void configure(HttpSecurity http) throws Exception {
        //customize the configs
      }
      }
      
    • 最后,如果项目中不需要安全性,请删除pom中的spring安全性依赖项。xml文件