Application showing CORS error after sometime (AZURE AD)

Viewed 996

I am using Spring Boot + Azure AD + angular9 and using azure ad default provided api to get access to my application. After launching application Microsoft login appear -> verify creds -> show me my landing page. All api works fine. But after sometime (almost 5-6 mins) all api start failing. It showing CORS ERROR in browser console.

Access to XMLHttpRequest at 'https://login.microsoftonline.com/common/oauth2/authorize?response_type=code
&client_id=<client_id>
&scope=openid%20https://graph.microsoft.com/user.read&state=lZfrMwK0nx5kQDjO56DJsMTFhcuvDmU5o0-ZCvTPvI4%3D
&redirect_uri=https://{abc}.com/login/oauth2/code/azure&nonce=CCGwfpb4klAiPtEApCs3nS8ICod0-htdHWvBATNYfXs' 
  (redirected from 'https://{abc}.com/api/supplier/add') from origin
 'https://{abc}.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource.

for every api onwards it is showing CORSS ERROR

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://login.microsoftonline.com/common/oauth2/authorize?
response_type=code&client_id=<client_id>
&scope=openid%20https://graph.microsoft.com/user.read
&state=LAJfYfn9XFOISAHO4Cq4iA5_Dkya3CFDXKgQmQVfpxg%3D
&redirect_uri=https://{abc}.com/login/oauth2/code/azure
&nonce=IBF8nVnrWhH-SY9VpNxouZcxn_6JZEo3J_d-JBHTAK4. 
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

Here is my Web-Security-config

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Value("${logout.url}")
    String logoutUrl;
    
    @Value("${redirect.url}")
    String redirectUrl;
    
    @Autowired
    private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService;
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        String logoffUrl = logoutUrl+"?post_logout_redirect_uri="+URLEncoder.encode(redirectUrl, "UTF-8");
        
         http
         .csrf().disable()
             .authorizeRequests()
             .anyRequest().authenticated()
             .and()
             .oauth2Login()
             .userInfoEndpoint()
             .oidcUserService(oidcUserService);
         
         http.logout().logoutUrl("/api/logout")
            .invalidateHttpSession(true)
            .deleteCookies("JSESSIONID")
            .logoutSuccessUrl(logoffUrl) ;
    }

}

WebMvcConfig

@Configuration
public class WebMvcConfig implements WebMvcConfigurer{
    
    @Value("${spring.allowed.origin}")
    public String allowedOrigin;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
            .allowedOrigins(allowedOrigin)
            .allowedMethods("GET", "POST")
            .allowCredentials(true)
            .maxAge(3600);
    }
    
    
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setUrlDecode(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}

From angular side I am sending header like below

headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Credentials': 'true',
  });

Please help.. thanks

1 Answers

I implemented SPA using angular msal service. I use loginPopUp method to get login pop up provided by Microsoft. It solve my ADFS security issue also. Here I am not using any accessTokenSilent / accessTokenRedirect method to get access token after the previous token expire. I added CSP header in my nginx.conf file (web server conf file), so after the token expire it automatically providing me new access token on click of any api.

header for CSP added in nginx.conf file

add_header Content-Security-Policy "frame-ancestors 'self';"  always;
Related