Add basic OpenID client

This commit is contained in:
Pierre HUBERT 2023-04-28 19:22:49 +02:00
parent 37259391f1
commit 661792b803
6 changed files with 1304 additions and 3 deletions

1093
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -6,3 +6,9 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
log = "0.4.17"
reqwest = { version = "0.11.17", features = ["json"] }
base64 = "0.21.0"
serde = { version = "1.0.160", features = ["derive"] }
serde_json = "1.0.96"
urlencoding = "2.1.2"

82
src/client.rs Normal file
View File

@ -0,0 +1,82 @@
//! # Open ID client implementation
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine;
use std::collections::HashMap;
use std::error::Error;
use crate::primitives::{OpenIDConfig, OpenIDTokenResponse, OpenIDUserInfo};
impl OpenIDConfig {
/// Load OpenID configuration from a given .well-known/openid-configuration URL
pub async fn load_from_url(url: &str) -> Result<Self, Box<dyn Error>> {
Ok(reqwest::get(url).await?.json().await?)
}
/// Get the authorization URL where a user should be redirect to perform authentication
pub fn gen_authorization_url(
&self,
client_id: &str,
state: &str,
redirect_uri: &str,
) -> String {
let client_id = urlencoding::encode(client_id);
let state = urlencoding::encode(state);
let redirect_uri = urlencoding::encode(redirect_uri);
format!("{}?response_type=code&scope=openid%20profile%20email&client_id={client_id}&state={state}&redirect_uri={redirect_uri}", self.authorization_endpoint)
}
/// Query the token endpoint
///
/// This endpoint returns both the parsed and the raw response, to allow handling
/// of bonus fields
pub async fn request_token(
&self,
client_id: &str,
client_secret: &str,
code: &str,
redirect_uri: &str,
) -> Result<(OpenIDTokenResponse, String), Box<dyn Error>> {
let authorization = BASE64_STANDARD.encode(format!("{}:{}", client_id, client_secret));
let mut params = HashMap::new();
params.insert("grant_type", "authorization_code");
params.insert("code", code);
params.insert("redirect_uri", redirect_uri);
let response = reqwest::Client::new()
.post(&self.token_endpoint)
.header("Authorization", format!("Basic {authorization}"))
.form(&params)
.send()
.await?
.text()
.await?;
Ok((serde_json::from_str(&response)?, response))
}
/// Query the UserInfo endpoint.
///
/// This endpoint should be use after having successfully retrieved the token
///
/// This endpoint returns both the parsed value and the raw response, in case of presence
/// of additional fields
pub async fn request_user_info(
&self,
token: &OpenIDTokenResponse,
) -> Result<(OpenIDUserInfo, String), Box<dyn Error>> {
let response = reqwest::Client::new()
.get(self.userinfo_endpoint.as_ref().expect(
"This client only support information retrieval through userinfo endpoint!",
))
.header("Authorization", format!("Bearer {}", token.access_token))
.send()
.await?
.text()
.await?;
Ok((serde_json::from_str(&response)?, response))
}
}

8
src/lib.rs Normal file
View File

@ -0,0 +1,8 @@
//! # Light OpenID
//!
//! Basic implementation of OpenID protocol, with primitives and basic client.
//!
//! See https://gitea.communiquons.org/pierre/oidc-test-client for an example of usage of this library
pub mod client;
pub mod primitives;

View File

@ -1,3 +0,0 @@
fn main() {
println!("Hello, world!");
}

115
src/primitives.rs Normal file
View File

@ -0,0 +1,115 @@
//! # OpenID primitives
//!
//! These primitives might be incomplete, but sufficient for a basic OpenID usage.
/// OpenID discovery information, typically distributed on http://provider/.well-known/openid-configuration
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
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
#[serde(skip_serializing_if = "Option::is_none")]
pub userinfo_endpoint: Option<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.
#[serde(skip_serializing_if = "Option::is_none")]
pub scopes_supported: Option<Vec<String>>,
/// 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<String>,
/// 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<String>,
/// 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<String>,
/// 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
#[serde(skip_serializing_if = "Option::is_none")]
pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
/// 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.
#[serde(skip_serializing_if = "Option::is_none")]
pub claims_supported: Option<Vec<String>>,
/// OPTIONAL JSON array containing a list of Proof Key for Code Exchange (PKCE)
#[serde(skip_serializing_if = "Option::is_none")]
pub code_challenge_methods_supported: Option<Vec<String>>,
}
/// 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 OpenIDTokenResponse {
/// 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>,
}