简体   繁体   English

Spring 引导 2 和安全性与 JWT 无法提供 static 内容 ZD18B8624A0F5F721DADD7B823

[英]Spring Boot 2 and Security With JWT is unable to serve static content of angular build

I am building spring boot application with spring security and JWT authentication token, it was running fine only when i serve rest apis only, but now i want to host angular files also, so i added angular build in spring boot's executable war at /WEB-INF/classes/static/, now i want host all files in static directory should be accessible from / I tries lot of things, below is my code I am building spring boot application with spring security and JWT authentication token, it was running fine only when i serve rest apis only, but now i want to host angular files also, so i added angular build in spring boot's executable war at /WEB- INF/classes/static/,现在我想托管 static 目录中的所有文件应该可以从 / 我尝试了很多东西,下面是我的代码

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(
    securedEnabled = true,
    jsr250Enabled = true,
    prePostEnabled = true
)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
CustomUserDetailsService customUserDetailsService;

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;

@Bean
public JwtAuthenticationFilter jwtAuthenticationFilter() {
    return new JwtAuthenticationFilter();
}

@Override
public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
    authenticationManagerBuilder
            .userDetailsService(customUserDetailsService)
            .passwordEncoder(passwordEncoder());
}

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

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

//    @Override
//    public void configure(WebSecurity web) throws Exception {
//                web.ignoring().requestMatchers().antMatchers("/static/**").antMatchers("/api/auth/**");
//    }

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
//                .cors()
//                    .and()
//                .csrf()
//                    .disable()
//                .exceptionHandling()
//                    .authenticationEntryPoint(unauthorizedHandler)
//                    .and()
//                .sessionManagement()
//                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
//                    .and()
//                .requestMatchers().antMatchers("/static/**").and()
            .authorizeRequests()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .antMatchers("/api/auth/**")
                    .permitAll()
                .antMatchers("/api/user/checkUsernameAvailability", "/api/user/checkEmailAvailability")
                    .permitAll()
                .antMatchers("/api/test/**")
                    .permitAll()
                .antMatchers("/", "/static/**")
                    .permitAll()
                .anyRequest()
                    .authenticated();

    // Add our custom JWT security filter
    http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

}

WebMvcConfig is WebMvcConfig 是

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

private final long MAX_AGE_SECS = 3600;

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedOrigins("*")
            .allowedMethods("HEAD", "OPTIONS", "GET", "POST", "PUT", "PATCH", "DELETE")
            .maxAge(MAX_AGE_SECS);
}

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    // TODO Auto-generated method stub
    
}

@Override
public void addFormatters(FormatterRegistry registry) {
    // TODO Auto-generated method stub
    
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
    // TODO Auto-generated method stub
    
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//      registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static");
}

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
    // TODO Auto-generated method stub
    
}

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
    // TODO Auto-generated method stub
    
}

@Override
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    // TODO Auto-generated method stub
    
}

@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    // TODO Auto-generated method stub
    
}

@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    // TODO Auto-generated method stub
    
}

@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
    // TODO Auto-generated method stub
    
}

@Override
public Validator getValidator() {
    // TODO Auto-generated method stub
    return null;
}

@Override
public MessageCodesResolver getMessageCodesResolver() {
    // TODO Auto-generated method stub
    return null;
}


}

JwtAuthenticationFilter JwtAuthenticationFilter

public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Autowired
private JwtTokenProvider tokenProvider;

@Autowired
private CustomUserDetailsService customUserDetailsService;

private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
    try {
        String jwt = getJwtFromRequest(request);

        if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
            String userId = tokenProvider.getUserIdFromJWT(jwt);

            /*
                Note that you could also encode the user's username and roles inside JWT claims
                and create the UserDetails object by parsing those claims from the JWT.
                That would avoid the following database hit. It's completely up to you.
             */
            UserDetails userDetails = customUserDetailsService.loadUserById(userId);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                    userDetails, null, userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
    } catch (Exception ex) {
        logger.error("Could not set user authentication in security context", ex);
    }

    filterChain.doFilter(request, response);
}

private String getJwtFromRequest(HttpServletRequest request) {
    String bearerToken = request.getHeader("Authorization");
    if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
}

There might be the need for more context on your side but here is one possible solution.您可能需要更多上下文,但这是一种可能的解决方案。

I think that what might be happening is Spring is serving your content from the static folder /static as you are telling us (it's even a default spring boot folder).我认为可能发生的事情是 Spring 正在从 static 文件夹 /static 正如您告诉我们的那样提供您的内容(它甚至是默认的 spring 引导文件夹)。

But spring doesn't know that it needs to redirect the request from for example: localhost:8080/ to localhost:8080/index.html .但是 spring 不知道它需要将请求从例如: localhost:8080/重定向到localhost:8080/index.html

Note: Without further detail its hard to understand what might be happening:)注意:如果没有进一步的细节,很难理解可能发生的事情:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM