我正在应用 spring boot security。当我在当前代码中打开浏览器时,它会无限重定向到 \'http://localhost:8080/login\' 并显示错误 \'localhost 已重定向您...
我正在应用 spring boot security。当我在当前代码中打开浏览器时,它会无限重定向到 \'http://localhost:8080/login\' 并显示错误 \'localhost 重定向您太多次。\'。由于 formLogin() 已被弃用,我使用了 lambda 表达式。
这是 CustomSecurityConfig 代码:
package edu.library.libraryspringboot.config;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Log4j2
@Configuration
@RequiredArgsConstructor
public class CustomSecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
log.info("-----------------configuration---------------------");
//http.formLogin();
http
.authorizeHttpRequests(authorize -> {
authorize
.anyRequest().authenticated();
})
.formLogin(formLogin -> {
formLogin
.loginPage("/login")
.permitAll();
});
return http.build();
}
@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
log.info("---------------web configuration---------------------");
return (web) -> web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}
}
这是 CustomUserDetailsService 代码。
package edu.library.libraryspringboot.security;
import org.springframework.security.core.userdetails.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Log4j2
@Service
public class CustomUserDetailsService implements UserDetailsService {
private PasswordEncoder passwordEncoder;
public CustomUserDetailsService() {
this.passwordEncoder = new BCryptPasswordEncoder();
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("loadUserByUsername: " + username);
UserDetails userDetails = User.builder()
.username("user1")
//.password("1111")
.password(passwordEncoder.encode("1111")) //Needs password encoding
.authorities("ROLE_USER")
.build();
return userDetails;
}
}
我想避免代码无限重定向。我应该如何修改代码才能看到登录页面?
先感谢您。