Java 如何禁用spring安全默认登录/登录页面?
我无法使spring security显示我自己的登录页面。我尝试了几乎所有可用的解决方案。我不知道我的代码出了什么问题 下面是我已经尝试过的代码和代码中的注释部分 SpringBoot版本-2.1.5 SecurityConfig.classJava 如何禁用spring安全默认登录/登录页面?,java,spring-boot,spring-security,Java,Spring Boot,Spring Security,我无法使spring security显示我自己的登录页面。我尝试了几乎所有可用的解决方案。我不知道我的代码出了什么问题 下面是我已经尝试过的代码和代码中的注释部分 SpringBoot版本-2.1.5 SecurityConfig.class @EnableWebSecurity @ComponentScan public class SecurityConfig extends WebSecurityConfigurerAdapter { @Bean public UserDetailsS
@EnableWebSecurity
@ComponentScan
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService(){
return super.userDetailsService();
}
@Override
public void configure(HttpSecurity httpSecurity) throws Exception{
httpSecurity.
authorizeRequests()
.antMatchers("/resources/**","/login", "/home").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").permitAll()
.defaultSuccessUrl("/user/dashboard")
.failureUrl("/login-error")
.and().logout().permitAll();
//////////// Tried this too /////////////////////////////////////
// httpSecurity.cors().disable()
// .csrf().disable()
// .httpBasic().disable()
// .authorizeRequests().antMatchers("/**").permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception{
authenticationManagerBuilder.userDetailsService(userDetailsService()).passwordEncoder(new BCryptPasswordEncoder());
}
}
视图控制器类:
@Controller
@RequestMapping("/")
public class ViewController {
@Autowired
UserRepository userRepository;
@RequestMapping(value = {"/home"})
public String showHome(){ return "home.html";}
@GetMapping(value = "/login")
public String showLogin(){
return "login.html";
}
我希望spring security禁用自己的默认登录页面并显示我的登录页面。您需要配置WebMVCConfiguer 添加以下类作为配置,并重写addViewController方法
@EnableWebMvc
@Configuration
public class WebConfiguration implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/");
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
之后,允许在安全配置中访问您的资源
http.authorizeRequests().antMatchers("/resources/**", "/css/**", "/js/**", "/img/**").permitAll()
嗯,这很奇怪,但我刚刚创建了一个新项目,将旧项目文件复制到新项目中,并按预期工作。@Ankit Spring boot version 2.1.5请使用Spring boot 1.5版本尝试您的更改。我在2.1.5版上所做的更改也不起作用。通过添加此项,是否会对获取视图造成混乱??因为我有ViewController.class,它对每个视图都有映射。此外,我没有
WEB-INF
文件夹。您需要触发自定义登录页而不是默认的spring boot登录,以便可以从ViewController中删除控制器方法。并确保您的登录页在根路径中可用。假设您的thymeleaf在resources/static/login.htmlading解决方案中可用,它的行为仍然相同。此外,我的登录页位于根路径。那么您的资源将无法访问。您是否通过覆盖addResourceHandlers注册了上述ResourceHandlerRegistry?我也编辑了我的答案。