Added CORS support
This commit is contained in:
39
src/main.rs
39
src/main.rs
@@ -45,6 +45,44 @@ mod init {
|
|||||||
)]
|
)]
|
||||||
struct ApiDoc;
|
struct ApiDoc;
|
||||||
|
|
||||||
|
mod cors {
|
||||||
|
// use tower_http::cors::AllowOrigin;
|
||||||
|
// use tower_http::cors::CorsLayer;
|
||||||
|
// use axum::routing::get;
|
||||||
|
// use axum::routing::Router;
|
||||||
|
|
||||||
|
pub fn configure_cors() -> tower_http::cors::CorsLayer {
|
||||||
|
// Start building the CORS layer with common settings
|
||||||
|
let cors = tower_http::cors::CorsLayer::new()
|
||||||
|
.allow_methods([axum::http::Method::GET, axum::http::Method::POST, axum::http::Method::PUT, axum::http::Method::DELETE]) // Specify allowed methods:cite[2]
|
||||||
|
.allow_headers([axum::http::header::CONTENT_TYPE, axum::http::header::AUTHORIZATION]) // Specify allowed headers:cite[2]
|
||||||
|
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
|
||||||
|
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
|
||||||
|
|
||||||
|
// Dynamically set the allowed origin based on the environment
|
||||||
|
match std::env::var("ENVIRONMENT").as_deref() {
|
||||||
|
Ok("production") => {
|
||||||
|
// In production, allow only your specific, trusted origins
|
||||||
|
cors.allow_origin(vec![
|
||||||
|
"https://www.your-production-domain.com".parse::<axum::http::HeaderValue>().unwrap(),
|
||||||
|
"https://your-production-domain.com".parse().unwrap(),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
Ok("staging") => {
|
||||||
|
// Staging environment
|
||||||
|
cors.allow_origin("https://staging.your-domain.com".parse::<axum::http::HeaderValue>().unwrap())
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
// Development (default): Allow localhost origins
|
||||||
|
cors.allow_origin(vec![
|
||||||
|
"http://localhost:3000".parse().unwrap(),
|
||||||
|
"http://127.0.0.1:3000".parse().unwrap(),
|
||||||
|
])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn routes() -> Router {
|
pub async fn routes() -> Router {
|
||||||
// build our application with a route
|
// build our application with a route
|
||||||
Router::new()
|
Router::new()
|
||||||
@@ -72,6 +110,7 @@ mod init {
|
|||||||
callers::endpoints::REFRESH_TOKEN,
|
callers::endpoints::REFRESH_TOKEN,
|
||||||
post(callers::login::endpoint::refresh_token),
|
post(callers::login::endpoint::refresh_token),
|
||||||
)
|
)
|
||||||
|
.layer(cors::configure_cors())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn app() -> Router {
|
pub async fn app() -> Router {
|
||||||
|
Reference in New Issue
Block a user