Auth Connect
Ionic Auth Connect handles logging in and/or registering a user with an authentication provider (such as Auth0, Azure AD, AWS Cognito, or Okta) using industry standard OAuth/OpenId Connect on iOS, Android, or on the web.
When used with Ionic Identity Vault, it provides a complete security solution for authentication and storage of logged-in credentials.
Auth Connect also allows your app to support multiple authentication providers. Should you need to change providers, easily switch between them without having to develop a new solution. Learn more.
#
Demo AppWe have a demo app available that shows the complete login/logout experience using Auth0. Swap the Auth0 configuration in the IonicAuthOptions
object to switch to a different auth provider.
Capacitor users will need to manually update the native project config files.
For Android, update the manifest file located at android/app/src/main/AndroidManifest.xml by adding the following intents next to the other intents in the main activity node:
For iOS, update the file located at ios/App/App/Info.plist by adding the following inside the existing CFBundleURLTypes node:
Note: You will need to update the
$AUTH_URL_SCHEME
placeholder with the bundle id of your app in both files when using Capacitor.
#
Configuring Auth ConnectThe main entry point into Auth Connect is done via the IonicAuth class. To configure IonicAuth
, you pass in a configuration object when creating a new instance of the class.
This is done by passing in an instance of IonicAuthOptions to the IonicAuth class. The IonicAuth class is the main interface exposed by the Auth Connect plugin, and is expected to be subclassed for specific behaviors and/or events.
#
Supported ProvidersLeveraging the OAuth/OpenId Connect protocols, Auth Connect supports:
#
WorkflowThe typical Auth Connect workflow consists of:
- Your client app instantiates the Auth Connect Plugin, passing in the IonicAuthOptions object. Configure it based on the chosen auth provider.
- On app load, the hosting app calls IsAuthenticated to check if the user is logged in already.
- If the user isn't logged in, redirect the app to a Login page and call the Login method. Auth Connect loads the chosen auth provider's login page.
- The app user enters their username and password and taps the provider's login button.
- On success, Auth Connect automatically retrieves and stores the user's access token. The onLoginSuccess method is fired, and the app can redirect to the desired protected homepage.
- The IsAuthenticated method can be called at any point to refresh the access token.
- Use GetAccessToken to retrieve the access token if making any API requests to the auth provider.
Note: Web apps using the current mode need to implement callback handlers on login and logout
#
Web Configuration OptionsWhen using Auth Connect in a web app, you have two options on how the login window will appear for your users. The window can either pop up in a new window/tab (known as "POPUP" mode), or it can occur in the current window ("CURRENT" mode).
Here's a visual comparison:
#
Popup ModePopup mode will pop open a new window/tab to the authentication provider, and after the user authenticates, the window will close and the user will be back at your app.
Popup mode is the default, but you can explicitly specify it by setting the implicitLogin option to "POPUP" in the IonicAuthOptions
configuraiton.
When using popup mode, you don't want to do any type of logic or page redirection in your redirectUri
or logoutUrl
pages. Once the user is done authenticating, the auth provider will redirect back to these pages, and Auth Connect will detect this and close the window.
Since these pages might briefly appear to your users, we recommend either keeping the page blank or have a simple branded page that they will see before the window closes.
#
Current ModeCurrent mode redirects the user to the authentication provider in their current window, so they will temporarily leave your app and be returned to the redirectUri
after authentication is done.
To use current mode, set impliciLogin
to "CURRENT" in the IonicAuthOptions
configuration.
When using current mode, you need to finish handling the login/logout process in the redirectUri
and logoutUrl
pages. This is required because in current mode, the user leaves your app completely, and Auth Connect needs to know when the user is done authenticating. To do so, use the handleLoginCallback, and handleLogoutCallback methods respectively:
#
Testing LocallyTo test an Ionic app using Auth Connect locally, configure IonicAuthOptions
to use http://localhost:8100/
as the base URL for properties such as redirectUri
and logoutUrl
. Then, run the ionic serve
command.
#
Checking Authentication StatusAuth Connect provides the isAuthenticated()
convenience method for checking if there is a current session and refreshing that session if it is already expired. However, there are cases where you may want to implement your own method for checking if the user is authenticated. An example of needing to do this would be to handle checking the authentication status when the device is offline.
The isAuthenticated()
method relies on the application having a connection to the internet because if the access token is expired, it will automatically attempt to refresh that token with the authentication provider. If the device is not connected to the network during this check, the refresh attempt will fail and the method will report back that the user is not currently authenticated.
Auth Connect provides access to the various building blocks necessary to create your own method for checking authentication status. A simple example for gracefully handling offline might look like the following:
#
Microsoft Edge (Pre-Chromium) SupportDue to a bug in the pre-Chromium version of Edge, you cannot overide a method in a subclass.
For instance, it is common to create a class that extends IonicAuth
like this:
If you need to support the pre-Chromium version of Edge, you will need to write your own method in the subclass that calls into the base class as follows:
You will then need to change external references from this.authentication.isAuthenticated()
to this.authentication.myAppIsAuthenticated()
(the name is not important so much as the fact that you are not overriding the base class method, pick a name that makes sense to you).
You will also need to use the CURRENT
behavior for implicitLogin
on Edge.
Note: this is only required if you need to support pre-Chromium Edge browsers. If you are creating a pure hybrid-native app or otherwise have no reason to support pre-Chromium Edge, then you can override methods like isAuthenticated()
in the usual manner.
#
Upgrading to v3.0.03.0.0 drops support for IE11 but otherwise is a drop-in replacement for 2.x.
#
Upgrading to v2.0.0- Upgrade your app to use
cordova-android
9.x (see the 9.0.0 milestone for progress) or Capacitor 2.x. - Install the new plugin version.
#
API DocumentationYou can find the API and interface documentation for everything below. The main classes to pay attention to are:
- IonicAuth
- IonicAuthOptions
- TokenStorageProvider (if Ionic Identity Vault is not being used.)# Auth Connect
#
Index#
Interfaces#
Variables#
Interfaces#
IIonicAuthIIonicAuth:
#
additionalLoginParameters▸ additionalLoginParameters(parameters: object
): void
Parameters:
Name | Type | Description |
---|---|---|
parameters | object | any additional parameters that should be added to the login request examples: `login_hint`, `domain_hint` |
Returns: void
#
clearStorage▸ clearStorage(): Promise
<void
>
This method will clear all tokens & data stored in the TokenStorageProvider as well as any metadata relevant to the existing session such as access token expiration time.
Returns: Promise
<void
>
#
expire▸ expire(): Promise
<void
>
expire the current access token, but keep the refresh token, useful for testing
Returns: Promise
<void
>
#
getAccessToken▸ getAccessToken(tokenName?: undefined
| string
, scopes?: undefined
| string
): Promise
<string
| undefined
>
get the access token, once logged in, for API calls
Parameters:
Name | Type | Description |
---|---|---|
Optional tokenName | undefined | string | Optional token name, only used when multiple tokens are required (Azure specific feature). |
Optional scopes | undefined | string | The scopes for the access token. |
Returns: Promise
<string
| undefined
>
#
getAuthResponse▸ getAuthResponse(): Promise
<any
| undefined
>
get the full original auth response
Returns: Promise
<any
| undefined
>
#
getIdToken▸ getIdToken(): Promise
<IDTokenType
| undefined
>
get the parsed id token, includes requested scope values
Returns: Promise
<IDTokenType
| undefined
>
#
getRefreshToken▸ getRefreshToken(): Promise
<string
| undefined
>
get the refresh token if available
Returns: Promise
<string
| undefined
>
#
handleCallback▸ handleCallback(url: string
): Promise
<AuthResult
>
called by the hosting app when callbacks happen, these will be to the URL specified in the options for LogoutUrl and RedirectUri
deprecated: Use handleLoginCallback instead
Parameters:
Name | Type | Description |
---|---|---|
url | string | callback url to handle |
Returns: Promise
<AuthResult
>
#
handleLoginCallback▸ handleLoginCallback(url?: undefined
| string
): Promise
<AuthResult
>
called by the hosting app when login callbacks happen, these will be to the URL specified in the options for RedirectUri
Parameters:
Name | Type | Description |
---|---|---|
Optional url | undefined | string | callback url to handle @default defaults to `window.location.href` |
Returns: Promise
<AuthResult
>
#
handleLogoutCallback▸ handleLogoutCallback(): Promise
<void
>
called by the hosting app when logout callbacks happens
Returns: Promise
<void
>
#
isAccessTokenAvailable▸ isAccessTokenAvailable(tokenName?: undefined
| string
): Promise
<boolean
>
check to see if the access token is available
Parameters:
Name | Type | Description |
---|---|---|
Optional tokenName | undefined | string | Optional token name, only used when multiple tokens are required (Azure specific feature). |
Returns: Promise
<boolean
>
#
isAccessTokenExpired▸ isAccessTokenExpired(): Promise
<boolean
>
check to see if the access token is expired
Returns: Promise
<boolean
>
#
isAuthenticated▸ isAuthenticated(): Promise
<boolean
>
check to see if the user is logged in, and refresh the token if needed
Returns: Promise
<boolean
>
#
isRefreshTokenAvailable▸ isRefreshTokenAvailable(): Promise
<boolean
>
check to see if the refresh token is available
Returns: Promise
<boolean
>
#
login▸ login(overrideUrl?: undefined
| string
): Promise
<void
>
Using configuration display the auth provider's login UI.
The overrideUrl parameter should only be used when the default discovery url needs to be overrode. (The known use case is with Azure AD custom user flows/policies.)
Parameters:
Name | Type |
---|---|
Optional overrideUrl | undefined | string |
Returns: Promise
<void
>
#
logout▸ logout(): Promise
<void
>
log the user out
Returns: Promise
<void
>
#
onLoginSuccess▸ onLoginSuccess(response: any
): void
Event handler which can be overridden to handle successful login events
Parameters:
Name | Type |
---|---|
response | any |
Returns: void
#
onLogout▸ onLogout(): void
Event handler which can be overridden to handle successful logout events
Returns: void
#
refreshSession▸ refreshSession(tokenName?: undefined
| string
): Promise
<void
>
refresh the session, throws if refresh token is invalid or missing
Parameters:
Name | Type | Description |
---|---|---|
Optional tokenName | undefined | string | Optional token name, only used when multiple tokens are required (Azure specific feature). |
Returns: Promise
<void
>
#
IonicAuthOptionsIonicAuthOptions:
Provided by the hosting app, this interface allows the hosting app to configure, and provide information needed to login, logout.
<Optional>
androidToolbarColor#
● androidToolbarColor: undefined
| string
setting to allow the toolbar color of the android webview control to be set. Takes a string that can be parsed as a color by android.graphics.Color.parseColor
<Optional>
audience#
● audience: undefined
| string
Provided audience (aud) value
<Optional>
authConfig#
● authConfig: "auth0" | "azure" | "cognito" | "salesforce" | "okta" | "ping" | "identity-server" | "keycloak" | "general"
The type of the Auth Server, currently only the following are supported:
- Auth0
- Azure Active Directory
- Cognito (AWS)
- Salesforce
- Okta
- Ping
'general' is deprecated--please use a specific provider.
#
clientID● clientID: string
Provided Application ID
<Optional>
clientSecret#
● clientSecret: undefined
| string
The client secret, optional
<Optional>
discoveryUrl#
● discoveryUrl: undefined
| string
Location of the Auth Server's discovery endpoint, can be null for Azure
<Optional>
implicitLogin#
● implicitLogin: "CURRENT" | "POPUP"
determines the UI mode to use with web authentication in implicit. "CURRENT" will replace the current window with the authentication provider, and "POPUP" will open the authentication provider in a new window/tab. When this is set to "CURRENT", you will need to use the handleLoginCallback and handleLogoutCallback to complete the auth
<Optional>
iosWebView#
● iosWebView: "private" | "shared"
setting the option to shared
allows for sharing a session between Safari and other applications for a true SSO experience between apps but on iOS 11 and higher it will prompt the user for permission to share the website data with the application. Using private
avoids the prompt but the session will only be shared with Safari on iOS 10 or lower.
<Optional>
logLevel#
● logLevel: "DEBUG" | "ERROR" | "NONE"
The log level for the module
#
logoutUrl● logoutUrl: string
Location that the hosting app expects logout callbacks to navigate to.
<Optional>
platform#
● platform: "web" | "cordova" | "capacitor"
Are we hosted in cordova, web, capacitor
<Optional>
redirectUri#
● redirectUri: undefined
| string
Location that the hosting app expects callbacks to navigate to.
<Optional>
scope#
● scope: undefined
| string
User details requested from the Authentication provider, each provider may support standard {e.g. openid, profile, email, etc.}, or custom scopes.
<Optional>
tokenStorageProvider#
● tokenStorageProvider: "localStorage" | TokenStorageProvider | IVUserInterface
The type of storage to use for the tokens
<Optional>
webAuthFlow#
● webAuthFlow: "implicit" | "PKCE"
Authentication flow to use on web defaults to: implicit
PKCE
is not supported by Azure, if authConfig
is set to azure
the plugin will use implicit
despite webAuthFlow
value
#
IonicGeneralAuthOptionsIonicGeneralAuthOptions:
<Optional>
alwaysSendClientSecretOnLogin#
● alwaysSendClientSecretOnLogin: undefined
| false
| true
should the 'client_secret' value always be passed in for login calls, regardless of implict(web) or not defaults to: true
<Optional>
androidToolbarColor#
● androidToolbarColor: undefined
| string
setting to allow the toolbar color of the android webview control to be set. Takes a string that can be parsed as a color by android.graphics.Color.parseColor
<Optional>
audience#
● audience: undefined
| string
Provided audience (aud) value
<Optional>
authConfig#
● authConfig: "auth0" | "azure" | "cognito" | "salesforce" | "okta" | "ping" | "identity-server" | "keycloak" | "general"
The type of the Auth Server, currently only the following are supported:
- Auth0
- Azure Active Directory
- Cognito (AWS)
- Salesforce
- Okta
- Ping
'general' is deprecated--please use a specific provider.
#
clientID● clientID: string
Provided Application ID
<Optional>
clientSecret#
● clientSecret: undefined
| string
The client secret, optional
<Optional>
discoveryUrl#
● discoveryUrl: undefined
| string
Location of the Auth Server's discovery endpoint, can be null for Azure
<Optional>
implicitLogin#
● implicitLogin: "CURRENT" | "POPUP"
determines the UI mode to use with web authentication in implicit. "CURRENT" will replace the current window with the authentication provider, and "POPUP" will open the authentication provider in a new window/tab. When this is set to "CURRENT", you will need to use the handleLoginCallback and handleLogoutCallback to complete the auth
<Optional>
iosWebView#
● iosWebView: "private" | "shared"
setting the option to shared
allows for sharing a session between Safari and other applications for a true SSO experience between apps but on iOS 11 and higher it will prompt the user for permission to share the website data with the application. Using private
avoids the prompt but the session will only be shared with Safari on iOS 10 or lower.
<Optional>
logLevel#
● logLevel: "DEBUG" | "ERROR" | "NONE"
The log level for the module
#
logoutUrl● logoutUrl: string
Location that the hosting app expects logout callbacks to navigate to.
<Optional>
platform#
● platform: "web" | "cordova" | "capacitor"
Are we hosted in cordova, web, capacitor
<Optional>
redirectUri#
● redirectUri: undefined
| string
Location that the hosting app expects callbacks to navigate to.
<Optional>
scope#
● scope: undefined
| string
User details requested from the Authentication provider, each provider may support standard {e.g. openid, profile, email, etc.}, or custom scopes.
<Optional>
tokenStorageProvider#
● tokenStorageProvider: "localStorage" | TokenStorageProvider | IVUserInterface
The type of storage to use for the tokens
<Optional>
webAuthFlow#
● webAuthFlow: "implicit" | "PKCE"
Authentication flow to use on web defaults to: implicit
PKCE
is not supported by Azure, if authConfig
is set to azure
the plugin will use implicit
despite webAuthFlow
value
#
TokenStorageProviderTokenStorageProvider:
This interface can be implemented by the hosting app, and set in the options it should be a wrapper around access to a secure storage solution if Ionic Identity Vault is not being used.
<Optional>
clear#
● clear: undefined
| function
clear storage
<Optional>
getAccessToken#
● getAccessToken: undefined
| function
get the saved access token
param: Optional token name, only used when multiple tokens are required (Azure specific feature).
<Optional>
getAuthResponse#
● getAuthResponse: undefined
| function
get the full auth result
<Optional>
getIdToken#
● getIdToken: undefined
| function
get the id token
<Optional>
getRefreshToken#
● getRefreshToken: undefined
| function
get the saved refresh token
<Optional>
setAccessToken#
● setAccessToken: undefined
| function
save the access token
param: Optional token name, only used when multiple tokens are required (Azure specific feature).
<Optional>
setAuthResponse#
● setAuthResponse: undefined
| function
save the full auth response
<Optional>
setIdToken#
● setIdToken: undefined
| function
save the id token
<Optional>
setRefreshToken#
● setRefreshToken: undefined
| function
save the refresh token
#
Variables<Const>
ready#
● ready: Promise
<unknown
> = new Promise(resolve => {
document.addEventListener('deviceready', () => {
resolve();
});
})
#
Changelog#
[3.2.1] (2020-11-06)#
Bug Fixes- Fix an issue in syntax that required typescript 3.8 or above.
#
[3.2.0] (2020-11-06)#
Features- add keycloak support
- Add public method to clear storage without invalidating tokens
#
Bug Fixes- ios: prevent no such module Cordova
- Fix an issue where the general provider would only use logout_endpoint and not check for end_session_endpoint which caused it not to work with some providers.
#
[3.1.5] (2020-10-28)#
Bug Fixes- allow additional parameters to go through
- fixing logout issues in the web implicit login flow with new handleLoginCallback and handleLogoutCallback methods
- using native storage on devices to avoid web storage being cleared
#
[3.1.4] (2020-09-02)#
Bug Fixes- fix bug with localstorage provider where auth response wasn't serialized/deserialized correctly
- remove unneeded redirectUri param from cognito logout
- auth: export TokenStorageProvider
- ping: don't always include client secret , closes [/tools.ietf.org/html/draft-ietf-oauth-browser-based-apps-04#section-7]
#
[3.1.3] (2020-07-28)#
Bug Fixes- fix issue with logout for identity server
#
[3.1.2] (2020-07-24)#
Bug Fixes- Fix issue where IonicGeneralAuthOptions was not exported.
#
[3.1.1] (2020-07-09)#
Bug Fixes- web-auth: add missing await to PKCE refresh
#
[3.1.0] (2020-06-29)#
Features- Add official IdentityServer intergration
#
Bug Fixes- fix a bug where the handleCallback method did not properly unwrap the auth result promise
#
[3.0.1] (2020-06-24)#
Bug Fixes- auth: do not resolve when replacing URL
#
[3.0.0] (2020-06-10)#
⚠ BREAKING CHANGES- IE 11 is no longer supported.
- Plugin must be imported and bundled into your app for use. (Code is no longer being exported to window.)
#
Bug Fixes- Properly decode JWTs with non-ASCII characters [SE-200]
- remove shims
- switch to esm
#
[2.2.1] (2020-05-29)#
Bug Fixes- okta: fix logout configuration
#
[2.2.0] (2020-05-27)#
Features- Okta integration
#
Bug Fixes- android: make source-file target-dir lowercase
- web: add client secret to postToken body if required
#
[2.1.0] (2020-04-23)#
Features- add support for Ping
#
Bug Fixes- web: add client secret to postToken body if required
#
[2.0.1] (2020-04-17)#
Bug Fixes- make client_secret optional for Cognito
#
[2.0.0] (2020-04-17)#
⚠ BREAKING CHANGES- AndroidX is now required in projects with auth v2.
#
Features- add isAccessTokenExpired, isRefreshTokenAvailable, getRefreshToken, refreshSession
- Add support for Saleforce
- isAccessTokenAvailable
- android: AndroidX upgrade
#
Bug Fixes- Android: Fix an issue where Auth Connect didn't work on Android 10.
- await the access token from storage
- Fix a bug where if a provider doesn't return when the access token expires it defaults to be immediately expired.
- Fix an issue where if refresh failed isAuthenticated still returned true
- ios: move AuthenticationServices import from .m to .h for Capacitor compat
- web: catch error on refresh frame creation
- web, cognito: fix for SE-150. Added logout_uri to list of valid params.
- Add upgrading to v2 instructions
#
[1.8.1] (2020-04-01)#
Bug Fixes- await the access token from storage
#
[1.8.0] (2020-04-01)#
Features- isAccessTokenAvailable
#
[1.7.0] (2020-03-27)#
Features- add isAccessTokenExpired, isRefreshTokenAvailable, getRefreshToken, refreshSession
#
[1.6.2] (2020-03-17)#
Bug Fixes- Android: Fix an issue where Auth Connect didn't work on Android 10.
#
[1.6.1] (2020-03-16)#
Bug Fixes- Fix an issue where if refresh failed isAuthenticated still returned true
#
[1.6.0] (2020-03-13)#
Features- Add support for Saleforce
#
Bug Fixes- Fix a bug where if a provider doesn't return when the access token expires it defaults to be immediately expired.
#
[1.5.4] (2020-03-10)#
Bug Fixes- web: catch error on refresh frame creation
#
[1.5.3] (2020-03-09)#
Bug Fixes- web, cognito: fix for SE-150. Added logout_uri to list of valid params.
#
[1.5.2] (2020-02-24)#
Bug Fixes- web: throw error if POST to token endpoint failed
#
[1.5.1] (2020-02-21)#
Bug Fixes- web: properly refresh token when using PKCE
#
[1.5.0] (2020-02-17)#
Features- web: add PKCE auth flow option
#
[1.4.0] (2020-02-13)#
Features- reject if user closed the auth browser
#
Bug Fixes- ios, android, web: SE-132: allow client_secret to be passed into authorization calls.
- propagate network errors on login
- update to general to send client secret in payload of token call
#
[1.3.5] (2019-12-17)#
Bug Fixes- ios: prevent blank screen on SFSafariViewController presentation
#
[1.3.4] (2019-12-04)#
Bug Fixes- android: implement IonicSecureWebView.hide() to avoid invalid action
- ios: add in new interface for ios 13 when using ASWebAuthenticationPresentationContextProviding
#
[1.3.3] (2019-11-08)#
Bug Fixes- ios: rename AFNetworking symbols that conflic with advanced-http plugin
#
[1.3.2] (2019-11-01)#
[1.3.1] (2019-10-29)#
[1.3.0] (2019-10-09)#
Bug Fixes- make sure interfaces are not snake cased, move some parameters off to method to make them more dynmaic, clean up some parameter checking to be more clear, make some dictionary combines clearer.
#
Features- ios,android,web: changes for supporting implicit path (aka web) in window rather than in tabs. allow pass through of login_hint value for azure/auth0 and domain_hint for azure. fixes for param handling
#
[1.2.0] (2019-09-16)#
Bug Fixes- all: remove unneeded plugin deps
- ios, web, android: make sure the access token is valid before returning it
- web: password reset error was being ignored and needed to check (hash) not (query params) for value
- Web: Fix issue with IE 11 not working.
#
Features- ios,android,web: support acquiring multiple tokens from an oauth source (especially azure ad), also fix some issues with refresh for the web path. The major change is that getToken now has two optional paramters, they both must be passed in or neither. The parameters are an id for the token being acquired and the specific scope for the token being acquired.
#
[1.1.4] (2019-08-28)#
[1.1.3] (2019-08-21)#
[1.1.2] (2019-08-14)#
[1.1.1] (2019-07-29)#
Bug Fixes- Android, iOS: fix incorrect package.json dependency
#
[1.1.0] (2019-07-29)#
Features- iOS, Android: Remove extra plugin dependencies and unify flow across Android and all iOS webviews.