Skip to content

Commit

Permalink
naming
Browse files Browse the repository at this point in the history
  • Loading branch information
NewbMiao committed Jun 8, 2023
1 parent 39c98cc commit 42ac807
Show file tree
Hide file tree
Showing 10 changed files with 101 additions and 38 deletions.
4 changes: 2 additions & 2 deletions .env.dev
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
GOOGLE_CLIENT_ID=""
GOOGLE_CLIENT_SECRET=""
DATABASE_URL="postgresql://axum-demo:axum-demo-sec@localhost:15432/axum-demo"
KEYCLOAK_CLIENT_ID="axum-demo"
DATABASE_URL="postgresql://axum-koans:axum-koans-sec@localhost:15432/axum-koans"
KEYCLOAK_CLIENT_ID="axum-koans"
KEYCLOAK_CLIENT_SECRET="tF2yB4ELq5zqT6cSpSNJMA1fuq9DVXnc"
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "axum-demo"
name = "axum-koans"
version = "0.1.0"
edition = "2021"

Expand Down
8 changes: 4 additions & 4 deletions docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,12 @@ services:
aliases:
- database
environment:
POSTGRESQL_DATABASE: axum-demo
POSTGRESQL_USERNAME: axum-demo
POSTGRESQL_PASSWORD: axum-demo-sec
POSTGRESQL_DATABASE: axum-koans
POSTGRESQL_USERNAME: axum-koans
POSTGRESQL_PASSWORD: axum-koans-sec

healthcheck:
test: pg_isready -U axum-demo
test: pg_isready -U axum-koans
interval: 10s
timeout: 5s
retries: 5
Expand Down
11 changes: 9 additions & 2 deletions examples/trace.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,15 @@
use axum::{routing::get, Router};
use tower_http::trace::{self, TraceLayer};
use tracing::Level;
use tracing::{event, instrument, Level};

#[instrument]
async fn handler() -> &'static str {
event!(Level::INFO, "handler event");
// let span = info_span!("handler");

// `enter` 返回一个 RAII ,当其被 drop 时,将自动结束该 span
// let _enter = span.enter();
event!(Level::INFO, "something happened inside handler");
"Hello, world!"
}

Expand All @@ -11,7 +18,7 @@ async fn main() {
tracing_subscriber::fmt()
.with_max_level(tracing::Level::INFO)
.with_ansi(false)
.json()
// .json()
.init();

let app = Router::new().route("/", get(handler)).layer(
Expand Down
61 changes: 58 additions & 3 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,62 @@
## keycloak
# axum-koans

replace google (identity provider) `clientSecret` and `clientId` in `realm.json` with yours
## setup

## database
1. add [google oauth configuration](https://console.cloud.google.com/apis/credentials)

- Authorized JavaScript origins
- http://localhost:8000
- http://localhost:8080
- Authorized redirect URIs
- http://localhost:8000/google/auth-callback
- http://localhost:8080/realms/axum-koans/broker/google/endpoint

2. add google client configuration in keycloak realm.json

```json
// replace `clientSecret` and `clientId` with your own google oauth client
"identityProviders": [
{
"alias": "google",
"internalId": "955ac868-8fbf-44ad-80e5-41c5e9d44953",
"providerId": "google",
"enabled": true,
"updateProfileFirstLoginMode": "on",
"trustEmail": false,
"storeToken": false,
"addReadTokenRoleOnCreate": false,
"authenticateByDefault": false,
"linkOnly": false,
"firstBrokerLoginFlowAlias": "first broker login",
"config": {
"offlineAccess": "true",
"userIp": "false",
"clientSecret": "**********",
"clientId": "**********.apps.googleusercontent.com"
}
}
]
```

3. init application

```shell
# keycloak and postgres
docker-compose up
# database migration
# install database migrations tool sqx
cargo install sqlx-cli --no-default-features --features native-tls,postgres
sqlx migrate run
```

## features

### Oauth

- google-oauth

http://localhost:8000/google/auth

- keycloak-google-oauth (token-exchange)

http://localhost:8000/keycloak/login (use google login method)
32 changes: 16 additions & 16 deletions realm.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"id": "bb4bf8bc-e725-478f-9002-1da7277e2969",
"realm": "axum-demo",
"realm": "axum-koans",
"notBefore": 0,
"defaultSignatureAlgorithm": "RS256",
"revokeRefreshToken": false,
Expand Down Expand Up @@ -45,7 +45,7 @@
"failureFactor": 30,
"defaultRole": {
"id": "b7936ab0-5c9b-4c1f-8fcf-6dd058e374fd",
"name": "default-roles-axum-demo",
"name": "default-roles-axum-koans",
"description": "${role_default-roles}",
"composite": true,
"clientRole": false,
Expand Down Expand Up @@ -94,11 +94,11 @@
{
"id": "586fb9e8-be81-4553-a75e-fb907e5d745a",
"createdTimestamp": 1685867284893,
"username": "service-account-axum-demo",
"username": "service-account-axum-koans",
"enabled": true,
"totp": false,
"emailVerified": false,
"serviceAccountClientId": "axum-demo",
"serviceAccountClientId": "axum-koans",
"disableableCredentialTypes": [],
"requiredActions": [],
"notBefore": 0
Expand Down Expand Up @@ -129,13 +129,13 @@
"clientId": "account",
"name": "${client_account}",
"rootUrl": "${authBaseUrl}",
"baseUrl": "/realms/axum-demo/account/",
"baseUrl": "/realms/axum-koans/account/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"/realms/axum-demo/account/*"
"/realms/axum-koans/account/*"
],
"webOrigins": [],
"notBefore": 0,
Expand Down Expand Up @@ -173,13 +173,13 @@
"clientId": "account-console",
"name": "${client_account-console}",
"rootUrl": "${authBaseUrl}",
"baseUrl": "/realms/axum-demo/account/",
"baseUrl": "/realms/axum-koans/account/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"/realms/axum-demo/account/*"
"/realms/axum-koans/account/*"
],
"webOrigins": [],
"notBefore": 0,
Expand Down Expand Up @@ -263,7 +263,7 @@
},
{
"id": "a48bb7ea-0f29-445b-8d5c-c311f20f1d61",
"clientId": "axum-demo",
"clientId": "axum-koans",
"name": "",
"description": "",
"rootUrl": "http://localhost:8000",
Expand Down Expand Up @@ -487,13 +487,13 @@
"policies": [
{
"id": "7f132011-1be7-467f-93f8-3d5b5c03492f",
"name": "axum-demo-token-exchange-policy",
"name": "axum-koans-token-exchange-policy",
"description": "",
"type": "client",
"logic": "POSITIVE",
"decisionStrategy": "UNANIMOUS",
"config": {
"clients": "[\"axum-demo\"]"
"clients": "[\"axum-koans\"]"
}
},
{
Expand Down Expand Up @@ -572,7 +572,7 @@
"config": {
"resources": "[\"client.resource.a48bb7ea-0f29-445b-8d5c-c311f20f1d61\"]",
"scopes": "[\"token-exchange\"]",
"applyPolicies": "[\"axum-demo-token-exchange-policy\"]"
"applyPolicies": "[\"axum-koans-token-exchange-policy\"]"
}
},
{
Expand All @@ -585,7 +585,7 @@
"config": {
"resources": "[\"idp.resource.955ac868-8fbf-44ad-80e5-41c5e9d44953\"]",
"scopes": "[\"token-exchange\"]",
"applyPolicies": "[\"axum-demo-token-exchange-policy\"]"
"applyPolicies": "[\"axum-koans-token-exchange-policy\"]"
}
}
],
Expand Down Expand Up @@ -627,13 +627,13 @@
"clientId": "security-admin-console",
"name": "${client_security-admin-console}",
"rootUrl": "${authAdminUrl}",
"baseUrl": "/admin/axum-demo/console/",
"baseUrl": "/admin/axum-koans/console/",
"surrogateAuthRequired": false,
"enabled": true,
"alwaysDisplayInConsole": false,
"clientAuthenticatorType": "client-secret",
"redirectUris": [
"/admin/axum-demo/console/*"
"/admin/axum-koans/console/*"
],
"webOrigins": [
"+"
Expand Down Expand Up @@ -1243,7 +1243,7 @@
"offlineAccess": "true",
"userIp": "false",
"clientSecret": "**********",
"clientId": "460945802170-to4anqvqf2rvp3a8pa27gevr42njiu6l.apps.googleusercontent.com"
"clientId": "**********.apps.googleusercontent.com"
}
}
],
Expand Down
8 changes: 4 additions & 4 deletions src/extensions/keycloak_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ impl KeycloakAuth {
let client_secret = ClientSecret::new(client_secret.to_string());

let token_url = TokenUrl::new(
"http://localhost:8080/realms/axum-demo/protocol/openid-connect/token".to_string(),
"http://localhost:8080/realms/axum-koans/protocol/openid-connect/token".to_string(),
)
.unwrap();
let auth_url = AuthUrl::new(
"http://localhost:8080/realms/axum-demo/protocol/openid-connect/auth".to_string(),
"http://localhost:8080/realms/axum-koans/protocol/openid-connect/auth".to_string(),
)
.unwrap();
let redirect_url =
Expand Down Expand Up @@ -116,7 +116,7 @@ impl KeycloakAuth {
requested_issuer: String,
) -> TokenExchangeResponse {
// 从 Keycloak 的令牌响应中获取访问令牌
let token_url = "http://localhost:8080/realms/axum-demo/protocol/openid-connect/token";
let token_url = "http://localhost:8080/realms/axum-koans/protocol/openid-connect/token";
let userinfo_response = Client::new()
.post(token_url)
.form(&[
Expand All @@ -141,7 +141,7 @@ impl KeycloakAuth {
}
pub async fn get_user_info(&self, token: String) -> UserInfo {
let user_info_url =
"http://localhost:8080/realms/axum-demo/protocol/openid-connect/userinfo";
"http://localhost:8080/realms/axum-koans/protocol/openid-connect/userinfo";
let res = Client::new()
.get(user_info_url)
.bearer_auth(token)
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use axum::{middleware, routing::get, Extension, Router};
use axum_demo::{
use axum_koans::{
extensions::{google_auth::GoogleAuth, keycloak_auth::KeycloakAuth},
handlers::{
auth::{auth_callback_handler, auth_handler},
Expand Down Expand Up @@ -82,12 +82,12 @@ async fn main() {
.layer(Extension(db_pool))
.into_inner(),
)
.layer(middleware::from_fn(log))
.layer(
TraceLayer::new_for_http()
.make_span_with(trace::DefaultMakeSpan::new().level(Level::INFO))
.on_response(trace::DefaultOnResponse::new().level(Level::INFO)),
);
)
.layer(middleware::from_fn(log));

let addr = SocketAddr::from(([0, 0, 0, 0], 8000));
axum::Server::bind(&addr)
Expand Down
5 changes: 3 additions & 2 deletions src/middlewares/log.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use axum::http::{Request, Response, StatusCode};
use axum::middleware::Next;
use axum::response::IntoResponse;
use hyper::Body;
use tracing::info;

pub async fn log(
req: Request<axum::body::Body>,
Expand Down Expand Up @@ -66,14 +67,14 @@ where
if let Ok(body) = std::str::from_utf8(&bytes) {
if log && !body.is_empty() {
if body.len() > 2000 {
println!(
info!(
"{} for req: {} with body: {}...",
direction,
path,
&body[0..2000]
);
} else {
println!("{} for req: {} with body: {}", direction, path, body);
info!("{} for req: {} with body: {}", direction, path, body);
}
}
}
Expand Down

0 comments on commit 42ac807

Please sign in to comment.