CORS 策略阻止了 Okta Api 从源“http://localhost:4200”获取“okta-api-url”的访问权限

时间:2021-03-05 20:14:56

标签: angular cors preflight

在尝试访问 OKTA api 时出现以下错误,请您在 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']
    }
}

登录.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;
      }
    );
  }
}

允许 cors 通过 http://localhost:4200 访问 Okta URL https://dev-99322141.okta.com/api/v1/authn 的可能解决方案是什么

1 个答案:

答案 0 :(得分:-1)

我的问题可以在关于标题或严格字体的 OKTA 配置中解决。 API 需要您不发送的标头中的信息。或者你忘记寄了。