3

I'm using BasePermission decorator as specified in documentation.

@strawberry.type
class Query:
    @strawberry.field(permission_classes=[IsAuthenticated])
    def user(self) -> User:
        # get by token OFC
        return User(user_id=1, email="vladimir@cw.tech", first_name = "Vladimir", last_name = "Kirilov")

In my impementation I use VerifyToken class as described in FastAPI auth0 documentation.

class IsAuthenticated(BasePermission):
    message = "User is not authenticated"

    def has_permission(self, source: Any, info: Info, **kwargs) -> bool:
        print(source)
        print(info)
        token: str = Depends(token_auth_scheme)
        print(token)
        result = VerifyToken(token.credentials).verify()
        if result.get("status"):
            print(result)
            return False

        return True

So I'm trying to get and verify the BEARER from the request, but I'm not able to extract it to process it further and get the error, please advise.

{
  "data": null,
  "errors": [
    {
      "message": "'Depends' object has no attribute 'credentials'",
      "locations": [
        {
          "line": 2,
          "column": 3
        }
      ],
      "path": [
        "user"
      ]
    }
  ]
}
Vladimir Stazhilov
  • 1,956
  • 4
  • 31
  • 63
  • You've moved the token retrieval from the function signature - FastAPI won't resolve random variables inside a method for you - those have to declared in some way through FastAPIs dependency hierarchy. You could probably just call the function/class directly instead of using `Depends` in this case? – MatsLindh Feb 21 '22 at 12:42
  • @MatsLindh hey thanks, but how should I extract the BEARER from GRAPHQL request? – Vladimir Stazhilov Feb 21 '22 at 12:43

1 Answers1

3

Figured it out, not the cleanest way, but here it is

class IsAuthenticated(BasePermission):
    message = "User is not authenticated"
    
    async def has_permission(self, source: Any, info: Info, **kwargs) -> bool:


        request: Union[Request, WebSocket] = info.context["request"]
        print(request.headers)
        if "Authorization" in request.headers:
            print(request.headers['Authorization'])
            result = VerifyToken( request.headers['Authorization'][7:] ).verify()
            if result.get("status") == "error":
                print(result.get("msg"))
                return False
            if result.get("sub"):
                print(result)
                return True
        return False
    
Vladimir Stazhilov
  • 1,956
  • 4
  • 31
  • 63