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

OpenApi security schemes support #144

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/aide/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ cfg-if = "1.0.0"
# custom axum extractors
serde_qs = { version = "0.13", optional = true }
jwt-authorizer = { version = "0.14", default-features = false, optional = true }
telegram-authorizer = { version = "0.1.0", default-features = false, optional = true }

[features]
macros = ["dep:aide-macros"]
Expand All @@ -52,6 +53,7 @@ axum-wasm = ["axum"]

serde_qs = ["dep:serde_qs"]
jwt-authorizer = ["dep:jwt-authorizer"]
telegram-authorizer = ["dep:telegram-authorizer"]

[dev-dependencies]
serde = { version = "1.0.144", features = ["derive"] }
Expand Down
51 changes: 24 additions & 27 deletions crates/aide/src/axum/inputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,14 @@
use crate::{
openapi::{
self, Header, MediaType, Operation, Parameter, ParameterData, ReferenceOr, RequestBody,
Response, SchemaObject, StatusCode,
Response, SchemaObject, SecurityScheme, StatusCode,
},
operation::{add_parameters, set_body},
};
use axum::{
body::Body,
extract::{
Extension, Form, Host, Json, MatchedPath, OriginalUri, Path, Query, RawQuery,
State,
Extension, Form, Host, Json, MatchedPath, OriginalUri, Path, Query, RawQuery, State,
},
};

Expand Down Expand Up @@ -410,6 +409,8 @@ mod extra {

#[cfg(feature = "jwt-authorizer")]
mod jwt_authorizer {
use std::any::type_name;

use super::*;
use crate::OperationInput;
use ::jwt_authorizer::JwtClaims;
Expand All @@ -419,31 +420,27 @@ mod jwt_authorizer {
ctx: &mut crate::gen::GenContext,
operation: &mut crate::openapi::Operation,
) {
let s = ctx.schema.subschema_for::<String>();
add_parameters(
ctx,
operation,
[Parameter::Header {
parameter_data: ParameterData {
name: "Authorization".to_string(),
description: Some("Jwt Bearer token".to_string()),
required: true,
format: crate::openapi::ParameterSchemaOrContent::Schema(
openapi::SchemaObject {
json_schema: s,
example: None,
external_docs: None,
},
),
extensions: Default::default(),
deprecated: None,
example: None,
examples: IndexMap::default(),
explode: None,
},
style: openapi::HeaderStyle::Simple,
}],
let t = "JWT Authorizer".to_string();
ctx.security_schemes.insert(
t.clone(),
ReferenceOr::Item(SecurityScheme::Http {
scheme: "bearer".to_string(),
bearer_format: Some("JWT".to_string()),
description: Some("A bearer token.".to_string()),
extensions: Default::default(),
}),
);

operation.security.push([(t, Vec::new())].into())
}
}
}

#[cfg(feature = "telegram-authorizer")]
mod telegram_authorizer {

use crate::OperationInput;
use ::telegram_authorizer::TelegramUser;

impl OperationInput for TelegramUser {}
}
10 changes: 7 additions & 3 deletions crates/aide/src/axum/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ use crate::{
util::merge_paths,
OperationInput, OperationOutput,
};
#[cfg(not(feature = "axum-wasm"))]
use axum::extract::connect_info::IntoMakeServiceWithConnectInfo;
use axum::{
body::Body,
handler::Handler,
Expand All @@ -185,8 +187,6 @@ use axum::{
routing::{IntoMakeService, Route, RouterAsService, RouterIntoService},
Router,
};
#[cfg(not(feature = "axum-wasm"))]
use axum::extract::connect_info::IntoMakeServiceWithConnectInfo;
use indexmap::map::Entry;
use indexmap::IndexMap;
use tower_layer::Layer;
Expand Down Expand Up @@ -361,7 +361,7 @@ where
}

fn merge_api(&mut self, api: &mut OpenApi) {
self.merge_api_with(api, |x| x)
self.merge_api_with(api, |x| x);
}
fn merge_api_with<F>(&mut self, api: &mut OpenApi, transform: F)
where
Expand Down Expand Up @@ -393,6 +393,10 @@ where

let components = api.components.get_or_insert_with(Default::default);

components
.security_schemes
.extend(ctx.security_schemes.drain());

components
.schemas
.extend(ctx.schema.take_definitions().into_iter().map(
Expand Down
11 changes: 8 additions & 3 deletions crates/aide/src/gen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,7 @@ pub fn on_error(handler: impl Fn(Error) + 'static) {
///
/// [`OpenApi`]: crate::openapi::OpenApi
pub fn extract_schemas(extract: bool) {
in_context(|ctx| {
ctx.set_extract_schemas(extract)
});
in_context(|ctx| ctx.set_extract_schemas(extract));
}

/// Set the inferred status code of empty responses (`()`).
Expand Down Expand Up @@ -105,6 +103,12 @@ pub struct GenContext {
/// for generating JSON schemas.
pub schema: SchemaGenerator,

/// Secutiry schemes descriptions.
pub security_schemes: std::collections::HashMap<
String,
crate::openapi::ReferenceOr<crate::openapi::SecurityScheme>,
>,

pub(crate) infer_responses: bool,

pub(crate) all_error_responses: bool,
Expand Down Expand Up @@ -134,6 +138,7 @@ impl GenContext {

let mut this = Self {
schema: SchemaGenerator::new(SchemaSettings::draft07()),
security_schemes: std::collections::HashMap::new(),
infer_responses: true,
all_error_responses: false,
extract_schemas: true,
Expand Down
9 changes: 6 additions & 3 deletions crates/aide/src/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,10 @@ impl<'t> TransformOperation<'t> {
{
in_context(|ctx| {
if let Some(mut res) = R::operation_response(ctx, self.operation) {
let responses = self.operation.responses.get_or_insert_with(Default::default);
let responses = self
.operation
.responses
.get_or_insert_with(Default::default);
if responses.default.is_none() {
let t = transform(TransformResponse::new(&mut res));

Expand Down Expand Up @@ -838,7 +841,7 @@ impl<'t> TransformOperation<'t> {
let t = callback_transform(TransformCallback::new(p));

if t.hidden {
callbacks.remove(callback_url);
callbacks.swap_remove(callback_url);
if self
.operation
.callbacks
Expand All @@ -848,7 +851,7 @@ impl<'t> TransformOperation<'t> {
.unwrap()
.is_empty()
{
self.operation.callbacks.remove(callback_name);
self.operation.callbacks.swap_remove(callback_name);
}
}

Expand Down
Loading