Not A Mzter


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

 

  1. 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
/src/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))
}
  1. We can create an struct to show custom responses
/src/api_handler.rs
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,
}
  1. Now in api_handler.rs we need to create the function login to handle http post request.
/src/api_handler.rs
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,
        }),
    )
}
 
  1. API Result :     Image of Rest Client making request for previous example code