简体   繁体   中英

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

@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

@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

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).

But spring doesn't know that it needs to redirect the request from for example: localhost:8080/ to localhost:8080/index.html .

Note: Without further detail its hard to understand what might be happening:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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