Rust - Axum Identity API Chapter : 2
Â
In this chapter we are going to create an endpoint to receive POST request and read Authorization Header with Axum TypedHeaders
Â
Create a new project and install dependencies
Â
- Using the same axum_api project from chapter 1, We need to compare user and password hardcoded to implement http post request. First add the next route to your route.rs
use axum::{
routing::{get, post},
Router,
};
use crate::api_handler::{health_checker, login};
pub fn create_router() -> Router {
/*...........*/
.route("/identity/login", post(login))
}
- We can create an struct to show custom responses
use axum::{http::StatusCode, Json};
use axum_extra::{
headers::{authorization::Basic, Authorization},
TypedHeader,
};
use serde::Serialize;
use serde_json::Value;
#[derive(Serialize)]
pub struct IdentityResponse {
error: Value,
data: Value,
}
- Now in api_handler.rs we need to create the function login to handle http post request.
pub async fn login(
TypedHeader(Authorization(credentials)): TypedHeader<Authorization<Basic>>,
) -> (StatusCode, Json<IdentityResponse>) {
// credentials from Basic Authorization header
if credentials.username() == "admin" && credentials.password() == "password" {
return (StatusCode::OK,
Json(IdentityResponse {
error: Value::Null,
data: Value::String("Valid credentials".to_string()),
}),
);
}
// If credentials are invalid
(
StatusCode::UNAUTHORIZED,
Json(IdentityResponse {
error: Value::String("Invalid credentials".to_string()),
data: Value::Null,
}),
)
}
- API Result :
Â
Â