2015-06-12 3 views
1

У меня есть приложение загрузки Spring, которое используется как защищенный сервер REST API. Я хотел бы иметь статическую страницу с документацией об этом API (например, я бы хотел использовать Wiki)Spring Boot не отображает содержимое веб-сайта

Насколько я могу судить, я не могу заставить его отображать статическое содержимое: например. Я попытался с greeting example и вызовом http://localhost:8080/greeting он будет отображать «приветствия» (не служит greeting.html страницы)

Я подозреваю, что проблема связана с каким-то фильтром в Spring Security.

Это вызывается фильтр цепи

o.a.c.c.C.[Tomcat].[localhost].[/]  : Initializing Spring FrameworkServlet 'dispatcherServlet' 
o.s.web.servlet.DispatcherServlet  : FrameworkServlet 'dispatcherServlet': initialization started 
o.s.web.servlet.DispatcherServlet  : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms 
o.s.security.web.FilterChainProxy  : /greeting at position 1 of 7 in additional filter chain; firing Filter: 'HeaderWriterFilter' 
o.s.security.web.FilterChainProxy  : /greeting at position 2 of 7 in additional filter chain; firing Filter: 'StatelessLoginFilter' 
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/greeting'; against '/api/login' 
o.s.security.web.FilterChainProxy  : /greeting at position 3 of 7 in additional filter chain; firing Filter: 'StatelessAuthenticationFilter' 
o.s.security.web.FilterChainProxy  : /greeting at position 4 of 7 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' 
o.s.security.web.FilterChainProxy  : /greeting at position 5 of 7 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' 
o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.sprin[email protected]9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' 
o.s.security.web.FilterChainProxy  : /greeting at position 6 of 7 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' 
o.s.security.web.FilterChainProxy  : /greeting at position 7 of 7 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' 
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/greeting'; against '/' 
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/greeting'; against '/documentation' 
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/greeting'; against '/greeting' 
o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /greeting; Attributes: [permitAll] 
o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.sprin[email protected]9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.sprin[email protected]b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS 
o.s.s.access.vote.AffirmativeBased  : Voter: org.sp[email protected]58e65a6f, returned: 1 
o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful 
o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object 
o.s.security.web.FilterChainProxy  : /greeting reached end of additional filter chain; proceeding with original chain 
o.s.s.w.a.ExceptionTranslationFilter  : Chain processed normally 

Я поставил greeting.html файл как в SRC/основные/WebApp/WEB-INF/шаблонов и в SRC/главная/ресурсы/шаблоны, я пытался указать в application.properties

# For the standard MVC JSTL view resolver 
spring.view.prefix=/WEB-INF/templates/ 
spring.view.suffix=.html 

Я попытался с решениями, предложенными в этих StackOverflow: "Spring Boot not serving static content" и "spring boot not launching static web content", но ничего не изменилось ...

и, наконец, это WebSecurityConfigurerAdapter:

public class StatelessAuthenticationSecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private UserDetailsService userDetailsService; 

@Autowired 
private TokenAuthenticationService tokenAuthenticationService; 

@Autowired 
private LDAPAuthenticationService ldapAuthenticationService; 

@Value("${ldap.useLdapForAuthentication}") 
private String useLdapForAuthentication; 

public StatelessAuthenticationSecurityConfig() { 
    super(true); 

} 

@Override 
protected void configure(HttpSecurity http) throws Exception { 
    http 
      .exceptionHandling().and() 
      .anonymous().and() 
      .servletApi().and() 
      .headers().cacheControl().and() 
      .authorizeRequests() 

      //allow anonymous resource requests 
      .antMatchers("/").permitAll() 
      .antMatchers("/documentation").permitAll() 
      .antMatchers("/greeting").permitAll() 

      .antMatchers("/favicon.ico").permitAll() 
      .antMatchers("/resources/**").permitAll() 

      //allow anonymous POSTs to login 
      .antMatchers(HttpMethod.OPTIONS, "/api/login").permitAll() 
      .antMatchers(HttpMethod.POST, "/api/login").permitAll() 
      .antMatchers(HttpMethod.OPTIONS, "/api/**").permitAll() 
      .antMatchers(HttpMethod.POST, "/api/**").hasAnyRole("ADMIN", "USER") 
      .antMatchers(HttpMethod.GET, "/api/**").hasAnyRole("ADMIN", "USER") //e compagnia cantando 

      //defined Admin only API area 
      .antMatchers("/admin/**").hasRole("ADMIN") 

      //all other request need to be authenticated 
      .anyRequest().hasRole("USER") 
      .and()    

      // custom JSON based authentication by POST of {"username":"<name>","password":"<password>"} which sets the token header upon authentication 
      .addFilterBefore(new StatelessLoginFilter("/api/login", tokenAuthenticationService, userDetailsService, ldapAuthenticationService, authenticationManager(), useLdapForAuthentication), UsernamePasswordAuthenticationFilter.class) 

      // custom Token based authentication based on the header previously given to the client 
      .addFilterBefore(new StatelessAuthenticationFilter(tokenAuthenticationService), UsernamePasswordAuthenticationFilter.class); 
} 

@Bean 
@Override 
public AuthenticationManager authenticationManagerBean() throws Exception { 
    return super.authenticationManagerBean(); 
} 

@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); 
} 

@Override 
protected UserDetailsService userDetailsService() { 
    return userDetailsService; 
} 

}

.antMatchers ("/ ресурсы/**") permitAll() - Должен ли разрешить доступ даже к ресурсам/шаблоны

я на самом деле. не может понять, почему он не передает веб-контент Пожалуйста, не могли бы вы дать мне какой-нибудь намек?

EDIT1

Контроллер:

@RestController 
public class GreetingController { 

@RequestMapping("/greeting") 
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) { 
    model.addAttribute("name", name); 
    return "greeting"; 
} 
} 
+0

Добавить свой контроллер. –

ответ

1

Согласно Руководству Spring: Building a RESTful Web Service

Основное различие между традиционным контроллером MVC и RESTful контроллер веб-службы выше способ создания тела ответа HTTP . Вместо того, чтобы полагаться на технологию представления для выполнения серверной визуализации данных приветствия в HTML, этот RESTful web сервисный контроллер просто заполняет и возвращает объект Приветствие. Данные объекта будут записываться непосредственно в ответ HTTP как JSON.

Так что в вашем случае он возвращает «привет» в JSON. Если вы хотите, чтобы он возвращал страницу greeting.html, вы должны использовать обычный @Controller.

+0

вот и все ... как постыдно меня :) Я полностью пропустил это! большое спасибо – davidetrapani

Смежные вопросы