Skip to main content

UserToken

Struct UserToken 

Source
pub struct UserToken {
    pub code: String,
    pub access_token: String,
    pub data_access_expiration_time: String,
    pub expires_in: String,
    pub long_lived_token: String,
    pub state: String,
    pub login_error: Option<LoginError>,
    /* private fields */
}
Expand description

UserToken is Obtain after a successful login to Facebook.

This kind of access token is needed any time the app calls an API to read, modify or write a specific person’s Facebook data on their behalf. User access tokens are generally obtained via a login dialog and require a person to permit your app to obtain one.

The tokens are retrieved from a successful login redirect url from facebook.

The data in the redirect URL depends on the LoginResponseType chosen when building the login url.

By default, a LoginResponseType::CODE is used. This means that the value in response data from facebook will code instead of access_token. And you will need to exchange the code for an access token.

This is recommended by Facebook to be done in server side using the respective method.

§Examples

§Example for when code is the response type

  • Get code at the client side.
use facebook_api_rs::prelude::Config;
use crate::facebook_api_rs::prelude::UserToken;

 let login_response_url =  "redirect_url/?#........................".to_string();
 let user_token =   UserToken::extract_user_tokens(login_response_url);
 // send the code to sever side to exchange for an access_token
 let code = user_token.code;
  • At the server side: exchange code for access_token
use crate::facebook_api_rs::prelude::{UserToken, Config};
   
 let code = "The code sent from client".to_string();
 let config = Config::new("your app_id".to_owned(), "your redirect_uri".to_string());

 let access_token  = UserToken::default()
        .exchange_code_for_access_token_at_server(
        code,
        "your app_secret".to_string(), config);

§Example for when token is the response type

When the response type is a token instead of code, the response data will be an access_token. Ans you will need to verify that at the server side.

  • Get token at the client side.
 use crate::facebook_api_rs::prelude::{UserToken, Config};

 let login_response_url =  "redirect_url/?#........................".to_string();
 let user_token =   UserToken::extract_user_tokens(login_response_url);
// send the access_token to sever for verification
 let access_token  = user_token.access_token;
  • At Server side: Verify the token. The verification can be done by inspecting the access_token gotten from the client which the response will be AccessTokenInformation
 use crate::facebook_api_rs::prelude::{UserToken, Config};
  
 let access_token_information = UserToken::access_token_information(
       "a valid access_token".to_owned(),
         "inspecting_token".to_owned()
       );

For information on verifying of access_token and exchanging of code check Facebook Confirming Identity

§User CANCELED login

let response_url = "YOUR_REDIRECT_URI?
 error_reason=user_denied
 &error=access_denied
 &error_description=Permissions+error";

 use crate::facebook_api_rs::prelude::{UserToken, Config};
// Capture the error
  let user_token =   UserToken::extract_user_tokens(login_response_url).login_error;

Fields§

§code: String

Response data is included as URL parameters and contains code parameter (an encrypted string unique to each login request). This is the default behavior if this parameter is not specified. It’s most useful when your server will be handling the token.

If the login redirect url contain code then you must exchange it for access_token. This should be done at the server.

§access_token: String

access_token is used for API calls

This token is obtained either from exchange with code or direct from the login redirect url. If it is obtained from client side then it should be verified at the server.

§data_access_expiration_time: String

Expires in 90 days based when the user was last active When this 90-day period expires, the user can still access your app — that is, they are still authenticated — but your app can’t access their data. To regain data access, your app must ask the user to re-authorize your app’s permissions.

§expires_in: String

The expiration time of the Access Token

§long_lived_token: String

A long-lived token generally lasts about 60 days These tokens are refreshed once per day, when the person using your app makes a request to Facebook’s servers. If no requests are made, the token will expire after about 60 days and the person will have to go through the login flow again to get a new token.

Note: Long access token can also expire due to other reasons, to check if a given token has expired use the method :

§Example

use facebook_api_rs::prelude::UserToken;
 let valid_token = "".to_owned();
 let debug_token = "".to_owned(); // the token you want check or debug

 UserToken::access_token_information(valid_token, debug_token)
§state: String

A string value created by your app to maintain state between the request and callback.

§login_error: Option<LoginError>

The error that occurs when login. This is mostly a user has “Cancelled” the login. The reason of the error will be available.

Implementations§

Source§

impl UserToken

Source

pub fn new(access_token: String, long_lived_token: String) -> Self

Source

pub fn new_with_url(url: String) -> Self

Source§

impl UserToken

Source

pub fn user_access_tokens(self) -> Self

Source

pub fn extract_user_tokens(url: String) -> UserToken

Extract different tokens and its parameters from a successful login redirect url.

§Argument
  • hash - A String of hash from the redirect url.
§Example
§Example for when code in the response data
  • Get code at the client side.
use facebook_api_rs::prelude::Config;
use crate::facebook_api_rs::prelude::UserToken;
 // The redirect url after login
 let login_response_url =  "redirect_url/?#........................".to_string();

 let user_token =   UserToken::extract_user_tokens(login_response_url);
 // Send the code to sever side to exchange for an access_token
 let code  = user_token.code;
  • At the server side: exchange code for access token
use crate::facebook_api_rs::prelude::{UserToken, Config};
   
   let code = "The code sent from client".to_string();
    let config = Config::new("your app_id".to_owned(), "your redirect_uri".to_string());

 let access_token  = UserToken::default()
        .exchange_code_for_access_token_at_server(
        code,
        "your app_secret".to_string(), config);
§Example for when token is the response type

When the response type is a token instead of code, the response data will be an access_token. And you will need to verify that at the server side.

  • Get token at the client side.
 use crate::facebook_api_rs::prelude::{UserToken, Config};

 let login_response_url =  "redirect_url/?#........................".to_string();

 let user_token =   UserToken::extract_user_tokens(login_response_url);
// send the access_token to sever verification
 let access_token  = user_token.access_token;
  • At Server side: verified the access_token

At the server side inspect the access_token gotten from the client

 use crate::facebook_api_rs::prelude::{UserToken, Config};
  
 let access_token_information = UserToken::access_token_information(
       "a valid access_token".to_owned(),
         "inspecting_token".to_owned()
       );
§Panic

It will panic when :

  • Login error -> If for any reason the login failed then the response url will contain an error. If the URL with an error is passed in, panic will occur with a message from the response url.

  • Empty url query parameters -> If no query parameters if found in the url, panic will occur.

Source

pub async fn exchange_short_live_for_long_live_token( self, short_live_token: String, app_secret: String, client_id: String, redirect_uri: String, ) -> Result<ExchangeToken, ClientErr>

Source

pub async fn app_access_token_at_server( self, app_secret: String, app_id: String, ) -> Result<String, ClientErr>

Source

pub async fn exchange_code_for_access_token_at_server( self, code: String, app_secret: String, client_id: String, redirect_uri: String, ) -> Result<ExchangeToken, ClientErr>

Exchanging Code for an access_token

§Argument
  • code- A string gotten from the extracted from login redirect url
  • app_secret- The app secret from your App Dashboard
  • config - A Config struct
Source

pub async fn access_token_information( valid_access_token: String, debug_access_token: String, ) -> Result<AccessTokenInformation, ClientErr>

This method will make a get request to facebook api to return information about a given token

§Arguments
  • valid_access_token - A String of a valid access token. This could be app_token, user_token, or page_token
  • debug_access_token - A String of the access token you intend to get information.

The response data is a struct

 use crate::facebook_api_rs::prelude::{AccessTokenInformation};

For more information about Facebook debug token check facebook debug token api

Source

pub fn set_url(self, url: String) -> Self

Trait Implementations§

Source§

impl Clone for UserToken

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for UserToken

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for UserToken

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for UserToken

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

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

fn in_current_span(self) -> Instrumented<Self> ⓘ

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

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more