简体   繁体   中英

Getting CORS error in GCP while IAP is enabled on App engine

We deployed the frontend(angular 14) and backend(python flask) in App Engine as a two different services and enabled IAP. IAP allows only the authorize user to access the web page.

When we hit the frontend endpoint, a google SSO page appears to do the authentication. Authorized users allowed to access the web page.

From the angular side we use library for SSO login https://www.npmjs.com/package/angular-oauth2-oidc to get authorized user details and BEARER token.

We are storing the BEARER token under the local storage.

localStorage.setItem("token",this.oAuthService.getIdToken());

BEARER token is added in the request HEADER when we interact the backend endpoint to authorize the user and to get the data.

token= localStorage.getItem('token')
  
  headers = new HttpHeaders({
  'Content-Type': 'application/json',
  'Cache-Control': 'no-cache',
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers": "X-Requested-With, Content-Type, Authorization",
      "Access-Control-Allow-Credentials": "true",
      "Authorization":"Bearer "+this.token,
      //'Authorization': `Bearer ${this.token}`

    })
postMonitoringDataById(monitoring: Monitoring){
   return this.http.post(environment.baseUrl+environment.MONITORING_SCREEN_DATA,monitoring,{ 
     headers: this.headers});


After applying the above functionality, we are getting a CORS error when we are sending a request to backend from front end (Error is shown below)

Access to XMLHttpRequest at 'https://python-end-point/getData' from origin 'http://angular-end-point' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Browser Error

In the backend we handled CORS policy

app = Flask(__name__)
#CORS(app)
cors = CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)

app.config['CORS_HEADERS'] = 'Content-Type'

@app.before_request
def basic_authentication():
    logger.info("preflight before request")
    if request.method.lower() == 'options':
        # return "OK",200
        return Response(status=200)
@app.after_request
def after_request(response):
    logger.info("set headers")
    # response.headers.add('Access-Control-Allow-Origin', '*')
    origin = request.headers.get('Origin')
    if origin:
        response.headers.set('Access-Control-Allow-Origin', origin)
    else:
        response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
    response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
    response.headers.add('Access-Control-Allow-Credentials', 'true')
    return response

@app.route('/getData', methods=["GET", "POST", "OPTIONS"])
def get_monitoring_screen_data():

Also for CORS error we added http headers in app.yaml file

handlers:
- url: /favicon.ico
  static_files: static/images/favicon.ico
  upload: static/images/favicon.ico
  http_headers:
    Access-Control-Allow-Origin: "*"
    Access-Control-Allow-Headers: "*"

When we check the GCP logs frontend request is not communicating the backend service. Flask app is not ran.

GCP log

GCP logs extended

When we are trying to send backend request from postman with BEAREAR token we are getting an excepted result.

Postman Log

GCP Postman Log

in further research we found document to solve the preflight option request.

Customizing IAP https://cloud.google.com/iap/docs/customizing

Below are the headers that i found in a GCP document GCP_IAP_UID GCP_IAAP_AUTH_TOKEN_87657E95ABB28982

Do we need to add this while making backend request.

By default the browser sends preflight request (OPTION Request) to backend. In flask i have handled the preflight request call by returning a response with status code 200, but still my flask service is not executing when i received a call from frontend. Options call does not have authorization header because of this we could not do authentication processes. I am not sure how to bypass the authorization process during OPTIONS call.

Kindly share your suggestions to solve this problem as i am new to the GCP

When you communicate with two different service, you have to enable HTTP option in IAP to avoid preflight CORS error.

You have covered the coding logic and you are in a final stage. The GCP document (as per your research) https://cloud.google.com/iap/docs/customizing is the correct one.

[HTTP Option][1]

The problem statement and the way of explaining the process and issue is really good. Keep it up.

Happy Coding !

Thanks

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