Skip to content

Routes at same level with different auth* requirements #382

@kentcb

Description

@kentcb

Hello,

How does one define distinct routes at the same level of the hierarchy with different authentication/authorization requirements? For example, how would one define the following:

  • /api/v1/ping : completely open, non-authenticated
  • /api/v1/user_info : requires authentication, but not authorization
  • /api/v1/stats : requires authentication and authorization as administrator

Sorry if I'm being dumb, but I spent quite a bit of time last night trying various things to achieve this and came up short. Here's about the closest I could get:

let apiPipeline =
    pipeline {
        plug acceptJson
    }

let authenticatedApiPipeline =
    pipeline {
        requires_authentication (Giraffe.Auth.challenge JwtBearerDefaults.AuthenticationScheme)
    }

let v1AuthenticatedApiRouter =
    router {
        pipe_through authenticatedApiPipeline

        forward "/user_info" (setStatusCode 200 >=> text "TODO: user info")
    }

let v1ApiRouter =
    router {
        forward "/ping" (setStatusCode 200 >=> text "pong")

        forward "" v1AuthenticatedApiRouter
    }

let apiRouter =
    router {
        not_found_handler (setStatusCode 404 >=> text "API 404")
        pipe_through apiPipeline

        forward "/v1" v1ApiRouter
    }

This already felt hacky to me, and I could see no way to extend it further to accommodate authorized routes as well. Is there a way to achieve this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions