0

我无法让 spring-security 显示我自己的登录页面。我已经尝试了几乎所有可用的解决方案。我不知道我的代码有什么问题。

下面是我已经尝试过的代码和代码中的注释部分。

SpringBoot 版本 - 2.1.5

安全配置类

@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 禁用它自己的默认登录页面并显示我的登录页面。

4

2 回答 2

0

需要配置WebMvcConfigurer

添加以下类作为您的配置并覆盖方法 addViewControllers

@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()
于 2019-06-11T07:04:02.130 回答
-1

好吧,这很奇怪,但我刚刚创建了一个新项目,将旧项目文件复制到新项目中,并按预期工作。

于 2019-06-13T05:47:51.540 回答