如何禁用Spring Security默认登录/登录页面?

时间:2019-06-11 05:31:10

标签: java spring-boot spring-security

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

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

SpringBoot版本-2.1.5

SecurityConfig.class

@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());
}

}

View Controller类:

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

2 个答案:

答案 0 :(得分: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()

答案 1 :(得分:0)

好吧,它很奇怪,但是我刚刚创建了一个新项目,将旧项目文件复制到新文件中,并且可以正常工作。