2

我有以下的配置放在/src/main/java/com/dog/bootstrap爲什麼我的Spring Security身份驗證不起作用?

@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而不要求我認證我自己。

回答

2

你實際上並不包括過濾器鏈,as described in the last step of this guide。嘗試添加此默認初始值設定項,其映射到/*

@Component public class SecurityWebApplicationInitializer 
    extends AbstractSecurityWebApplicationInitializer { 
} 
+0

就是這樣!謝謝 :) – Popcorn