Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom endpoint to serve files with OAuth active #1477

Closed
Jimmy-Newtron opened this issue Oct 24, 2024 · 2 comments
Closed

Add custom endpoint to serve files with OAuth active #1477

Jimmy-Newtron opened this issue Oct 24, 2024 · 2 comments
Labels
auth Pertaining to authentication.

Comments

@Jimmy-Newtron
Copy link

I am trying to figure out how to achieve my goal of serving private files (PDF, images, audio, videos, ...) that can be stored in a central S3 storage, by simply adding a custom endpoint with authentication (OAuth).

My actual setup returns an error 401 because the token is not part of the request to the server.

How can I ensure to have the token?

Copy link

dosubot bot commented Oct 24, 2024

Hey there, @Jimmy-Newtron! I'm here to help you with any bugs, questions, or contributions you have. Let's tackle this together!

To serve private files with OAuth authentication, you need to ensure that the authentication token is included in the request to your custom endpoint. Here's a step-by-step approach to achieve this:

  1. Create a Custom Endpoint: Use FastAPI to define a custom endpoint that serves the files. Ensure this endpoint requires authentication by checking for a valid token.

    from fastapi import FastAPI, Depends, HTTPException
    from fastapi.responses import FileResponse
    from your_auth_module import get_current_user
    
    app = FastAPI()
    
    @app.get("/serve-file")
    async def serve_file(file_path: str, user=Depends(get_current_user)):
        if not user:
            raise HTTPException(status_code=401, detail="Unauthorized")
        # Logic to fetch the file from S3
        return FileResponse(file_path)
  2. Modify the Frontend Component: In your PDFElement component, ensure that the token is included in the request. You can use the Fetch API or Axios to set custom headers.

    import React, { useEffect, useState } from 'react';
    import { useAuth } from 'path-to-your-auth-hook';
    
    const PDFElement = ({ element }) => {
      const { token } = useAuth();
      const [pdfUrl, setPdfUrl] = useState(null);
    
      useEffect(() => {
        if (element.url) {
          const fetchPdf = async () => {
            const response = await fetch(`/serve-file?file_path=${element.url}`, {
              headers: {
                'Authorization': `Bearer ${token}`
              }
            });
            if (response.ok) {
              setPdfUrl(element.url);
            } else {
              console.error('Failed to fetch PDF');
            }
          };
          fetchPdf();
        }
      }, [element.url, token]);
    
      if (!pdfUrl) return null;
    
      return <iframe src={pdfUrl} />;
    };
    
    export default PDFElement;
  3. Ensure Token Management: Use a state management solution like Recoil to manage the authentication token. The useAuth hook should provide access to the token, which is then used in the request headers.

By following these steps, you can ensure that the token is included in the request to your custom endpoint, allowing you to serve private files securely with OAuth authentication.

To continue talking to Dosu, mention @dosu.

@dosubot dosubot bot added the auth Pertaining to authentication. label Oct 24, 2024
@dokterbob
Copy link
Collaborator

Effectively a dup of #1101. We need to move towards cookie auth of the frontend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
auth Pertaining to authentication.
Projects
None yet
Development

No branches or pull requests

2 participants