spring引导安全:如何跳过localhost的登录?

kuhbmx9i  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(319)

我的工作spring boot securityconfig当前如下所示:

protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/css/**", "/js/**", "/img/**", "/error", "/webjars/**", "/login", "**/favicon.ico").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin().failureUrl("/login?state=badauth")
            .loginPage("/login")
            .loginProcessingUrl("/processLogin")
            .successHandler(successHandler())
            .failureHandler(failureHandler())
            .permitAll()
            .and()
            .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login?state=loggedout");
    ;
    }

我正在尝试允许localhost上的用户在不登录的情况下访问所有资源。我尝试将以下内容插入链中的各个位置:

.antMatchers("/**").access("hasIpAddress(\"127.0.0.1\") or hasIpAddress(\"::1\")")

这总是会导致非本地主机访问失败,并出现禁止的错误。
如何绕过本地主机上的用户登录?

azpvetkf

azpvetkf1#

试试这个
演示应用程序.java

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

testcontroller.java测试控制器

@RestController
public class TestController {

    @GetMapping("/secured")
    public ResponseEntity secured() {
        return ResponseEntity.ok("Access granted");
    }

}

Web安全配置.java

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
                .antMatchers("/**")
                .access("hasIpAddress('127.0.0.1') or hasIpAddress('::1') or isAuthenticated()")  // 127.0.0.1 and localhost do not need to authenticate on any url
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("user").password(passwordEncoder().encode("password"))
                .authorities("ROLE_USER");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
cdmah0mi

cdmah0mi2#

在进行身份验证之前,请尝试添加hasipaddress(),如下所示:

.antMatchers("/**").hasIpAddress("127.0.0.1").anyRequest().authenticated();
os8fio9y

os8fio9y3#

您可以尝试在spring boot中禁用默认安全性,方法是在 application.properties 本地/dev概要文件: security.basic.enabled=false

相关问题