Skip to main content

rustauth_oauth/oauth2/
client_credentials_token.rs

1use super::error::OAuthError;
2use super::request::{apply_client_authentication, ClientAuthentication, OAuthFormRequest};
3use super::tokens::{get_primary_client_id, ProviderOptions};
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct ClientCredentialsTokenRequest {
7    pub options: ProviderOptions,
8    pub scope: Option<String>,
9    pub authentication: ClientAuthentication,
10    pub resource: Vec<String>,
11}
12
13impl Default for ClientCredentialsTokenRequest {
14    fn default() -> Self {
15        Self {
16            options: ProviderOptions::default(),
17            scope: None,
18            authentication: ClientAuthentication::Post,
19            resource: Vec::new(),
20        }
21    }
22}
23
24impl ClientCredentialsTokenRequest {
25    pub fn try_new(options: ProviderOptions) -> Result<Self, OAuthError> {
26        get_primary_client_id(&options.client_id).ok_or(OAuthError::MissingOption("client_id"))?;
27        options
28            .client_secret_str()
29            .ok_or(OAuthError::MissingOption("client_secret"))?;
30        Ok(Self {
31            options,
32            ..Self::default()
33        })
34    }
35
36    pub fn scope(mut self, scope: impl Into<String>) -> Self {
37        self.scope = Some(scope.into());
38        self
39    }
40
41    pub fn authentication(mut self, authentication: ClientAuthentication) -> Self {
42        self.authentication = authentication;
43        self
44    }
45
46    pub fn resource(mut self, resource: impl Into<String>) -> Self {
47        self.resource.push(resource.into());
48        self
49    }
50}
51
52pub fn create_client_credentials_token_request(
53    input: ClientCredentialsTokenRequest,
54) -> Result<OAuthFormRequest, OAuthError> {
55    let mut request = OAuthFormRequest::new();
56    request.set_body("grant_type", "client_credentials");
57    if let Some(scope) = input.scope {
58        request.set_body("scope", scope);
59    }
60    for resource in input.resource {
61        request.push_body("resource", resource);
62    }
63    get_primary_client_id(&input.options.client_id)
64        .ok_or(OAuthError::MissingOption("client_id"))?;
65    input
66        .options
67        .client_secret_str()
68        .ok_or(OAuthError::MissingOption("client_secret"))?;
69    apply_client_authentication(&mut request, &input.options, input.authentication, true)?;
70    Ok(request)
71}