Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 40 additions & 11 deletions backend/auth-core/src/oidc.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::config::CommonConfig;
use anyhow::anyhow;
use base64::{Engine, engine::general_purpose::STANDARD as BASE64};
use oauth2::{ClientId, ClientSecret, EndpointMaybeSet, EndpointNotSet, EndpointSet, reqwest};
use openidconnect::core::{CoreClient, CoreProviderMetadata, CoreTokenResponse};
use oauth2::{ClientId, ClientSecret, reqwest};
use openidconnect::core::CoreProviderMetadata;
use openidconnect::{IssuerUrl, RefreshToken};
use sea_orm::{Database, DatabaseConnection};
use sodiumoxide::crypto::box_::{PublicKey, SecretKey};
Expand All @@ -26,13 +26,42 @@ pub async fn create_db_connection(config: &CommonConfig) -> Result<DatabaseConne
Database::connect(&database_url).await.map_err(Into::into)
}

pub type OidcClient = CoreClient<
EndpointSet,
EndpointNotSet,
EndpointNotSet,
EndpointNotSet,
EndpointMaybeSet,
EndpointMaybeSet,
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct DiamondAdditionalClaims {
pub fedid: Option<String>,
}

impl openidconnect::AdditionalClaims for DiamondAdditionalClaims {}

pub type DiamondIdTokenFields = openidconnect::IdTokenFields<
DiamondAdditionalClaims,
openidconnect::EmptyExtraTokenFields,
openidconnect::core::CoreGenderClaim,
openidconnect::core::CoreJweContentEncryptionAlgorithm,
openidconnect::core::CoreJwsSigningAlgorithm,
>;

pub type DiamondTokenResponse =
openidconnect::StandardTokenResponse<DiamondIdTokenFields, openidconnect::core::CoreTokenType>;

pub type OidcClient = openidconnect::Client<
DiamondAdditionalClaims,
openidconnect::core::CoreAuthDisplay,
openidconnect::core::CoreGenderClaim,
openidconnect::core::CoreJweContentEncryptionAlgorithm,
openidconnect::core::CoreJsonWebKey,
openidconnect::core::CoreAuthPrompt,
openidconnect::StandardErrorResponse<openidconnect::core::CoreErrorResponseType>,
DiamondTokenResponse,
openidconnect::core::CoreTokenIntrospectionResponse,
openidconnect::core::CoreRevocableToken,
openidconnect::core::CoreRevocationErrorResponse,
openidconnect::EndpointSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointNotSet,
openidconnect::EndpointMaybeSet,
openidconnect::EndpointMaybeSet,
>;

pub async fn create_oidc_client(config: &CommonConfig) -> Result<(OidcClient, reqwest::Client)> {
Expand All @@ -48,7 +77,7 @@ pub async fn create_oidc_client(config: &CommonConfig) -> Result<(OidcClient, re
)
.await?;

let oidc_client = CoreClient::from_provider_metadata(
let oidc_client = OidcClient::from_provider_metadata(
provider_metadata,
ClientId::new(config.client_id.to_string()),
if config.client_secret.is_empty() {
Expand All @@ -72,7 +101,7 @@ pub async fn exchange_refresh_token(
oidc_client: &OidcClient,
http_client: &reqwest::Client,
refresh_token: &RefreshToken,
) -> Result<CoreTokenResponse> {
) -> Result<DiamondTokenResponse> {
let token_response = oidc_client
.exchange_refresh_token(refresh_token)?
.request_async(http_client)
Expand Down
16 changes: 16 additions & 0 deletions backend/auth-gateway/src/auth_session_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,31 +23,44 @@ pub struct TokenSessionData {
pub access_token: AccessToken,
pub access_token_expires_at: DateTime<Utc>,
pub refresh_token: RefreshToken,
pub name: Option<String>,
pub preferred_username: Option<String>,
pub fedid: Option<String>,
}

impl TokenSessionData {
pub const SESSION_KEY: &str = "token_session_data";

#[allow(clippy::too_many_arguments)]
pub fn new(
issuer: IssuerUrl,
subject: SubjectIdentifier,
access_token: AccessToken,
access_token_expires_at: DateTime<Utc>,
refresh_token: RefreshToken,
name: Option<String>,
preferred_username: Option<String>,
fedid: Option<String>,
) -> Self {
Self {
issuer,
subject,
access_token,
access_token_expires_at,
refresh_token,
name,
preferred_username,
fedid,
}
}

pub fn from_token_response<T: auth_core::oauth2::TokenResponse>(
token_response: &T,
issuer: IssuerUrl,
subject: SubjectIdentifier,
name: Option<String>,
preferred_username: Option<String>,
fedid: Option<String>,
) -> Result<Self> {
let access_token = token_response.access_token().clone();
let refresh_token = token_response
Expand All @@ -64,6 +77,9 @@ impl TokenSessionData {
access_token,
access_token_expires_at,
refresh_token,
name,
preferred_username,
fedid,
))
}

Expand Down
12 changes: 12 additions & 0 deletions backend/auth-gateway/src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ pub async fn callback(
&token_response,
claims.issuer().clone(),
claims.subject().clone(),
claims
.name()
.and_then(|name| name.get(None))
.map(|n| n.to_string()),
claims
.preferred_username()
.map(|username| username.to_string()),
claims
.additional_claims()
.fedid
.as_ref()
.map(|fedid| fedid.to_string()),
)?;
write_token_to_database(&state.database_connection, &token_data, &state.public_key).await?;
session
Expand Down
2 changes: 2 additions & 0 deletions backend/auth-gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod callback;
mod config;
mod login;
mod state;
mod userinfo;

use auth_core::middleware::inject_token::inject_token_with;
use clap::Parser;
Expand Down Expand Up @@ -96,6 +97,7 @@ fn create_router(state: Arc<AppState>, graph_url: String) -> Router {
.route("/auth/login", get(login::login))
.route("/auth/callback", get(callback::callback))
.route("/auth/logout", post(logout))
.route("/auth/me", get(userinfo::userinfo))
.route("/healthcheck", get(auth_core::healthcheck::healthcheck))
.layer(session_layer)
.layer(
Expand Down
34 changes: 34 additions & 0 deletions backend/auth-gateway/src/userinfo.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
use axum::{
http::StatusCode,
response::{IntoResponse, Json},
};
use serde::Serialize;
use tower_sessions::Session;

use crate::Result;
use crate::auth_session_data::TokenSessionData;

#[derive(Debug, Serialize)]
pub struct UserInfo {
pub name: Option<String>,
pub preferred_username: Option<String>,
pub fedid: Option<String>,
}

pub async fn userinfo(session: Session) -> Result<impl IntoResponse> {
let token_session_data: Option<TokenSessionData> =
session.get(TokenSessionData::SESSION_KEY).await?;

match token_session_data {
Some(token) => Ok((
StatusCode::OK,
Json(UserInfo {
name: token.name,
preferred_username: token.preferred_username,
fedid: token.fedid,
}),
)
.into_response()),
None => Ok(StatusCode::UNAUTHORIZED.into_response()),
}
}
Loading