2015-10-02 42 views
2

我尝试创建使用的球衣和春季安全SpringBoot应用。 我想用基本认证来保护我的整个应用程序。 我的安全配置:春季启动与新泽西基本验证总是404

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(jsr250Enabled = true, securedEnabled = true, prePostEnabled = true) 
public class WebSerucityConfig extends WebSecurityConfigurerAdapter { 
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
    http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); 
    @Override 
    public void configure(WebSecurity web) throws Exception { 
     web.debug(true); 
    } 

    @Autowired(required = false) 
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { 
     auth 
      .inMemoryAuthentication() 
      .withUser("user").password("password").roles("USER").and() 
      .withUser("admin").password("password").roles("USER", "ADMIN"); 
    } 
} 

我的球衣控制器:

@Component 
@Path("/") 
public class Home { 

    @GET 
    @Produces("application/json") 
    public String list() { 
     String email = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); 
     return email; 
    } 
} 

没有春季安全(如果我允许所有的请求),应用控制器运行,但如果我能httpBasic验证我总是HTTP 404。

有什么想法?

回答

4

这是因为新泽西州和Spring MVC是映射到相同的地方 - 到根上下文“/”。

检查日志:春天的分派Servlet是新泽西州的Servlet(检查你的日志ServletRegistrationBean短语)后注册。

和情景是:

  1. 您使用curl
  2. 新泽西试图处理你的请求,但HTTP 401错误未经授权出现
  3. 现在的Spring MVC试图处理您的请求发送例如请求
  4. 但是你还没有在Spring MVC中配置这个特定的上下文,所以Http Error 404没有出现

这就是为什么你总是有这404

最简单的解决方法是在你的application.properties

server.servlet-path=/some_context_for_spring_mvc 

它使泽西将被映射到根“/”,但添加属性的Spring MVC到some_context_for_spring_mvc - 现在Jersey和Spring MVC之间的冲突消失了。在春季启动关于Spring MVC

更多细节,你可以在这里找到:

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-switch-off-the-spring-mvc-dispatcherservlet

春季启动要满足您的应用程序的根目录的所有内容/向下。如果你宁愿自己的servlet映射到URL,你可以做到这一点,当然,你可能会失去一些其他引导MVC功能。要添加自己的servlet和其映射到根资源只是申报类型的Servlet的@Bean,并给它特殊的bean名字的DispatcherServlet(如果你想将其关闭,您还可以创建不同类型的具有该名称的bean并不能取代它)。

我希望这会有所帮助。