question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

using Security scopes with sqladmin endpoint /admin

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

none

Description

I have tried to follow fastapi portal docs to set up authentication/authorization.
authentication: https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ authorization: https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/

when user visits the app main page like http://localhost:8000 if there is not JWT token then he is redirected to login page. Once login happens he comes to dashboard page. The /admin is not protected so am looking for way to send him back to login page and only if he has game:admin scope he can come to admin page.

I read about Middleware and seems simple enough.

https://fastapi.tiangolo.com/tutorial/middleware/

using above middleware docs I have to do things manually but way I have been able to use Security in signature and do those check for me I wanted to hook that into /admin endpoint. Actually if no JWT token he should be send to login page that is also not happening my entry page is /.

hypothetically I wanted below /admin endpoint setup (actual are down later).

@app.get("/admin", response_class=Response)
def setup(request: Request,  
         current_user: User = 
         Security(get_current_active_user, scopes=["game:admin"])):

here are snippets to give you some idea. I am not using any middleware which I saw in some discussions where you suggesting to use.

main.py

app = FastAPI()
setup_admin(app)


@app.get("/", response_class=HTMLResponse)                                      
def show_login(request: Request):                                               
    """                                                                         
      show login.html called non-Ajax mode like redirect.                       
    """                                                                         
    return templates.TemplateResponse("login.html", {                           
             "request": request                                                 
            })          

@app.post("/token", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = 
        Depends()):
    #user = authenticate_user(fake_users_db, form_data.username, form_data.password)
    user = authenticate_user(get_db(), form_data.username, form_data.password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer", "HX-Rdirect": "/"}

@app.delete("/game/{id}", response_class=Response)
def delete_game(request: Request, id: int, 
        otp: str = fastapi.Form(default=None),
         db: Session = Depends(get_db),
         current_user: User = 
         Security(get_current_active_user, scopes=["game:delete"])):

admin.py

from models import User
from mysqldb import engine

from sqladmin import Admin, ModelView
from fastapi import FastAPI, Security, Request
from authjwt import get_current_active_user




#class AuthModelView(ModelView):

#class UserAdmin(AuthModelView, model=User):
class UserAdmin(ModelView, model=User):
    column_list = [
            User.username, User.email, User.full_name, 
            User.hashed_password, User.disabled, 
            User.scopes
            ]

    def is_accessible(self, request: Request,
        current_user: User = 
        Security(get_current_active_user, scopes=["game:admin"])) -> bool:
        print(current_user)
        print("is_accessible");
        return True

    def is_visible(self, request: Request,
        current_user: User = 
        Security(get_current_active_user, scopes=["game:admin"])) -> bool:
        print(current_user)
        print("is_visible");
        return True

def setup_admin(app: FastAPI):
    admin = Admin(app, engine)
    admin.add_view(UserAdmin)

I attempted this I see the print statements above showing its output but the actual get_current_active_user is not getting called.

Operating System

Linux

Operating System Details

No response

FastAPI Version

0.75.0

Python Version

3.7.3

Additional Context

No response

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:8 (5 by maintainers)

github_iconTop GitHub Comments

1reaction
imitencommented, Sep 2, 2022

Security(get_current_active_user, scopes=[“game:admin”])) -> bool: that above line is used in oauth2-scopes. Security they mentioned in docs is like Depends and in main.py for endpoints its getting invoked fine.

1reaction
JarroVGITcommented, Aug 25, 2022

Please put in at least a very little effort in providing some information and a question? This is just a link to another discussion.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Use the Cloud SQL Admin API
Cloud SQL provides a REST API for administering your instances programmatically. The REST API is defined by BackupRuns, Databases, Instances, Flags, ...
Read more >
Azure SQL Database & Azure SQL Managed Instance
This article provides common security requirements and best practices in Azure SQL Database and Azure SQL Managed Instance.
Read more >
OAuth 2.0 Scopes for Google APIs | Authorization
Many scopes overlap, so it's best to use a scope that isn't sensitive. ... https://www.googleapis.com/auth/admin.directory.user.security ...
Read more >
Data access configuration | Databricks on AWS
To configure all warehouses to use an AWS instance profile when ... Settings at the bottom of the sidebar and select SQL Admin...
Read more >
Azure AD – How to use custom scopes for admin consent
In this post I show you how to configure this custom settings in Azure AD v2 endpoint with application manifest step-by-step. Permissions in ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found