Skip to content

Instantly share code, notes, and snippets.

@ThorstenHans
Created October 16, 2023 12:20
Show Gist options
  • Save ThorstenHans/18c0ffe26e269d24f52994a199ee7849 to your computer and use it in GitHub Desktop.
Save ThorstenHans/18c0ffe26e269d24f52994a199ee7849 to your computer and use it in GitHub Desktop.
Basic Auth with Spin
[package]
name = "spin-rust-basic-auth"
authors = ["Thorsten Hans <thorsten.hans@gmail.com>"]
description = ""
version = "0.1.0"
edition = "2021"
[lib]
crate-type = [ "cdylib" ]
[dependencies]
# Useful crate to handle errors.
anyhow = "1"
# Crate to simplify working with bytes.
bytes = "1"
# General-purpose crate with common HTTP types.
http = "0.2"
http-auth-basic = "0.3.3"
# The Spin SDK.
spin-sdk = { git = "https://github.com/fermyon/spin", tag = "v1.5.1" }
[workspace]
use anyhow::{Result};
use http::{HeaderValue};
use http_auth_basic::Credentials;
use spin_sdk::{
http::{Request, Response},
http_component,
};
/// A simple Spin HTTP component.
#[http_component]
fn handle_spin_rust_basic_auth(req: Request) -> Result<Response> {
println!("{:?}", req.headers());
match req.headers().get("Authorization") {
Some(h) => handle(&req, h),
None => Ok(http::Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body(Some("No token presented".into()))?),
}
}
fn handle(r: &Request, h: &HeaderValue) -> Result<Response> {
let value = h.to_str()?;
match Credentials::from_header(value.to_string()) {
Ok(creds) => {
if creds.user_id == "admin" {
return Ok(http::Response::builder().status(http::StatusCode::OK).body(None)?);
}
Ok(http::Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body(Some("Wrong user".into()))?)
},
Err(_) => {
Ok(http::Response::builder()
.status(http::StatusCode::FORBIDDEN)
.body(Some("Error decoding header value".into()))?)
}
}
}
spin_manifest_version = "1"
authors = ["Thorsten Hans <thorsten.hans@gmail.com>"]
description = ""
name = "spin-rust-basic-auth"
trigger = { type = "http", base = "/" }
version = "0.1.0"
[[component]]
id = "spin-rust-basic-auth"
source = "target/wasm32-wasi/release/spin_rust_basic_auth.wasm"
allowed_http_hosts = []
[component.trigger]
route = "/..."
[component.build]
command = "cargo build --target wasm32-wasi --release"
watch = ["src/**/*.rs", "Cargo.toml"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment