首页 文章

spring security登录404

提问于
浏览
0

我正在探索一点 Spring 天 . 为了方便 endpoints ,我遇到了 Spring 季启动,请参阅:

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/sample")
    @ResponseBody
    String sample() {
        return "Hello sample!";
    }

    @RequestMapping("/sample2")
    @ResponseBody
    String sample2() {
        return "Hello sample secured!";
    }
}

从逻辑上讲, endpoints 可以在localhost:8181 / sample上访问

但是在使用spring security时,“受保护” endpoints 因为登录页面给我404而无法访问

login page gives me 404

我的安全类如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/sample" ).permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
                User.withDefaultPasswordEncoder()
                        .username("user")
                        .password("password")
                        .roles("USER")
                        .build();

        return new InMemoryUserDetailsManager(user);
    }
}

我可以访问 /sample ,因为没有受到保护 . 但无法访问 /sample2 ,因为它重定向到 /login

我根据本指南配置我的安全类:https://spring.io/guides/gs/securing-web/

2 回答

  • 2

    我可以访问/采样,因为没有受到保护 . 但重定向到/ login时无法访问/ sample2

    因为您没有在安全配置中绕过 /sample2 .

    .antMatchers("/sample2" ).permitAll()
    

    另一件事是,您已指定自定义登录页面

    .formLogin()
    .loginPage("/login")
    

    你必须提供一个登录页面 .

  • 0

    userDetailsService 注入 authenticationProvider

    @Bean
        public AuthenticationProvider authenticationProvider(){
            DaoAuthenticationProvider authenticationProvider=new CustomAuthenticationProvider();
            authenticationProvider.setUserDetailsService(userDetailsService());
            return authenticationProvider;
        }
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception{
            auth.authenticationProvider(authenticationProvider());
        }
    

    将此配置添加到spring安全性:

    .antMatchers("/sample2").hasRole("USER")
    

相关问题