[Rust/Rust Server] Fix example/test code (#19318)

* [Rust Server] Fix code so examples compile

Zero length arrays don't correctly type infer, so if we have no scopes, we need to not create a empty array

We need an authentication middleware - without it the code doesn't compile.

* Update samples

* [Rust Server] Remove trailing whitespace

* Update samples

* [Rust Server] [CI] Build all targets

* [Rust] Fix reqwest test
This commit is contained in:
Richard Whitehouse 2024-08-09 08:54:58 +01:00 committed by GitHub
parent 4b493358a8
commit ad7acc30eb
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 347 additions and 341 deletions

View File

@ -34,4 +34,4 @@ jobs:
toolchain: stable toolchain: stable
- name: Build - name: Build
working-directory: ${{ matrix.sample }} working-directory: ${{ matrix.sample }}
run: cargo build run: cargo build --all-targets

View File

@ -26,6 +26,7 @@ import io.swagger.v3.oas.models.media.XML;
import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.security.SecurityScheme;
import io.swagger.v3.oas.models.servers.Server; import io.swagger.v3.oas.models.servers.Server;
import joptsimple.internal.Strings; import joptsimple.internal.Strings;
import lombok.Setter; import lombok.Setter;
@ -1108,6 +1109,20 @@ public class RustServerCodegen extends AbstractRustCodegen implements CodegenCon
bundle.put("callbacks", callbackData); bundle.put("callbacks", callbackData);
} }
// Flag whether we have any OAuth scopes
Map<String, SecurityScheme> securitySchemeMap = openAPI.getComponents() != null ? openAPI.getComponents().getSecuritySchemes() : null;
List<CodegenSecurity> authMethods = fromSecurity(securitySchemeMap);
boolean hasAuthScopes = false;
if (authMethods != null && !authMethods.isEmpty()) {
for (CodegenSecurity authMethod : authMethods) {
if (authMethod.hasScopes != null && authMethod.hasScopes) {
hasAuthScopes = true;
break;
}
}
}
bundle.put("hasAuthScopes", hasAuthScopes);
return super.postProcessSupportingFileData(bundle); return super.postProcessSupportingFileData(bundle);
} }

View File

@ -51,7 +51,7 @@ fn main() {
{{#operation}} {{#operation}}
{{#vendorExtensions}} {{#vendorExtensions}}
{{^x-no-client-example}} {{^x-no-client-example}}
"{{{operationId}}}", "{{{operationId}}}",
{{/x-no-client-example}} {{/x-no-client-example}}
{{/vendorExtensions}} {{/vendorExtensions}}
{{/operation}} {{/operation}}
@ -80,24 +80,29 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
{{#authMethods}} {{#hasAuthScopes}}
{{#scopes}} [
{{#authMethods}}
{{#scopes}}
"{{{scope}}}", "{{{scope}}}",
{{/scopes}} {{/scopes}}
{{/authMethods}} {{/authMethods}}
].join(", ") ].join::<&str>(", ")
}, {{/hasAuthScopes}}
{{^hasAuthScopes}}
"".to_owned()
{{/hasAuthScopes}}
},
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use {{{externCrateName}}}::{AuthenticationApi, Claims}; use {{{externCrateName}}}::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,29 +15,35 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
{{#authMethods}} {{#hasAuthScopes}}
{{#scopes}} [
"{{{scope}}}", {{#authMethods}}
{{/scopes}} {{#scopes}}
{{/authMethods}} "{{{scope}}}",
].join(", ") {{/scopes}}
} {{/authMethods}}
].join::<&str>(", ")
{{/hasAuthScopes}}
{{^hasAuthScopes}}
"".to_owned()
{{/hasAuthScopes}}
}
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -68,8 +74,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -110,23 +116,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -12,7 +12,8 @@ fn test_types() {
double: 45.56, double: 45.56,
string: String::from("something"), string: String::from("something"),
boolean: true, boolean: true,
uuid: Uuid::new_v4() uuid: Uuid::new_v4(),
bytes: vec![1,2,3,4]
}; };
assert_eq!(type_of(tt.int32), "i32"); assert_eq!(type_of(tt.int32), "i32");
assert_eq!(type_of(tt.int64), "i64"); assert_eq!(type_of(tt.int64), "i64");

View File

@ -36,9 +36,9 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"MultipartRelatedRequestPost", "MultipartRelatedRequestPost",
"MultipartRequestPost", "MultipartRequestPost",
"MultipleIdenticalMimeTypesPost", "MultipleIdenticalMimeTypesPost",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -61,19 +61,18 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
].join(", ") "".to_owned()
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use multipart_v3::{AuthenticationApi, Claims}; use multipart_v3::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,24 +15,24 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
].join(", ") "".to_owned()
} }
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -63,8 +63,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -105,23 +105,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -56,19 +56,18 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
].join(", ") "".to_owned()
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use no_example_v3::{AuthenticationApi, Claims}; use no_example_v3::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,24 +15,24 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
].join(", ") "".to_owned()
} }
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -63,8 +63,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -105,23 +105,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -60,31 +60,31 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"AnyOfGet", "AnyOfGet",
"CallbackWithHeaderPost", "CallbackWithHeaderPost",
"ComplexQueryParamGet", "ComplexQueryParamGet",
"JsonComplexQueryParamGet", "JsonComplexQueryParamGet",
"MandatoryRequestHeaderGet", "MandatoryRequestHeaderGet",
"MergePatchJsonGet", "MergePatchJsonGet",
"MultigetGet", "MultigetGet",
"MultipleAuthSchemeGet", "MultipleAuthSchemeGet",
"OneOfGet", "OneOfGet",
"OverrideServerGet", "OverrideServerGet",
"ParamgetGet", "ParamgetGet",
"ReadonlyAuthSchemeGet", "ReadonlyAuthSchemeGet",
"RegisterCallbackPost", "RegisterCallbackPost",
"RequiredOctetStreamPut", "RequiredOctetStreamPut",
"ResponsesWithHeadersGet", "ResponsesWithHeadersGet",
"Rfc7807Get", "Rfc7807Get",
"UntypedPropertyGet", "UntypedPropertyGet",
"UuidGet", "UuidGet",
"XmlExtraPost", "XmlExtraPost",
"XmlOtherPost", "XmlOtherPost",
"XmlOtherPut", "XmlOtherPut",
"XmlPost", "XmlPost",
"XmlPut", "XmlPut",
"CreateRepo", "CreateRepo",
"GetRepoInfo", "GetRepoInfo",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -107,21 +107,21 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
[
"test.read", "test.read",
"test.write", "test.write",
].join(", ") ].join::<&str>(", ")
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use openapi_v3::{AuthenticationApi, Claims}; use openapi_v3::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,26 +15,27 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
"test.read", [
"test.write", "test.read",
].join(", ") "test.write",
} ].join::<&str>(", ")
}
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -65,8 +66,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -107,23 +108,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -70,43 +70,43 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"Op10Get", "Op10Get",
"Op11Get", "Op11Get",
"Op12Get", "Op12Get",
"Op13Get", "Op13Get",
"Op14Get", "Op14Get",
"Op15Get", "Op15Get",
"Op16Get", "Op16Get",
"Op17Get", "Op17Get",
"Op18Get", "Op18Get",
"Op19Get", "Op19Get",
"Op1Get", "Op1Get",
"Op20Get", "Op20Get",
"Op21Get", "Op21Get",
"Op22Get", "Op22Get",
"Op23Get", "Op23Get",
"Op24Get", "Op24Get",
"Op25Get", "Op25Get",
"Op26Get", "Op26Get",
"Op27Get", "Op27Get",
"Op28Get", "Op28Get",
"Op29Get", "Op29Get",
"Op2Get", "Op2Get",
"Op30Get", "Op30Get",
"Op31Get", "Op31Get",
"Op32Get", "Op32Get",
"Op33Get", "Op33Get",
"Op34Get", "Op34Get",
"Op35Get", "Op35Get",
"Op36Get", "Op36Get",
"Op37Get", "Op37Get",
"Op3Get", "Op3Get",
"Op4Get", "Op4Get",
"Op5Get", "Op5Get",
"Op6Get", "Op6Get",
"Op7Get", "Op7Get",
"Op8Get", "Op8Get",
"Op9Get", "Op9Get",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -129,19 +129,18 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
].join(", ") "".to_owned()
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use ops_v3::{AuthenticationApi, Claims}; use ops_v3::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,24 +15,24 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
].join(", ") "".to_owned()
} }
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -63,8 +63,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -105,23 +105,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -68,31 +68,31 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"Call123example", "Call123example",
"FakeOuterBooleanSerialize", "FakeOuterBooleanSerialize",
"FakeOuterCompositeSerialize", "FakeOuterCompositeSerialize",
"FakeOuterNumberSerialize", "FakeOuterNumberSerialize",
"FakeOuterStringSerialize", "FakeOuterStringSerialize",
"FakeResponseWithNumericalDescription", "FakeResponseWithNumericalDescription",
"HyphenParam", "HyphenParam",
"TestEndpointParameters", "TestEndpointParameters",
"TestEnumParameters", "TestEnumParameters",
"TestJsonFormData", "TestJsonFormData",
"DeletePet", "DeletePet",
"FindPetsByStatus", "FindPetsByStatus",
"FindPetsByTags", "FindPetsByTags",
"GetPetById", "GetPetById",
"UpdatePetWithForm", "UpdatePetWithForm",
"UploadFile", "UploadFile",
"DeleteOrder", "DeleteOrder",
"GetInventory", "GetInventory",
"GetOrderById", "GetOrderById",
"CreateUsersWithArrayInput", "CreateUsersWithArrayInput",
"CreateUsersWithListInput", "CreateUsersWithListInput",
"DeleteUser", "DeleteUser",
"GetUserByName", "GetUserByName",
"LoginUser", "LoginUser",
"LogoutUser", "LogoutUser",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -115,21 +115,21 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
[
"write:pets", "write:pets",
"read:pets", "read:pets",
].join(", ") ].join::<&str>(", ")
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use petstore_with_fake_endpoints_models_for_testing::{AuthenticationApi, Claims}; use petstore_with_fake_endpoints_models_for_testing::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,26 +15,27 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
"write:pets", [
"read:pets", "write:pets",
].join(", ") "read:pets",
} ].join::<&str>(", ")
}
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -65,8 +66,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -107,23 +108,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -34,7 +34,7 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"PingGet", "PingGet",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -57,19 +57,18 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
].join(", ") "".to_owned()
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use ping_bearer_auth::{AuthenticationApi, Claims}; use ping_bearer_auth::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,24 +15,24 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
].join(", ") "".to_owned()
} }
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -63,8 +63,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -105,23 +105,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }

View File

@ -42,13 +42,13 @@ fn main() {
.arg(Arg::with_name("operation") .arg(Arg::with_name("operation")
.help("Sets the operation to run") .help("Sets the operation to run")
.possible_values(&[ .possible_values(&[
"AllOfGet", "AllOfGet",
"DummyGet", "DummyGet",
"FileResponseGet", "FileResponseGet",
"GetStructuredYaml", "GetStructuredYaml",
"HtmlPost", "HtmlPost",
"PostYaml", "PostYaml",
"RawJsonGet", "RawJsonGet",
]) ])
.required(true) .required(true)
.index(1)) .index(1))
@ -71,19 +71,18 @@ fn main() {
// In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server // In a real (production) system this Bearer token should be obtained via an external Identity/Authentication-server
// Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side. // Ensure that you set the correct algorithm and encodingkey that matches what is used on the server side.
// See https://github.com/Keats/jsonwebtoken for more information // See https://github.com/Keats/jsonwebtoken for more information
let auth_token = build_token( let auth_token = build_token(
Claims { Claims {
sub: "tester@acme.com".to_owned(), sub: "tester@acme.com".to_owned(),
company: "ACME".to_owned(), company: "ACME".to_owned(),
iss: "my_identity_provider".to_owned(), iss: "my_identity_provider".to_owned(),
// added a very long expiry time // added a very long expiry time
aud: "org.acme.Resource_Server".to_string(), aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, exp: 10000000000,
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
scopes: [ scopes:
].join(", ") "".to_owned()
}, },
b"secret").unwrap(); b"secret").unwrap();
let auth_data = if !auth_token.is_empty() { let auth_data = if !auth_token.is_empty() {

View File

@ -30,9 +30,7 @@ pub async fn create(addr: &str, https: bool) {
let service = MakeService::new(server); let service = MakeService::new(server);
// This pushes a fourth layer of the middleware-stack even though Swagger assumes only three levels. let service = MakeAllowAllAuthenticator::new(service, "cosmo");
// This fourth layer creates an accept-all policy, hower the example-code already acchieves the same via a Bearer-token with full permissions, so next line is not needed (anymore).
// let service = MakeAllowAllAuthenticator::new(service, "cosmo");
#[allow(unused_mut)] #[allow(unused_mut)]
let mut service = let mut service =

View File

@ -1,7 +1,7 @@
use swagger::{ use swagger::{
ApiError, ApiError,
auth::{Basic, Bearer}, auth::{Basic, Bearer},
Has, Has,
XSpanIdString}; XSpanIdString};
use rust_server_test::{AuthenticationApi, Claims}; use rust_server_test::{AuthenticationApi, Claims};
use crate::server::Server; use crate::server::Server;
@ -15,24 +15,24 @@ use log::{error, debug};
/// Get a dummy claim with full permissions (all scopes) for testing purposes /// Get a dummy claim with full permissions (all scopes) for testing purposes
fn full_permission_claim() -> Claims { fn full_permission_claim() -> Claims {
Claims { // In this example code all available Scopes are added, so the current Bearer Token gets fully authorization.
sub: "tester@acme.com".to_owned(), Claims {
company: "ACME".to_owned(), sub: "tester@acme.com".to_owned(),
iss: "mini-bank-IDP".to_owned(), company: "ACME".to_owned(),
aud: "org.acme.Resource_Server".to_string(), iss: "mini-bank-IDP".to_owned(),
// added a very long expiry time aud: "org.acme.Resource_Server".to_string(),
exp: 10000000000, // added a very long expiry time
// In this example code all available Scopes are added, so the current Bearer Token gets fully authorization. exp: 10000000000,
scopes: [ scopes:
].join(", ") "".to_owned()
} }
} }
/// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example. /// Extract the data from a Bearer token using the provided Key (secret) and using the HS512-algorithm in this example.
fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> { fn extract_token_data(token: &str, key: &[u8]) -> Result<TokenData<Claims>, JwtError::Error> {
// Ensure that you set the correct algorithm and correct key. // Ensure that you set the correct algorithm and correct key.
// See https://github.com/Keats/jsonwebtoken for more information. // See https://github.com/Keats/jsonwebtoken for more information.
let header = decode_header(token)?; let header = decode_header(token)?;
@ -63,8 +63,8 @@ fn build_authorization(claims: Claims) -> Authorization {
let scopes = swagger::auth::Scopes::Some(scopes); let scopes = swagger::auth::Scopes::Some(scopes);
Authorization{ Authorization{
subject: claims.sub, subject: claims.sub,
scopes, scopes,
issuer: Some(claims.iss)} issuer: Some(claims.iss)}
} }
@ -105,23 +105,23 @@ impl<C> AuthenticationApi for Server<C> where C: Has<XSpanIdString> + Send + Syn
fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> { fn apikey_authorization(&self, api_key: &str) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received api-key, {api_key:#?}"); debug!("\tAuthorizationApi: Received api-key, {api_key:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
/// Implementation of the method to map a basic authentication (username and password) to an Authorization /// Implementation of the method to map a basic authentication (username and password) to an Authorization
fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> { fn basic_authorization(&self, basic: &Basic) -> Result<Authorization, ApiError> {
debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}"); debug!("\tAuthorizationApi: Received Basic-token, {basic:#?}");
// TODO: insert the logic to map received apikey to the set of claims // TODO: insert the logic to map received apikey to the set of claims
let claims = full_permission_claim(); let claims = full_permission_claim();
// and build an authorization out of it // and build an authorization out of it
Ok(build_authorization(claims)) Ok(build_authorization(claims))
} }
} }