fastAPI credentials are missing for POST requests

69 Views Asked by At

server middleware config:

@app.middleware("http")
async def inspector(request: Request, call_next):
    print(f"{request.method} {request.url}")
    response = await call_next(request)
    return response

app.add_middleware(
    CORSMiddleware,
    allow_origins=[os.getenv('ORIGIN')],
    allow_credentials=True,
    allow_methods=["GET, POST, PUT, DELETE"],
    allow_headers=["*"],
    expose_headers=["*"]
)


@app.middleware('http')
async def auth(request: Request, call_next):
    print(request.cookies)
    return await call_next(request)

front (Angular):

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class Api {

  url = 'http://localhost:8000/'

  constructor(private http: HttpClient) { }

  get(ext: string): Observable<any[] | any> {
    return this.http.get(this.url + ext, { withCredentials: true });
  }

  post(ext: string, data: any): Observable<any[] | any> {
    return this.http.post(this.url + ext, data, { withCredentials: true });
  }

  put(ext: string, data: any): Observable<any[] | any> {
    return this.http.put(this.url + ext, data, { withCredentials: true });
  }

  delete(ext: string): Observable<any[] | any> {
    return this.http.delete(this.url + ext, { withCredentials: true });
  }

  errorHandler(e: Error, cb: Function = () => {}): void {
    console.log(e.message);
    cb()
  }
}

the cookies print alright on GET requests, but as an empty dict on POST requests. any ideas?

the error message i get for the post request is "Access to XMLHttpRequest at 'http://localhost:8000/commander/' 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."

thanks in advance

1

There are 1 best solutions below

0
On

adding this line solved the problem. the OPTIONS requests were (obviously, now) sent with no cookies and jammed the auth.

if request.method == 'OPTIONS':
        return await call_next(request)