#[repr(transparent)]
pub struct ClientSecret(_);
Expand description

A Client Secret

Implementations§

Constructs a new ClientSecret

Constructs a new ClientSecret from a static reference

Converts this ClientSecret into a Box<ClientSecretRef>

This will drop any excess capacity.

Unwraps the underlying String value

Methods from Deref<Target = ClientSecretRef>§

Provides access to the underlying value as a string slice.

Examples found in repository?
src/types.rs (line 89)
89
    pub fn secret(&self) -> &str { self.as_str() }

Get the secret from this string.

This function is the same as ClientSecret::as_str, but has another name for searchability, prefer to use this function.

Examples found in repository?
src/lib.rs (line 221)
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
    pub fn refresh_token_request(
        &self,
        client_id: &ClientId,
        client_secret: &ClientSecret,
    ) -> http::Request<Vec<u8>> {
        use http::{HeaderMap, Method};
        use std::collections::HashMap;

        let mut params = HashMap::new();
        params.insert("client_id", client_id.as_str());
        params.insert("client_secret", client_secret.secret());
        params.insert("grant_type", "refresh_token");
        params.insert("refresh_token", self.secret());

        construct_request(
            &crate::TOKEN_URL,
            &params,
            HeaderMap::new(),
            Method::POST,
            vec![],
        )
    }
More examples
Hide additional examples
src/tokens/app_access_token.rs (line 196)
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    pub fn get_app_access_token_request(
        client_id: &ClientIdRef,
        client_secret: &ClientSecretRef,
        scopes: Vec<Scope>,
    ) -> http::Request<Vec<u8>> {
        use http::{HeaderMap, Method};
        use std::collections::HashMap;
        let scope: String = scopes
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
            .join(" ");
        let mut params = HashMap::new();
        params.insert("client_id", client_id.as_str());
        params.insert("client_secret", client_secret.secret());
        params.insert("grant_type", "client_credentials");
        params.insert("scope", &scope);

        crate::construct_request(
            &crate::TOKEN_URL,
            &params,
            HeaderMap::new(),
            Method::POST,
            vec![],
        )
    }
src/tokens/user_token.rs (line 193)
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
    pub async fn mock_token<'a, C>(
        http_client: &'a C,
        client_id: ClientId,
        client_secret: ClientSecret,
        user_id: impl AsRef<str>,
        scopes: Vec<Scope>,
    ) -> Result<UserToken, UserTokenExchangeError<<C as Client<'a>>::Error>>
    where
        C: Client<'a>,
    {
        use http::{HeaderMap, Method};
        use std::collections::HashMap;

        let user_id = user_id.as_ref();
        let scope_str = scopes.as_slice().join(" ");
        let mut params = HashMap::new();
        params.insert("client_id", client_id.as_str());
        params.insert("client_secret", client_secret.secret());
        params.insert("grant_type", "user_token");
        params.insert("scope", &scope_str);
        params.insert("user_id", user_id);

        let req = crate::construct_request(
            &crate::AUTH_URL,
            &params,
            HeaderMap::new(),
            Method::POST,
            vec![],
        );

        let resp = http_client
            .req(req)
            .await
            .map_err(UserTokenExchangeError::RequestError)?;
        let response = crate::id::TwitchTokenResponse::from_response(&resp)?;

        UserToken::from_existing(
            http_client,
            response.access_token,
            response.refresh_token,
            client_secret,
        )
        .await
        .map_err(Into::into)
    }

    /// Set the client secret
    pub fn set_secret(&mut self, secret: Option<ClientSecret>) { self.client_secret = secret }
}

#[cfg_attr(feature = "client", async_trait::async_trait)]
impl TwitchToken for UserToken {
    fn token_type() -> super::BearerTokenType { super::BearerTokenType::UserToken }

    fn client_id(&self) -> &ClientId { &self.client_id }

    fn token(&self) -> &AccessToken { &self.access_token }

    fn login(&self) -> Option<&UserNameRef> { Some(&self.login) }

    fn user_id(&self) -> Option<&UserIdRef> { Some(&self.user_id) }

    #[cfg(feature = "client")]
    async fn refresh_token<'a, C>(
        &mut self,
        http_client: &'a C,
    ) -> Result<(), RefreshTokenError<<C as Client<'a>>::Error>>
    where
        Self: Sized,
        C: Client<'a>,
    {
        if let Some(client_secret) = self.client_secret.clone() {
            let (access_token, expires, refresh_token) =
                if let Some(token) = self.refresh_token.take() {
                    token
                        .refresh_token(http_client, &self.client_id, &client_secret)
                        .await?
                } else {
                    return Err(RefreshTokenError::NoRefreshToken);
                };
            self.access_token = access_token;
            self.expires_in = expires;
            self.refresh_token = refresh_token;
            Ok(())
        } else {
            return Err(RefreshTokenError::NoClientSecretFound);
        }
    }

    fn expires_in(&self) -> std::time::Duration {
        if !self.never_expiring {
            self.expires_in
                .checked_sub(self.struct_created.elapsed())
                .unwrap_or_default()
        } else {
            // We don't return an option here because it's not expected to use this if the token is known to be unexpiring.
            // TODO: Use Duration::MAX
            std::time::Duration::new(u64::MAX, 1_000_000_000 - 1)
        }
    }

    fn scopes(&self) -> &[Scope] { self.scopes.as_slice() }
}

/// Builder for [OAuth authorization code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow)
///
/// See [`ImplicitUserTokenBuilder`] for the [OAuth implicit code flow](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-implicit-code-flow) (does not require Client Secret)
pub struct UserTokenBuilder {
    pub(crate) scopes: Vec<Scope>,
    pub(crate) csrf: Option<crate::types::CsrfToken>,
    pub(crate) force_verify: bool,
    pub(crate) redirect_url: url::Url,
    client_id: ClientId,
    client_secret: ClientSecret,
}

impl UserTokenBuilder {
    /// Create a [`UserTokenBuilder`]
    ///
    /// # Notes
    ///
    /// The `url` crate converts empty paths into "/" (such as `https://example.com` into `https://example.com/`),
    /// which means that you'll need to add `https://example.com/` to your redirect URIs (note the "trailing" slash) if you want to use an empty path.
    ///
    /// To avoid this, use a path such as `https://example.com/twitch/register` or similar instead, where the `url` crate would not add a trailing `/`.
    pub fn new(
        client_id: impl Into<ClientId>,
        client_secret: impl Into<ClientSecret>,
        redirect_url: url::Url,
    ) -> UserTokenBuilder {
        UserTokenBuilder {
            scopes: vec![],
            csrf: None,
            force_verify: false,
            redirect_url,
            client_id: client_id.into(),
            client_secret: client_secret.into(),
        }
    }

    /// Add scopes to the request
    pub fn set_scopes(mut self, scopes: Vec<Scope>) -> Self {
        self.scopes = scopes;
        self
    }

    /// Add a single scope to request
    pub fn add_scope(&mut self, scope: Scope) { self.scopes.push(scope); }

    /// Enable or disable function to make the user able to switch accounts if needed.
    pub fn force_verify(mut self, b: bool) -> Self {
        self.force_verify = b;
        self
    }

    /// Generate the URL to request a code.
    ///
    /// Step 1. in the [guide](https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-authorization-code-flow)
    pub fn generate_url(&mut self) -> (url::Url, crate::types::CsrfToken) {
        let csrf = crate::types::CsrfToken::new_random();
        self.csrf = Some(csrf.clone());
        let mut url = crate::AUTH_URL.clone();

        let auth = vec![
            ("response_type", "code"),
            ("client_id", self.client_id.as_str()),
            ("redirect_uri", self.redirect_url.as_str()),
            ("state", csrf.as_str()),
        ];

        url.query_pairs_mut().extend_pairs(auth);

        if !self.scopes.is_empty() {
            url.query_pairs_mut()
                .append_pair("scope", &self.scopes.as_slice().join(" "));
        }

        if self.force_verify {
            url.query_pairs_mut().append_pair("force_verify", "true");
        };

        (url, csrf)
    }

    /// Set the CSRF token.
    ///
    /// Hidden because you should preferably not use this.
    #[doc(hidden)]
    pub fn set_csrf(&mut self, csrf: crate::types::CsrfToken) { self.csrf = Some(csrf); }

    /// Check if the CSRF is valid
    pub fn csrf_is_valid(&self, csrf: &str) -> bool {
        if let Some(csrf2) = &self.csrf {
            csrf2.secret() == csrf
        } else {
            false
        }
    }

    /// Get the request for getting a [TwitchTokenResponse](crate::id::TwitchTokenResponse), to be used in [UserToken::from_response].
    ///
    /// # Examples
    ///
    /// ```rust
    /// use twitch_oauth2::{tokens::UserTokenBuilder, id::TwitchTokenResponse};
    /// use url::Url;
    /// let callback_url = Url::parse("http://localhost/twitch/register")?;
    /// let mut builder = UserTokenBuilder::new("myclientid", "myclientsecret", callback_url);
    /// let (url, _csrf_code) = builder.generate_url();
    ///
    /// // Direct the user to this url.
    /// // Later when your server gets a response on `callback_url` with `?code=xxxxxxx&state=xxxxxxx&scope=aa%3Aaa+bb%3Abb`
    ///
    /// // validate the state
    /// # let state_in_query = _csrf_code.secret();
    /// if !builder.csrf_is_valid(state_in_query) {
    ///     panic!("state mismatched")
    /// }
    /// // and then get your token
    /// # let code_in_query = _csrf_code.secret();
    /// let request = builder.get_user_token_request(code_in_query);
    ///
    /// // use your favorite http client
    ///
    /// let response: http::Response<Vec<u8>> = client_req(request);
    /// let twitch_response = TwitchTokenResponse::from_response(&response)?;
    ///
    /// // you now have a access token, do what you want with it.
    /// // You're recommended to convert it into a `UserToken` via `UserToken::from_response`
    ///
    /// // You can validate the access_token like this
    /// let validated_req = twitch_response.access_token.validate_token_request();
    /// # fn client_req(_: http::Request<Vec<u8>>) -> http::Response<Vec<u8>> { http::Response::new(
    /// # r#"{"access_token":"rfx2uswqe8l4g1mkagrvg5tv0ks3","expires_in":14124,"refresh_token":"5b93chm6hdve3mycz05zfzatkfdenfspp1h1ar2xxdalen01","scope":["channel:moderate","chat:edit","chat:read"],"token_type":"bearer"}"#.bytes().collect()
    /// # ) }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn get_user_token_request(&self, code: &str) -> http::Request<Vec<u8>> {
        use http::{HeaderMap, Method};
        use std::collections::HashMap;
        let mut params = HashMap::new();
        params.insert("client_id", self.client_id.as_str());
        params.insert("client_secret", self.client_secret.secret());
        params.insert("code", code);
        params.insert("grant_type", "authorization_code");
        params.insert("redirect_uri", self.redirect_url.as_str());

        crate::construct_request(
            &crate::TOKEN_URL,
            &params,
            HeaderMap::new(),
            Method::POST,
            vec![],
        )
    }

Trait Implementations§

Converts this type into a shared reference of the (usually inferred) input type.
Converts this type into a shared reference of the (usually inferred) input type.
Immutably borrows from an owned value. Read more
Immutably borrows from an owned value. Read more
Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The resulting type after dereferencing.
Dereferences the value.
Deserialize this value from the given Serde deserializer. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
The associated error which can be returned from parsing.
Parses a string s to return a value of this type. Read more
Feeds this value into the given Hasher. Read more
Feeds a slice of this type into the given Hasher. Read more
This method returns an Ordering between self and other. Read more
Compares and returns the maximum of two values. Read more
Compares and returns the minimum of two values. Read more
Restrict a value to a certain interval. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method tests for self and other values to be equal, and is used by ==. Read more
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason. Read more
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more
Compare self to key and return true if they are equal.

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more