[Python] FastAPI social authorization error:...

Discussão em 'Python' iniciado por Stack, Março 23, 2025.

  1. Stack

    Stack Membro Participativo

    When im trying to create social authentication using google I got error:

    authlib.integrations.base_client.errors.MismatchingStateError: mismatching_state: CSRF Warning! State not equal in request and response.

    I have already tried to use incognito and change configuration using authorize_state and server_metadata_url insted of authorize_url and access_token_url.

    I have debuged the state value in my routers and its look same:

    INFO:app.auth.routers:Generated state: 2oZOn1KlrZbJidnu7CbW4YmbH5bCyp
    INFO:app.auth.routers:Session state: 2oZOn1KlrZbJidnu7CbW4YmbH5bCyp
    INFO: 127.0.0.1:43082 - "GET /auth/google/login HTTP/1.1" 200 OK
    INFO:app.auth.routers:Session state: 2oZOn1KlrZbJidnu7CbW4YmbH5bCyp
    INFO:app.auth.routers:Received state: 2oZOn1KlrZbJidnu7CbW4YmbH5bCyp


    my routers:


    @router.get("/{provider}/login")
    async def social_login_start(
    provider: str,
    request: Request,
    auth_service: SocialAuth = Depends(SocialAuthFactory.get_social_auth)
    ):
    redirect_uri = f"{settings.BASE_URL}/auth/{provider}/callback"
    auth_url_data = await auth_service.client.create_authorization_url(redirect_uri=redirect_uri)
    request.session["state"] = auth_url_data["state"]

    logger.info(f"Generated auth URL: {auth_url_data['url']}")
    logger.info(f"Generated state: {auth_url_data['state']}")
    logger.info(f"Session state: {request.session['state']}")

    return {"url": auth_url_data["url"]}

    @router.get("/{provider}/callback")
    async def social_callback(
    provider: str,
    request: Request,
    auth_service: SocialAuth = Depends(SocialAuthFactory.get_social_auth)
    ):
    state = request.session.get("state")
    logger.info(f"Session state: {state}")
    logger.info(f"Received state: {request.query_params.get('state')}")
    if not state or state != request.query_params.get("state"):
    raise HTTPException(status_code=400, detail="Invalid state parameter")
    token = await auth_service.client.authorize_access_token(request, state=state)
    logger.info(f"Received token: {token}")
    user = await auth_service.authenticate_user(token)
    access_token = SecurityService.create_access_token(data={"sub": user.email})
    request.session.pop("state", None)
    return {"access_token": access_token, "token_type": "Bearer"}

    Continue reading...

Compartilhe esta Página