为什么我的Spring Security身份验证不起作用?

时间:2014-01-10 01:21:45

标签: java spring authentication spring-security restful-authentication

我在/src/main/java/com/dog/bootstrap中放置了以下配置:

@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        System.out.println("hello");
        auth.inMemoryAuthentication()
            .withUser("user")
            .password("password")
            .roles("USER");
    }
}

我按如下方式加载:

public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) {
    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
    dispatcherContext.scan("com.dog.bootstrap");

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(dispatcherContext));

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);

    Set<String> mappingConflicts = dispatcher.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'dispatcher' could not be mapped to '/' due " +
                "to an existing mapping.");
    }
}

我的控制器:

@Controller
public class DogController {
    @RequestMapping(value = {"/dog"}, method = RequestMethod.GET)
    @ResponseBody
    public String getSource(@PathVariable("domain") String domain) throws Exception {
        return "dogs";
    }
}

当我启动我的应用时,我确实看到正在打印hello,因此正在调用configure(AuthenticationManagerBuilder auth)。但是,我的终端都没有要求我进入登录页面。当我转到localhost:8080/dog时,它输出dogs而不要求我对自己进行身份验证。

1 个答案:

答案 0 :(得分:2)

您实际上并未包含过滤器链as described in the last step of this guide。尝试添加此默认初始值设定项,映射到/*

@Component public class SecurityWebApplicationInitializer 
    extends AbstractSecurityWebApplicationInitializer {
}