Skip to content

Conversation

JMLX42
Copy link
Contributor

@JMLX42 JMLX42 commented Sep 14, 2025

Summary

This PR implements support for using any type that implements Display for security scopes in #[utoipa::path] and #[openapi] macros, as requested in #1462.

Changes

  • Modified SecurityRequirementsAttrItem in security_requirement.rs to use LitStrOrExpr instead of just string literals for scopes
  • Updated parsing logic to accept both literals and expressions
  • Modified ToTokens implementation to call .to_string() on both literals and expressions to generate proper String values
  • Added comprehensive tests for both #[utoipa::path] and #[openapi] macros

Benefits

  • Type Safety: Compile-time validation of security scopes
  • Better Organization: Scopes can be defined as enums/structs with clear semantics
  • IDE Support: Autocomplete and refactoring tools work better with types
  • Maintainability: Centralized scope definitions that are easier to update
  • Backwards Compatible: String literals still work exactly as before

Example Usage

use std::fmt::Display;

enum Scope {
    Read,
    Write,
}

impl Display for Scope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Scope::Read => write!(f, "read:items"),
            Scope::Write => write!(f, "write:items"),
        }
    }
}

#[utoipa::path(
    get,
    path = "/items",
    responses(
        (status = 200, description = "success response")
    ),
    security(
        ("oauth2" = [Scope::Read, Scope::Write])
    )
)]
fn get_items() -> String {
    // ...
}

Testing

Added tests demonstrating:

  • Using enum types with Display implementation
  • Mixing string literals and Display types in the same security requirement
  • Backwards compatibility with existing string literal syntax
  • Support in both #[utoipa::path] and #[openapi] macros

All existing tests continue to pass without modification.

Closes #1462

Allow security scopes in `#[utoipa::path]` and `#[openapi]` macros
to accept any type that implements Display, not just string literals.

This enables more idiomatic Rust code where scopes can be represented
as enums or structs with Display implementations, providing:
- Type safety and compile-time validation
- Better IDE support with autocomplete
- Centralized scope definitions
- Full backwards compatibility with string literals

Example:
```rust
enum Scope { Read, Write }
impl Display for Scope { ... }

#[utoipa::path(
    security(("bearerAuth" = [Scope::Read, Scope::Write]))
)]
```

Closes juhaku#1462
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Support Display types for security scopes in path and openapi macros

1 participant