Search code examples
angularcorspreflight

Okta Api Access to fetch at "okta-api-url' from origin 'http://localhost:4200' has been blocked by CORS policy


getting given below error while trying to access the OKTA api could you please suggest the possible solution, in Angular

 Access to fetch at 'https://dev-99322141.okta.com/api/v1/authn' from origin
 'http://localhost:4200' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to 
fetch the resource with CORS disabled.

config/my-app-config.ts

export default {
    oidc: {
        clientId: '<client id which is get from OKTA API>',
        issuer: 'https://dev-<numbers>.okta.com/oauth2/default',
        redirectUri: 'http://localhost:4200/login/callback',
        scopes: ['openid', 'profile', 'email']
    }
}

login.component.ts

export class LoginComponent implements OnInit {

  oktaSignIn: any;

  constructor(private oktaAuthService: OktaAuthService) { 

    this.oktaSignIn = new OktaSignIn({
      logo:'assets/images/logo.png',
      baseUrl: myAppConfig.oidc.issuer.split('/oauth2')[0],
      clientId: myAppConfig.oidc.clientId,
      redirectUri: myAppConfig.oidc.redirectUri,
      authParams: {
        pkce: true,
        issuer: myAppConfig.oidc.issuer,
        scopes: myAppConfig.oidc.scopes
      }
    });
  }

  ngOnInit(): void {
    this.oktaSignIn.remove(); // remove if any previous elements over there

    this.oktaSignIn.renderEl({
      el: '#okta-sign-in-widget'}, // this name shouldb e same as dive tag id in login.component.html
      (response) =>  {
        if(response.status === 'SUCCESS') {
          this.oktaAuthService.signInWithRedirect();
        }
      },
      (error) => {
        throw error;
      }
    );
  }
}

what could be the the possible solution to allow cors to access the Okta URL, https://dev-99322141.okta.com/api/v1/authn by http://localhost:4200


Solution

  • I problem can be solved in OKTA configurations regarding headers or strict font. The API expects information in the header that you do not send. Or you forgot you sent it.