Struct fxa_client::FirefoxAccount
source · pub struct FirefoxAccount { /* private fields */ }
Expand description
Object representing the signed-in state of an application.
The FirefoxAccount
object is the main interface provided by this crate.
It represents the signed-in state of an application that may be connected to
user’s Firefox Account, and provides methods for inspecting the state of the
account and accessing other services on behalf of the user.
Implementations§
source§impl FirefoxAccount
impl FirefoxAccount
Constructors and state management
These are methods for managing the signed-in state of the application,
either by restoring a previously-saved state via FirefoxAccount::from_json
or by starting afresh with FirefoxAccount::new
.
The application must persist the signed-in state after calling any methods that may alter it. Such methods are marked in the documentation as follows:
💾 This method alters the persisted account state.
After calling any such method, use FirefoxAccount::to_json
to serialize
the modified account state and persist the resulting string in application
settings.
sourcepub fn new(
content_url: &str,
client_id: &str,
redirect_uri: &str,
token_server_url_override: &Option<String>
) -> FirefoxAccount
pub fn new(
content_url: &str,
client_id: &str,
redirect_uri: &str,
token_server_url_override: &Option<String>
) -> FirefoxAccount
Create a new FirefoxAccount
instance, not connected to any account.
💾 This method alters the persisted account state.
This method constructs as new FirefoxAccount
instance configured to connect
the application to a user’s account.
Arguments
content_url
- the URL of the Firefox Accounts server to use- For example, use
https://accounts.firefox.com
for the main Mozilla-hosted service.
- For example, use
client_id
- the registered OAuth client id of the application.redirect_uri
- the registered OAuth redirect URI of the application.token_server_url_override
: optionally, URL for the user’s Sync Tokenserver.- This can be used to support users who self-host their sync data.
If
None
then it will default to the Mozilla-hosted Sync server.
- This can be used to support users who self-host their sync data.
If
sourcepub fn from_json(data: &str) -> Result<FirefoxAccount, FxaError>
pub fn from_json(data: &str) -> Result<FirefoxAccount, FxaError>
Restore a FirefoxAccount
instance from serialized state.
Given a JSON string previously obtained from FirefoxAccount::to_json
, this
method will deserialize it and return a live FirefoxAccount
instance.
⚠️ Warning: since the serialized state contains access tokens, you should
not call from_json
multiple times on the same data. This would result
in multiple live objects sharing the same access tokens and is likely to
produce unexpected behaviour.
sourcepub fn to_json(&self) -> Result<String, FxaError>
pub fn to_json(&self) -> Result<String, FxaError>
Save current state to a JSON string.
This method serializes the current account state into a JSON string, which the application can use to persist the user’s signed-in state across restarts. The application should call this method and update its persisted state after any potentially-state-changing operation.
⚠️ Warning: the serialized state may contain encryption keys and access tokens that let anyone holding them access the user’s data in Firefox Sync and/or other FxA services. Applications should take care to store the resulting data in a secure fashion, as appropriate for their target platform.
source§impl FirefoxAccount
impl FirefoxAccount
Signing in and out
These are methods for managing the signed-in state, such as authenticating via an OAuth flow or disconnecting from the user’s account.
The Firefox Accounts system supports two methods for connecting an application to a user’s account:
-
A traditional OAuth flow, where the user is directed to a webpage to enter their account credentials and then redirected back to the application. This is exposed by the
begin_oauth_flow
method. -
A device pairing flow, where the user scans a QRCode presented by another app that is already connected to the account, which then directs them to a webpage for a simplified signing flow. This is exposed by the
begin_pairing_flow
method.
Technical details of the pairing flow can be found in the Firefox Accounts documentation hub.
sourcepub fn begin_oauth_flow(
&self,
scopes: &[String],
entrypoint: &str,
metrics: Option<MetricsParams>
) -> Result<String, FxaError>
pub fn begin_oauth_flow(
&self,
scopes: &[String],
entrypoint: &str,
metrics: Option<MetricsParams>
) -> Result<String, FxaError>
Initiate a web-based OAuth sign-in flow.
This method initializes some internal state and then returns a URL at which the user may perform a web-based authorization flow to connect the application to their account. The application should direct the user to the provided URL.
When the resulting OAuth flow redirects back to the configured redirect_uri
,
the query parameters should be extracting from the URL and passed to the
complete_oauth_flow
method to finalize
the signin.
Arguments
scopes
- list of OAuth scopes to request.- The requested scopes will determine what account-related data the application is able to access.
entrypoint
- metrics identifier for UX entrypoint.- This parameter is used for metrics purposes, to identify the UX entrypoint from which the user triggered the signin request. For example, the application toolbar, on the onboarding flow.
metrics
- optionally, additional metrics tracking paramters.- These will be included as query parameters in the resulting URL.
Get the URL at which to begin a device-pairing signin flow.
If the user wants to sign in using device pairing, call this method and then
direct them to visit the resulting URL on an already-signed-in device. Doing
so will trigger the other device to show a QR code to be scanned, and the result
from said QR code can be passed to begin_pairing_flow
.
sourcepub fn begin_pairing_flow(
&self,
pairing_url: &str,
scopes: &[String],
entrypoint: &str,
metrics: Option<MetricsParams>
) -> Result<String, FxaError>
pub fn begin_pairing_flow(
&self,
pairing_url: &str,
scopes: &[String],
entrypoint: &str,
metrics: Option<MetricsParams>
) -> Result<String, FxaError>
Initiate a device-pairing sign-in flow.
Once the user has scanned a pairing QR code, pass the scanned value to this method. It will return a URL to which the application should redirect the user in order to continue the sign-in flow.
When the resulting flow redirects back to the configured redirect_uri
,
the resulting OAuth parameters should be extracting from the URL and passed
to complete_oauth_flow
to finalize
the signin.
Arguments
pairing_url
- the URL scanned from a QR code on another device.scopes
- list of OAuth scopes to request.- The requested scopes will determine what account-related data the application is able to access.
entrypoint
- metrics identifier for UX entrypoint.- This parameter is used for metrics purposes, to identify the UX entrypoint from which the user triggered the signin request. For example, the application toolbar, on the onboarding flow.
metrics
- optionally, additional metrics tracking paramters.- These will be included as query parameters in the resulting URL.
sourcepub fn complete_oauth_flow(&self, code: &str, state: &str) -> Result<(), FxaError>
pub fn complete_oauth_flow(&self, code: &str, state: &str) -> Result<(), FxaError>
Complete an OAuth flow.
💾 This method alters the persisted account state.
At the conclusion of an OAuth flow, the user will be redirect to the
application’s registered redirect_uri
. It should extract the code
and state
parameters from the resulting URL and pass them to this
method in order to complete the sign-in.
Arguments
code
- the OAuth authorization code obtained from the redirect URI.state
- the OAuth state parameter obtained from the redirect URI.
Check authorization status for this application.
💾 This method alters the persisted account state.
Applications may call this method to check with the FxA server about the status
of their authentication tokens. It returns an AuthorizationInfo
struct
with details about whether the tokens are still active.
sourcepub fn disconnect(&self)
pub fn disconnect(&self)
Disconnect from the user’s account.
💾 This method alters the persisted account state.
This method destroys any tokens held by the client, effectively disconnecting from the user’s account. Applications should call this when the user opts to sign out.
The persisted account state after calling this method will contain only the user’s last-seen profile information, if any. This may be useful in helping the user to reconnnect to their account. If reconnecting to the same account is not desired then the application should discard the persisted account state.
source§impl FirefoxAccount
impl FirefoxAccount
User Profile info
These methods can be used to find out information about the connected user.
sourcepub fn get_profile(&self, ignore_cache: bool) -> Result<Profile, FxaError>
pub fn get_profile(&self, ignore_cache: bool) -> Result<Profile, FxaError>
Get profile information for the signed-in user, if any.
💾 This method alters the persisted account state.
This method fetches a Profile
struct with information about the currently-signed-in
user, either by using locally-cached profile information or by fetching fresh data from
the server.
Arguments
ignore_cache
- if true, always hit the server for fresh profile information.
Notes
- Profile information is only available to applications that have been
granted the
profile
scope. - There is currently no API for fetching cached profile information without potentially hitting the server.
- If there is no signed-in user, this method will throw an
Authentication
error.
source§impl FirefoxAccount
impl FirefoxAccount
Device Management
Applications that connect to a user’s account may register additional information about themselves via a “device record”, which allows them to:
- customize how they appear in the user’s account management page
- receive push notifications about events that happen on the account
- participate in the FxA “device commands” ecosystem
For more details on FxA device registration and management, consult the Firefox Accounts Device Registration docs.
sourcepub fn initialize_device(
&self,
name: &str,
device_type: DeviceType,
supported_capabilities: Vec<DeviceCapability>
) -> Result<(), FxaError>
pub fn initialize_device(
&self,
name: &str,
device_type: DeviceType,
supported_capabilities: Vec<DeviceCapability>
) -> Result<(), FxaError>
Create a new device record for this application.
💾 This method alters the persisted account state.
This method registed a device record for the application, providing basic metadata for the device along with a list of supported Device Capabilities for participating in the “device commands” ecosystem.
Applications should call this method soon after a successful sign-in, to ensure they they appear correctly in the user’s account-management pages and when discovered by other devices connected to the account.
Arguments
name
- human-readable display name to use for this applicationdevice_type
- the type of device the application is installed onsupported_capabilities
- the set of capabilities to register for this device in the “device commands” ecosystem.
Notes
- Device registration is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn get_current_device_id(&self) -> Result<String, FxaError>
pub fn get_current_device_id(&self) -> Result<String, FxaError>
Get the device id registered for this application.
Notes
- If the application has not registered a device record, this method will
throw an
Other
error.- (Yeah…sorry. This should be changed to do something better.)
- Device metadata is only visible to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn get_devices(&self, ignore_cache: bool) -> Result<Vec<Device>, FxaError>
pub fn get_devices(&self, ignore_cache: bool) -> Result<Vec<Device>, FxaError>
Get the list of devices registered on the user’s account.
💾 This method alters the persisted account state.
This method returns a list of Device
structs representing all the devices
currently attached to the user’s account (including the current device).
The application might use this information to e.g. display a list of appropriate
send-tab targets.
Arguments
ignore_cache
- if true, always hit the server for fresh profile information.
Notes
- Device metadata is only visible to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn get_attached_clients(&self) -> Result<Vec<AttachedClient>, FxaError>
pub fn get_attached_clients(&self) -> Result<Vec<AttachedClient>, FxaError>
Get the list of all client applications attached to the user’s account.
This method returns a list of AttachedClient
structs representing all the applications
connected to the user’s acount. This includes applications that are registered as a device
as well as server-side services that the user has connected.
This information is really only useful for targetted messaging or marketing purposes, e.g. if the application wants to advertize a related product, but first wants to check whether the user is already using that product.
Notes
- Attached client metadata is only visible to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn set_device_name(&self, display_name: &str) -> Result<(), FxaError>
pub fn set_device_name(&self, display_name: &str) -> Result<(), FxaError>
Update the display name used for this application instance.
💾 This method alters the persisted account state.
This method modifies the name of the current application’s device record, as seen by other applications and in the user’s account management pages.
Arguments
display_name
- the new name for the current device.
Notes
- Device registration is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn clear_device_name(&self) -> Result<(), FxaError>
pub fn clear_device_name(&self) -> Result<(), FxaError>
Clear any custom display name used for this application instance.
💾 This method alters the persisted account state.
This method clears the name of the current application’s device record, causing other applications or the user’s account management pages to have to fill in some sort of default name when displaying this device.
Notes
- Device registration is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn ensure_capabilities(
&self,
supported_capabilities: Vec<DeviceCapability>
) -> Result<(), FxaError>
pub fn ensure_capabilities(
&self,
supported_capabilities: Vec<DeviceCapability>
) -> Result<(), FxaError>
Ensure that the device record has a specific set of capabilities.
💾 This method alters the persisted account state.
This method checks that the currently-registred device record is advertising the given set of capabilities in the FxA “device commands” ecosystem. If not, then it updates the device record to do so.
Applications should call this method on each startup as a way to ensure that their expected set of capabilities is being accurately reflected on the FxA server, and to handle the rollout of new capabilities over time.
Arguments
supported_capabilities
- the set of capabilities to register for this device in the “device commands” ecosystem.
Notes
- Device registration is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn set_push_subscription(
&self,
subscription: DevicePushSubscription
) -> Result<(), FxaError>
pub fn set_push_subscription(
&self,
subscription: DevicePushSubscription
) -> Result<(), FxaError>
Set or update a push subscription endpoint for this device.
💾 This method alters the persisted account state.
This method registers the given webpush subscription with the FxA server, requesting
that is send notifications in the event of any significant changes to the user’s
account. When the application receives a push message at the registered subscription
endpoint, it should decrypt the payload and pass it to the handle_push_message
method for processing.
Arguments
subscription
- theDevicePushSubscription
details to register with the server.
Notes
- Device registration is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn handle_push_message(
&self,
payload: &str
) -> Result<Vec<AccountEvent>, FxaError>
pub fn handle_push_message(
&self,
payload: &str
) -> Result<Vec<AccountEvent>, FxaError>
Process and respond to server-delivered account update messages.
💾 This method alters the persisted account state.
Applications should call this method whenever they receive a push notiication on subscription
endpoint previously registered with the Firefox Accounts server. Such messages typically indicate
a noteworthy change of state on the user’s account, such as an update to their profile information
or the disconnection of a client. The FirefoxAccount
struct will update its internl state
accordingly and return a list of AccountEvent
structs describing the events, which the application
may use for further processing.
sourcepub fn poll_device_commands(
&self
) -> Result<Vec<IncomingDeviceCommand>, FxaError>
pub fn poll_device_commands(
&self
) -> Result<Vec<IncomingDeviceCommand>, FxaError>
Poll the server for any pending device commands.
💾 This method alters the persisted account state.
Applications that have registered one or more DeviceCapability
s with the server can use
this method to check whether other devices on the account have sent them any commands.
It will return a list of IncomingDeviceCommand
structs for the application to process.
Notes
- Device commands are typically delivered via push message and the
CommandReceived
event. Polling should only be used as a backup delivery mechanism, f the application has reason to believe that push messages may have been missed. - Device commands functionality is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
sourcepub fn send_single_tab(
&self,
target_device_id: &str,
title: &str,
url: &str
) -> Result<(), FxaError>
pub fn send_single_tab(
&self,
target_device_id: &str,
title: &str,
url: &str
) -> Result<(), FxaError>
Use device commands to send a single tab to another device.
💾 This method alters the persisted account state.
If a device on the account has registered the SendTab
capability, this method can be used to send it a tab.
Notes
- If the given device id does not existing or is not capable of receiving tabs,
this method will throw an
Other
error.- (Yeah…sorry. This should be changed to do something better.)
- It is not currently possible to send a full
SendTabPayload
to another device, but that’s purely an API limitation that should go away in future. - Device commands functionality is only available to applications that have been
granted the
https://identity.mozilla.com/apps/oldsync
scope.
source§impl FirefoxAccount
impl FirefoxAccount
Account Management URLs
Signed-in applications should not attempt to perform an account-level management (such as changing profile data or managing devices) using native UI. Instead, they should offer the user the opportunity to visit their account managment pages on the web.
The methods in this section provide URLs at which the user can perform various account-management activities.
sourcepub fn get_token_server_endpoint_url(&self) -> Result<String, FxaError>
pub fn get_token_server_endpoint_url(&self) -> Result<String, FxaError>
Get the URL at which to access the user’s sync data.
💾 This method alters the persisted account state.
sourcepub fn get_connection_success_url(&self) -> Result<String, FxaError>
pub fn get_connection_success_url(&self) -> Result<String, FxaError>
Get a URL which shows a “successfully connceted!” message.
💾 This method alters the persisted account state.
Applications can use this method after a successful signin, to redirect the user to a success message displayed in web content rather than having to implement their own native success UI.
sourcepub fn get_manage_account_url(
&self,
entrypoint: &str
) -> Result<String, FxaError>
pub fn get_manage_account_url(
&self,
entrypoint: &str
) -> Result<String, FxaError>
Get a URL at which the user can manage their account and profile data.
💾 This method alters the persisted account state.
Applications should link the user out to this URL from an appropriate place in their signed-in settings UI.
Arguments
entrypoint
- metrics identifier for UX entrypoint.- This parameter is used for metrics purposes, to identify the UX entrypoint from which the user followed the link.
sourcepub fn get_manage_devices_url(
&self,
entrypoint: &str
) -> Result<String, FxaError>
pub fn get_manage_devices_url(
&self,
entrypoint: &str
) -> Result<String, FxaError>
Get a URL at which the user can manage the devices connected to their account.
💾 This method alters the persisted account state.
Applications should link the user out to this URL from an appropriate place in their signed-in settings UI. For example, “Manage your devices…” may be a useful link to place somewhere near the device list in the send-tab UI.
Arguments
entrypoint
- metrics identifier for UX entrypoint.- This parameter is used for metrics purposes, to identify the UX entrypoint from which the user followed the link.
source§impl FirefoxAccount
impl FirefoxAccount
Token Management
A signed-in appliction will typically hold a number of different tokens associated with the user’s account, including:
- An OAuth
refresh_token
, representing their ongoing connection to the account and the scopes that have been granted. - Short-lived OAuth
access_token
s that can be used to access resources on behalf of the user. - Optionally, a
session_token
that gives full control over the user’s account, typically managed on behalf of web content that runs within the context of the application.
sourcepub fn get_access_token(
&self,
scope: &str,
ttl: Option<i64>
) -> Result<AccessTokenInfo, FxaError>
pub fn get_access_token(
&self,
scope: &str,
ttl: Option<i64>
) -> Result<AccessTokenInfo, FxaError>
Get a short-lived OAuth access token for the user’s account.
💾 This method alters the persisted account state.
Applications that need to access resources on behalf of the user must obtain an
access_token
in order to do so. For example, an access token is required when
fetching the user’s profile data, or when accessing their data stored in Firefox Sync.
This method will obtain and return an access token bearing the requested scopes, either from a local cache of previously-issued tokens, or by creating a new one from the server.
Arguments
scope
- the OAuth scope to be granted by the token.- This must be one of the scopes requested during the signin flow.
- Only a single scope is supported; for multiple scopes request multiple tokens.
ttl
- optionally, the time for which the token should be valid, in seconds.
Notes
- If the application receives an authorization error when trying to use the resulting
token, it should call
clear_access_token_cache
before requesting a fresh token.
sourcepub fn get_session_token(&self) -> Result<String, FxaError>
pub fn get_session_token(&self) -> Result<String, FxaError>
Get the session token for the user’s account, if one is available.
💾 This method alters the persisted account state.
Applications that function as a web browser may need to hold on to a session token on behalf of Firefox Accounts web content. This method exists so that they can retreive it an pass it back to said web content when required.
Notes
- Please do not attempt to use the resulting token to directly make calls to the Firefox Accounts servers! All account management functionality should be performed in web content.
- A session token is only available to applications that have requested the
https://identity.mozilla.com/tokens/session
scope.
sourcepub fn handle_session_token_change(
&self,
session_token: &str
) -> Result<(), FxaError>
pub fn handle_session_token_change(
&self,
session_token: &str
) -> Result<(), FxaError>
Update the stored session token for the user’s account.
💾 This method alters the persisted account state.
Applications that function as a web browser may need to hold on to a session token on behalf of Firefox Accounts web content. This method exists so that said web content signals that it has generated a new session token, the stored value can be updated to match.
Arguments
session_token
- the new session token value provided from web content.
Create a new OAuth authorization code using the stored session token.
When a signed-in application receives an incoming device pairing request, it can use this method to grant the request and generate a corresponding OAuth authorization code. This code would then be passed back to the connecting device over the pairing channel (a process which is not currently supported by any code in this component).
Arguments
params
- the OAuth parameters from the incoming authorization request
sourcepub fn clear_access_token_cache(&self)
pub fn clear_access_token_cache(&self)
Clear the access token cache in response to an auth failure.
💾 This method alters the persisted account state.
Applications that receive an authentication error when trying to use an access token, should call this method before creating a new token and retrying the failed operation. It ensures that the expired token is removed and a fresh one generated.
source§impl FirefoxAccount
impl FirefoxAccount
Telemetry Methods
This component does not currently submit telemetry via Glean, but it does gather a small amount of telemetry about send-tab that the application may submit on its behalf.
sourcepub fn gather_telemetry(&self) -> Result<String, FxaError>
pub fn gather_telemetry(&self) -> Result<String, FxaError>
Collect and return telemetry about send-tab attempts.
Applications that register the SendTab
capability
should also arrange to submit “sync ping” telemetry. Calling this method will
return a JSON string of telemetry data that can be incorporated into that ping.
Sorry, this is not particularly carefully documented because it is intended as a stop-gap until we get native Glean support. If you know how to submit a sync ping, you’ll know what to do with the contents of the JSON string.
source§impl FirefoxAccount
impl FirefoxAccount
Migration Support Methods
Some applications may have existing signed-in account state from a bespoke implementation of the Firefox Accounts signin protocol, but want to move to using this component in order to reduce maintenance costs.
The sign-in state for a legacy FxA integration would typically consist of a session token and a pair of cryptographic keys used for accessing Firefox Sync. The methods in this section can be used to help migrate from such legacy state into state that’s suitable for use with this component.
sourcepub fn migrate_from_session_token(
&self,
session_token: &str,
k_sync: &str,
k_xcs: &str,
copy_session_token: bool
) -> Result<FxAMigrationResult, FxaError>
pub fn migrate_from_session_token(
&self,
session_token: &str,
k_sync: &str,
k_xcs: &str,
copy_session_token: bool
) -> Result<FxAMigrationResult, FxaError>
Sign in by using legacy session-token state.
💾 This method alters the persisted account state.
When migrating to use the FxA client component, create a FirefoxAccount
instance
and then pass any legacy sign-in state to this method. It will attempt to use the
session token to bootstrap a full internal state of OAuth tokens, and will store the
provided credentials internally in case it needs to retry after e.g. a network failure.
Arguments
session_token
- the session token from legacy sign-in statek_sync
- the Firefox Sync encryption key from legacy sign-in statek_xcs
- the Firefox Sync “X-Client-State: value from legacy sign-in statecopy_session_token
- if true, copy the given session token rather than using it directly
Notes
- If successful, this method will return an
FxAMigrationResult
with some statistics about the migration process. - If unsuccessful this method will throw an error, but you may be able to retry the migration again at a later time.
- Use is_in_migration_state to check whether the persisted account state includes a a pending migration that can be retried.
sourcepub fn retry_migrate_from_session_token(
&self
) -> Result<FxAMigrationResult, FxaError>
pub fn retry_migrate_from_session_token(
&self
) -> Result<FxAMigrationResult, FxaError>
Retry a previously failed migration from legacy session-token state.
💾 This method alters the persisted account state.
If an earlier call to migrate_from_session_token
failed, it may have stored the provided state for retrying at a later time. Call this method
in order to execute such a retry.
sourcepub fn is_in_migration_state(&self) -> MigrationState
pub fn is_in_migration_state(&self) -> MigrationState
Check for a previously failed migration from legacy session-token state.
If an earlier call to migrate_from_session_token
failed, it may have stored the provided state for retrying at a later time. Call this method
in check whether such state exists, then retry at an appropriate time.