Spring引导休息外部tomcat 401错误

时间:2018-03-27 18:28:10

标签: spring tomcat spring-boot

我有一个Spring boot REST应用程序,在嵌入式tomcat上运行时效果很好。但是,只要我在外部tomcat上部署它,它就会为登录请求提供401

我关注https://www.mkyong.com/spring-boot/spring-boot-deploy-war-file-to-tomcat/并且能够在tomcat上部署。

@SpringBootApplication
@EnableJpaAuditing
public class Application  extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder         application) {
        return application.sources(Application.class);
    }

}

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

  @Autowired
  private EntryPointUnauthorizedHandler unauthorizedHandler;

  @Autowired
  private UserDetailsService userDetailsService;

  @Autowired
  private SecurityService securityService;

  @Autowired
  public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
      .userDetailsService(this.userDetailsService)
        .passwordEncoder(passwordEncoder());
  }

  @Bean
  public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
  }

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

  @Bean
  public AuthenticationTokenFilter authenticationTokenFilterBean() throws     Exception {
    AuthenticationTokenFilter authenticationTokenFilter = new     AuthenticationTokenFilter();
        authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean());
return authenticationTokenFilter;
  }

  @Bean
  public SecurityService securityService() {
    return this.securityService;
  }

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
      .csrf()
        .disable()
      .exceptionHandling()
        .authenticationEntryPoint(this.unauthorizedHandler)
        .and()
      .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
      .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .antMatchers("/auth/**").permitAll()
        .anyRequest().authenticated()
         .and()
      .cors();

    // Custom JWT based authentication
    httpSecurity
      .addFilterBefore(authenticationTokenFilterBean(),     UsernamePasswordAuthenticationFilter.class);
  }

}

登录时的回复

{
"timestamp": 1522175007525,
"status": 401,
"error": "Unauthorized",
"message": "Access Denied",
"path": "/test-app/api/auth"

}

1 个答案:

答案 0 :(得分:0)

我能够通过更改上下文路径来解决问题。

在application.properties文件中,我已经设置了

server.contextPath=/api

但tomcat完全忽略了它,最终路径从app / api / service更改为app / service

休息一切正常