Use OpenID primites & client from light-openid crate
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing

This commit is contained in:
Pierre HUBERT 2023-04-29 12:33:23 +02:00
parent 2eaeb12835
commit dc49d78075
6 changed files with 48 additions and 184 deletions

1
Cargo.lock generated
View File

@ -580,7 +580,6 @@ dependencies = [
"mime_guess",
"qrcode-generator",
"rand",
"reqwest",
"serde",
"serde_json",
"serde_yaml",

View File

@ -39,4 +39,3 @@ light-openid = { version = "1.0.1", features=["crypto-wrapper"] }
bincode = "2.0.0-rc.3"
chrono = "0.4.24"
lazy_static = "1.4.0"
reqwest = { version = "0.11.16", features = ["json"] }

View File

@ -7,6 +7,7 @@ use actix_web::error::ErrorUnauthorized;
use actix_web::{web, HttpRequest, HttpResponse, Responder};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
use crate::actors::openid_sessions_actor::{OpenIDSessionsActor, Session, SessionID};
use crate::actors::users_actor::UsersActor;
@ -20,7 +21,7 @@ use crate::data::code_challenge::CodeChallenge;
use crate::data::current_user::CurrentUser;
use crate::data::id_token::IdToken;
use crate::data::jwt_signer::{JWTSigner, JsonWebKey};
use crate::data::openid_primitive::{OpenIDConfig, OpenIDUserInfo, TokenResponse};
use crate::data::session_identity::SessionIdentity;
use crate::data::user::User;
use crate::utils::string_utils::rand_str;
@ -51,15 +52,32 @@ pub async fn get_configuration(req: HttpRequest) -> impl Responder {
issuer: AppConfig::get().website_origin.clone(),
authorization_endpoint: AppConfig::get().full_url(AUTHORIZE_URI),
token_endpoint: curr_origin.clone() + TOKEN_URI,
userinfo_endpoint: curr_origin.clone() + USERINFO_URI,
userinfo_endpoint: Some(curr_origin.clone() + USERINFO_URI),
jwks_uri: curr_origin + CERT_URI,
scopes_supported: vec!["openid", "profile", "email"],
response_types_supported: vec!["code", "id_token", "token id_token"],
subject_types_supported: vec!["public"],
id_token_signing_alg_values_supported: vec!["RS256"],
token_endpoint_auth_methods_supported: vec!["client_secret_post", "client_secret_basic"],
claims_supported: vec!["sub", "name", "given_name", "family_name", "email"],
code_challenge_methods_supported: vec!["plain", "S256"],
scopes_supported: Some(vec![
"openid".to_string(),
"profile".to_string(),
"email".to_string(),
]),
response_types_supported: vec![
"code".to_string(),
"id_token".to_string(),
"token id_token".to_string(),
],
subject_types_supported: vec!["public".to_string()],
id_token_signing_alg_values_supported: vec!["RS256".to_string()],
token_endpoint_auth_methods_supported: Some(vec![
"client_secret_post".to_string(),
"client_secret_basic".to_string(),
]),
claims_supported: Some(vec![
"sub".to_string(),
"name".to_string(),
"given_name".to_string(),
"family_name".to_string(),
"email".to_string(),
]),
code_challenge_methods_supported: Some(vec!["plain".to_string(), "S256".to_string()]),
})
}
@ -438,7 +456,7 @@ pub async fn token(
email: user.email,
};
TokenResponse {
OpenIDTokenResponse {
access_token: session.access_token.expect("Missing access token!"),
token_type: "Bearer".to_string(),
refresh_token: Some(session.refresh_token),
@ -488,7 +506,7 @@ pub async fn token(
.await
.unwrap();
TokenResponse {
OpenIDTokenResponse {
access_token: session.access_token.expect("Missing access token!"),
token_type: "Bearer".to_string(),
refresh_token: Some(session.refresh_token),

View File

@ -8,7 +8,6 @@ pub mod entity_manager;
pub mod id_token;
pub mod jwt_signer;
pub mod login_redirect;
pub mod openid_primitive;
pub mod provider;
pub mod provider_configuration;
pub mod session_identity;

View File

@ -1,107 +0,0 @@
//! # OpenID primitives
/// OpenID discovery information
#[derive(Debug, Clone, serde::Serialize)]
pub struct OpenIDConfig {
/// URL using the https scheme with no query or fragment component that the OP asserts as its Issuer Identifier. If Issuer discovery is supported (see Section 2), this value MUST be identical to the issuer value returned by WebFinger. This also MUST be identical to the iss Claim value in ID Tokens issued from this Issuer
pub issuer: String,
/// REQUIRED. URL of the OP's OAuth 2.0 Authorization Endpoint `OpenID.Core`
pub authorization_endpoint: String,
/// URL of the OP's OAuth 2.0 Token Endpoint `OpenID.Core`. This is REQUIRED unless only the Implicit Flow is used.
pub token_endpoint: String,
/// RECOMMENDED. URL of the OP's UserInfo Endpoint `[`OpenID.Core`]`. This URL MUST use the https scheme and MAY contain port, path, and query parameter components
pub userinfo_endpoint: String,
/// REQUIRED. URL of the OP's JSON Web Key Set `[`JWK`]` document. This contains the signing key(s) the RP uses to validate signatures from the OP. The JWK Set MAY also contain the Server's encryption key(s), which are used by RPs to encrypt requests to the Server. When both signing and encryption keys are made available, a use (Key Use) parameter value is REQUIRED for all keys in the referenced JWK Set to indicate each key's intended usage. Although some algorithms allow the same key to be used for both signatures and encryption, doing so is NOT RECOMMENDED, as it is less secure. The JWK x5c parameter MAY be used to provide X.509 representations of keys provided. When used, the bare key values MUST still be present and MUST match those in the certificate.
pub jwks_uri: String,
/// RECOMMENDED. JSON array containing a list of the OAuth 2.0 `[`RFC6749`]` scope values that this server supports. The server MUST support the openid scope value. Servers MAY choose not to advertise some supported scope values even when this parameter is used, although those defined in `[`OpenID.Core`]` SHOULD be listed, if supported.
pub scopes_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the OAuth 2.0 response_type values that this OP supports. Dynamic OpenID Providers MUST support the code, id_token, and the token id_token Response Type values.
pub response_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the Subject Identifier types that this OP supports. Valid types include pairwise and public.
pub subject_types_supported: Vec<&'static str>,
/// REQUIRED. JSON array containing a list of the JWS signing algorithms (alg values) supported by the OP for the ID Token to encode the Claims in a JWT `[`JWT`. The algorithm RS256 MUST be included. The value none MAY be supported, but MUST NOT be used unless the Response Type used returns no ID Token from the Authorization Endpoint (such as when using the Authorization Code Flow).
pub id_token_signing_alg_values_supported: Vec<&'static str>,
/// OPTIONAL. JSON array containing a list of Client Authentication methods supported by this Token Endpoint. The options are client_secret_post, client_secret_basic, client_secret_jwt, and private_key_jwt
pub token_endpoint_auth_methods_supported: Vec<&'static str>,
/// RECOMMENDED. JSON array containing a list of the Claim Names of the Claims that the OpenID Provider MAY be able to supply values for. Note that for privacy or other reasons, this might not be an exhaustive list.
pub claims_supported: Vec<&'static str>,
pub code_challenge_methods_supported: Vec<&'static str>,
}
/// OpenID token response
///
/// The content of this field is specified in
/// * OAuth specifications: https://datatracker.ietf.org/doc/html/rfc6749#section-5.1
/// * OpenID Core specifications: https://openid.net/specs/openid-connect-core-1_0.html#TokenResponse
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TokenResponse {
/// REQUIRED. The access token issued by the authorization server.
pub access_token: String,
/// REQUIRED. The type of the token issued. It MUST be "Bearer"
pub token_type: String,
/// OPTIONAL. The refresh token, which can be used to obtain new
/// access tokens using the same authorization grant
#[serde(skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
/// RECOMMENDED. The lifetime in seconds of the access token. For
/// example, the value "3600" denotes that the access token will
/// expire in one hour from the time the response was generated.
/// If omitted, the authorization server SHOULD provide the
/// expiration time via other means or document the default value.
#[serde(skip_serializing_if = "Option::is_none")]
pub expires_in: Option<u64>,
/// REQUIRED. ID Token value associated with the authenticated session.
///
/// Note: this field is marked as optionnal because it is excluded in case
/// of request of refresh token.
#[serde(skip_serializing_if = "Option::is_none")]
pub id_token: Option<String>,
}
/// Refer to <https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims> for more information
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct OpenIDUserInfo {
/// Subject - Identifier for the End-User at the Issuer
///
/// This is the only mandatory field
pub sub: String,
/// End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Given name(s) or first name(s) of the End-User. Note that in some cultures, people can have multiple given names; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub given_name: Option<String>,
/// Surname(s) or last name(s) of the End-User. Note that in some cultures, people can have multiple family names or no family name; all can be present, with the names being separated by space characters.
#[serde(skip_serializing_if = "Option::is_none")]
pub family_name: Option<String>,
/// Shorthand name by which the End-User wishes to be referred to at the RP, such as janedoe or j.doe. This value MAY be any valid JSON string including special characters such as @, /, or whitespace. The RP MUST NOT rely upon this value being unique, as discussed in
#[serde(skip_serializing_if = "Option::is_none")]
pub preferred_username: Option<String>,
/// End-User's preferred e-mail address. Its value MUST conform to the RFC 5322 RFC5322 addr-spec syntax. The RP MUST NOT rely upon this value being unique, as discussed in Section 5.7.
#[serde(skip_serializing_if = "Option::is_none")]
pub email: Option<String>,
/// True if the End-User's e-mail address has been verified; otherwise false. When this Claim Value is true, this means that the OP took affirmative steps to ensure that this e-mail address was controlled by the End-User at the time the verification was performed. The means by which an e-mail address is verified is context-specific, and dependent upon the trust framework or contractual agreements within which the parties are operating.
#[serde(skip_serializing_if = "Option::is_none")]
pub email_verified: Option<bool>,
}

View File

@ -1,38 +1,20 @@
use std::cell::RefCell;
use std::collections::HashMap;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use light_openid::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
use crate::actors::providers_states_actor::ProviderLoginState;
use crate::constants::OIDC_PROVIDERS_LIFETIME;
use crate::data::app_config::AppConfig;
use crate::data::jwt_signer::JsonWebKey;
use crate::data::openid_primitive::{OpenIDUserInfo, TokenResponse};
use crate::data::provider::Provider;
use crate::utils::err::Res;
use crate::utils::time::time;
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ProviderDiscovery {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
pub userinfo_endpoint: Option<String>,
pub jwks_uri: String,
pub claims_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ProviderJWKs {
pub keys: Vec<JsonWebKey>,
}
/// Provider configuration
#[derive(Debug, Clone)]
pub struct ProviderConfiguration {
pub discovery: ProviderDiscovery,
//pub keys: ProviderJWKs,
pub discovery: OpenIDConfig,
pub expire: u64,
}
@ -52,41 +34,23 @@ impl ProviderConfiguration {
&self,
provider: &Provider,
authorization_code: &str,
) -> Res<TokenResponse> {
let authorization =
BASE64_STANDARD.encode(format!("{}:{}", provider.client_id, provider.client_secret));
) -> Res<OpenIDTokenResponse> {
let (token, _) = self
.discovery
.request_token(
&provider.client_id,
&provider.client_secret,
authorization_code,
&AppConfig::get().oidc_provider_redirect_url(),
)
.await?;
let redirect_url = AppConfig::get().oidc_provider_redirect_url();
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("code", authorization_code);
params.insert("redirect_uri", redirect_url.as_str());
Ok(reqwest::Client::new()
.post(&self.discovery.token_endpoint)
.header("Authorization", format!("Basic {authorization}"))
.form(&params)
.send()
.await?
.json()
.await?)
Ok(token)
}
/// Retrieve information about the user, using given [TokenResponse]
pub async fn get_userinfo(&self, token: &TokenResponse) -> Res<OpenIDUserInfo> {
Ok(reqwest::Client::new()
.get(
self.discovery
.userinfo_endpoint
.as_ref()
.expect("Userinfo endpoint is required by this implementation!"),
)
.header("Authorization", format!("Bearer {}", token.access_token))
.send()
.await?
.json()
.await?)
/// Retrieve information about the user, using a given [OpenIDTokenResponse]
pub async fn get_userinfo(&self, token: &OpenIDTokenResponse) -> Res<OpenIDUserInfo> {
Ok(self.discovery.request_user_info(token).await?.0)
}
}
@ -119,16 +83,8 @@ impl ProviderConfigurationHelper {
/// Get fresh configuration from provider
async fn fetch_configuration(provider: &Provider) -> Res<ProviderConfiguration> {
let discovery: ProviderDiscovery = reqwest::get(&provider.configuration_url)
.await?
.json()
.await?;
// let keys: ProviderJWKs = reqwest::get(&discovery.jwks_uri).await?.json().await?;
Ok(ProviderConfiguration {
discovery,
// keys,
discovery: OpenIDConfig::load_from_url(&provider.configuration_url).await?,
expire: time() + OIDC_PROVIDERS_LIFETIME,
})
}