最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

cors - Why is my FastAPI endpoint not saving an HTTPonly Cookie using Fetch? - Stack Overflow

programmeradmin2浏览0评论

The question says it all, I feel like I've read everything I can and I am still no further forwards. The current situation is:

  • Enter api.mydomain into a browser directly does save my cookie
  • Using Fetch from my index.html from my portal.mydomain does not.

I have no CORS errors and the OPTIONS, GET and POST requests all get a 200 response. The payload in FastAPI is being correctly received as I can see the JSON data payload, just no cookie, nor can I see the cookie set in my broswer dev tools.

In my HTML file I have the following:

    fetch(';count=2', {
    method: 'GET',
    credentials: 'include',
    headers: {
        "Access-Control-Allow-Origin": ";
    }
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
    

const payload = {
    "email": "[email protected]",
    "password": "password",
    "csrf": "csrf"
}
const jsonData = JSON.stringify(payload);

fetch('', {
    method: 'POST',
    credentials: 'include',
    headers: {
        "Access-Control-Allow-Origin": ";,
        "Content-Type": "application/json"
    },
    body: jsonData
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));

My router looks like this for API:

@router.get("/cookie")
def set_cookie(response: Response):
    # Set an HttpOnly cookie
    response.set_cookie(
        key="testCookie",
        value="testCookieValue",
        httponly=True,  # This makes the cookie HttpOnly
        secure=True,    # Use secure cookies in production
        samesite="none"  # Adjust based on your needs
    )
    return {"message": "Cookie has been set2"}

My initial FastAPI config looks like this:

origins = [
    ";,
    ";,
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=[
        "Content-Type", 
        "Authorization", 
        "X-Requested-With", 
        "Access-Control-Request-Method", 
        "Access-Control-Request-Headers",
        "Access-Control-Allow-Origin"],
    
)

I'm not sure what else to try.

The question says it all, I feel like I've read everything I can and I am still no further forwards. The current situation is:

  • Enter api.mydomain into a browser directly does save my cookie
  • Using Fetch from my index.html from my portal.mydomain does not.

I have no CORS errors and the OPTIONS, GET and POST requests all get a 200 response. The payload in FastAPI is being correctly received as I can see the JSON data payload, just no cookie, nor can I see the cookie set in my broswer dev tools.

In my HTML file I have the following:

    fetch('https://api.mydomain/api/v1/forms/cookie?category=all&count=2', {
    method: 'GET',
    credentials: 'include',
    headers: {
        "Access-Control-Allow-Origin": "https://portal.mydomain"
    }
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
    

const payload = {
    "email": "[email protected]",
    "password": "password",
    "csrf": "csrf"
}
const jsonData = JSON.stringify(payload);

fetch('https://api.mydomain/api/v1/forms/auth', {
    method: 'POST',
    credentials: 'include',
    headers: {
        "Access-Control-Allow-Origin": "https://portal.mydomain",
        "Content-Type": "application/json"
    },
    body: jsonData
})
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));

My router looks like this for API:

@router.get("/cookie")
def set_cookie(response: Response):
    # Set an HttpOnly cookie
    response.set_cookie(
        key="testCookie",
        value="testCookieValue",
        httponly=True,  # This makes the cookie HttpOnly
        secure=True,    # Use secure cookies in production
        samesite="none"  # Adjust based on your needs
    )
    return {"message": "Cookie has been set2"}

My initial FastAPI config looks like this:

origins = [
    "https://portal.mydomain",
    "https://api.mydomain",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=[
        "Content-Type", 
        "Authorization", 
        "X-Requested-With", 
        "Access-Control-Request-Method", 
        "Access-Control-Request-Headers",
        "Access-Control-Allow-Origin"],
    
)

I'm not sure what else to try.

Share Improve this question edited Feb 15 at 15:17 Chris 34.3k10 gold badges99 silver badges234 bronze badges asked Feb 15 at 10:46 Johnny John BoyJohnny John Boy 3,2846 gold badges33 silver badges56 bronze badges 4
  • 1 Regardless of the issue, please take a look at this answer, as it could prove helpful to you. – Chris Commented Feb 15 at 15:05
  • what's the reason of setting samesite to none - it doesn't seem that you need it. Are you aware of the risks? – Chris Commented Feb 15 at 15:31
  • 1 This (and the references included) might be helpful as well. – Chris Commented Feb 15 at 15:31
  • Thanks @Chris they were helpful links. I set it at none just to see if this was the cause, since I've the domain= to the response, I managed to set it more securely. – Johnny John Boy Commented Feb 17 at 10:10
Add a comment  | 

1 Answer 1

Reset to default 4

This has nothing to do with CORS. The issue is that by default, a cookie set on api.mydomain is not available on any other subdomain, such as portal.mydomain. To make a cookie available on all subdomains, you must explicitly set the domain to .mydomain:

@router.get("/cookie")
def set_cookie(response: Response):
    # Set an HttpOnly cookie
    response.set_cookie(
        key="testCookie",
        value="testCookieValue",
        httponly=True,
        secure=True,
        samesite="none",
        domain=".mydomain",
    )
    return {"message": "Cookie has been set2"}
发布评论

评论列表(0)

  1. 暂无评论