[英]Spring Boot Security: How to skip login for localhost?
我的工作 spring 啟動 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");
;
}
我試圖讓本地主機上的用戶無需登錄即可訪問所有資源。我嘗試將以下內容插入到鏈中的各個位置:
.antMatchers("/**").access("hasIpAddress(\"127.0.0.1\") or hasIpAddress(\"::1\")")
這總是會導致非本地主機訪問因禁止而失敗。
如何僅繞過本地主機上的用戶登錄?
嘗試這個
DemoApplication.java
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
測試控制器.java
@RestController
public class TestController {
@GetMapping("/secured")
public ResponseEntity secured() {
return ResponseEntity.ok("Access granted");
}
}
WebSecurityConfig.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();
}
}
嘗試在像這樣進行身份驗證之前添加 hasIpAddress() :
.antMatchers("/**").hasIpAddress("127.0.0.1").anyRequest().authenticated();
您可以嘗試通過在本地/開發配置文件的application.properties
文件中添加以下行來禁用 Spring 引導中的默認安全性:
security.basic.enabled=false
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.