-2

I'm trying to call a secure Resource. I use @CrossOrigin(origins = "*") in all rest controllers. But I get cross origin error

I can't call "http://localhost:8081/ifrs/api/v1/period" with "GET" method But I can call "getJwtToken" because it's not scure.

my config is:

@Configuration
public class SecuirtyConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtFilter jwtFilter;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        http
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers("/ifrs/api/v1/user/token").permitAll()
            
            .anyRequest().authenticated()
            
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            
            .and()
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)         
            ;
        
        
        http.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
        
    }
    
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
        
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
    
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    
}

and JWT config:

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDomainService userDomainService;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request, 
            HttpServletResponse response, 
            FilterChain filterChain) throws ServletException, IOException {
        
        try {
            
            String token = request.getHeader("Authorization");
            
            String jwtToken = null;
            if ( token != null ) {
                
                if ( token.startsWith("Bearer ") ) {
                    
                    jwtToken = token.replace("Bearer ", "");
                    
                    String username = jwtUtils.getUsername(jwtToken);
                    username = username.trim();

                    // isUserAuthentication
                    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

                    if (username != null && authentication == null) {
                        User user = (User) userDomainService.loadUserByUsername(username);
                        
                        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                        
                        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    }
                    
                } else if ( token.startsWith("Basic ") ) {
                    
                    jwtToken = token.replace("Basic ", "");
                    
                    Base64 codec = new Base64();
                    byte[] decoded = codec.decode(jwtToken);
                    
                    String[] userAndPass = new String(decoded).split(":");
                    String username = userAndPass[0];
                    String password = userAndPass[1];
                    
                    request.setAttribute("username", username);
                    request.setAttribute("password", password);
                    
                }
                
            }

            filterChain.doFilter(request, response);

        } catch (ExpiredJwtException e) {
            throw e;

        } catch (Exception e) {
            throw e;
            
        }
        
    }

}

enter image description here

enter image description here

I test all ways to fix it. @CrossOrigin(origins = "*") is only working for not secure Resources. how to fixe it?

thanks

mehnet ali
  • 73
  • 3
  • 12
  • My answer has ```allowedHeader``` and ```tMatchers(HttpMethod.OPTIONS)```. But there is not a reference for a complete answer – mehnet ali Sep 06 '22 at 06:06
  • Hendy Irawan's answer contains `allowedHeader` and another answer contains it, too. `.antMatchers(HttpMethod.OPTIONS).permitAll()` is not neccessary, because the CORS filter is executed before the authorization filter and breaks the filter chain. – dur Sep 06 '22 at 06:54

1 Answers1

-1

I changed my code

class SecuirtyConfig --> corsConfigurationSource :

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.addAllowedHeader("*");    // new Line
    configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

and configure(HttpSecurity http) :

.cors().and()
    .csrf().disable()
    .authorizeRequests()
    .antMatchers(HttpMethod.OPTIONS).permitAll()
    .antMatchers("/ifrs/api/v1/user/token").permitAll()

thanks

mehnet ali
  • 73
  • 3
  • 12