This is a generic OAuth 2 client plugin. It let you configure the oauth parameters yourself instead of using SDKs. Therefore it is usable with various providers.See identity providers the community has already used this plugin with.
How to install
For Capacitor v4
npm i @byteowls/capacitor-oauth2npx cap sync
For Capacitor v3 use 3.0.1
npm i @byteowls/capacitor-oauth2@3.0.1npx cap sync
For Capacitor v2 use 2.1.0
npm i @byteowls/capacitor-oauth2@2.1.0npx cap sync
Versions
Plugin | For Capacitor | Docs | Notes |
---|---|---|---|
4.x | 4.x.x | README | Breaking changes see Changelog. XCode 12.0 needs this version |
3.x | 3.x.x | README | Breaking changes see Changelog. XCode 12.0 needs this version |
2.x | 2.x.x | README | Breaking changes see Changelog. XCode 11.4 needs this version |
1.x | 1.x.x | README |
For further details on what has changed see the CHANGELOG.
Sponsors
I would like to especially thank some people and companies for supporting my work on this plugin and therefore improving it for everybody.
- Mark Laurence and the Royal Veterinary College - Thanks for supporting open source.
Maintainers
Maintainer | GitHub | Social |
---|---|---|
Michael Oberwasserlechner | moberwasserlechner | @michaelowl_web |
Actively maintained: YES
Supported flows
See the excellent article about OAuth2 response type combinations.
https://medium.com/@darutk/diagrams-of-all-the-openid-connect-flows-6968e3990660
The plugin on the other will behave differently depending on the existence of certain config parameters:
These parameters are:
accessTokenEndpoint
resourceUrl
e.g.
If responseType=code
, pkceDisable=true
and accessTokenEndpoint
is missing the authorizationCode
will be resolve along with the whole authorization response.This only works for the Web and Android. On iOS the used lib does not allows to cancel after the authorization request see #13.
If you just need the id_token
JWT you have to set accessTokenEndpoint
and resourceUrl
to null
.
Tested / working flows
These flows are already working and were tested by me.
Implicit flow
responseType: "token"
Code flow + PKCE
...responseType: "code"pkceEnable: true...
Please be aware that some providers (OneDrive, Auth0) allow Code Flow + PKCE only for native apps. Web apps have to use implicit flow.
Important
For security reasons this plugin does/will not support Code Flow without PKCE.
That would include storing your client secret in client code which is highly insecure and not recommended.That flow should only be used on the backend (server).
Configuration
Starting with version 3.0.0, the plugin is registered automatically on all platforms.
Use it
import {OAuth2Client} from "@byteowls/capacitor-oauth2";@Component({ template: '<button>Login with OAuth</button>' + '<button>Refresh token</button>' + '<button>Logout OAuth</button>'})export class SignupComponent { accessToken: string; refreshToken: string; onOAuthBtnClick() { OAuth2Client.authenticate( oauth2Options ).then(response => { this.accessToken = response["access_token"]; // storage recommended for android logout this.refreshToken = response["refresh_token"]; // only if you include a resourceUrl protected user values are included in the response! let oauthUserId = response["id"]; let name = response["name"]; // go to backend }).catch(reason => { console.error("OAuth rejected", reason); }); } // Refreshing tokens only works on iOS/Android for now onOAuthRefreshBtnClick() { if (!this.refreshToken) { console.error("No refresh token found. Log in with OAuth first."); } OAuth2Client.refreshToken( oauth2RefreshOptions ).then(response => { this.accessToken = response["access_token"]; // storage recommended for android logout // Don't forget to store the new refresh token as well! this.refreshToken = response["refresh_token"]; // Go to backend }).catch(reason => { console.error("Refreshing token failed", reason); }); } onLogoutClick() { OAuth2Client.logout( oauth2LogoutOptions, this.accessToken // only used on android ).then(() => { // do something }).catch(reason => { console.error("OAuth logout failed", reason); }); }}
Options
See the oauth2Options
and oauth2RefreshOptions
interfaces at https://github.com/moberwasserlechner/capacitor-oauth2/blob/main/src/definitions.ts for details.
Example:
{ authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth", accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token", scope: "email profile", resourceUrl: "https://www.googleapis.com/userinfo/v2/me", logsEnabled: true, web: { appId: environment.oauthAppId.google.web, responseType: "token", // implicit flow accessTokenEndpoint: "", // clear the tokenEndpoint as we know that implicit flow gets the accessToken from the authorizationRequest redirectUrl: "https://localhost:4200", windowOptions: "height=600,left=0,top=0" }, android: { appId: environment.oauthAppId.google.android, responseType: "code", // if you configured a android app in google dev console the value must be "code" redirectUrl: "com.companyname.appname:/" // package name from google dev console }, ios: { appId: environment.oauthAppId.google.ios, responseType: "code", // if you configured a ios app in google dev console the value must be "code" redirectUrl: "com.companyname.appname:/" // Bundle ID from google dev console } }
authenticate() and logout()
Overrideable Base Parameter
These parameters are overrideable in every platform
parameter | default | required | description | since |
---|---|---|---|---|
appId | yes | aka clientId, serviceId, ... | ||
authorizationBaseUrl | yes | |||
responseType | yes | |||
redirectUrl | yes | 2.0.0 | ||
accessTokenEndpoint | If empty the authorization response incl code is returned. Known issue: Not on iOS! | |||
resourceUrl | If empty the tokens are return instead. If you need just the id_token you have to set both accessTokenEndpoint and resourceUrl to null or empty ``. | |||
additionalResourceHeaders | Additional headers for the resource request | 3.0.0 | ||
pkceEnabled | false | Enable PKCE if you need it. Note: On iOS because of #111 boolean values are not overwritten. You have to explicitly define the param in the subsection. | ||
logsEnabled | false | Enable extensive logging. All plugin outputs are prefixed with I/Capacitor/OAuth2ClientPlugin: across all platforms. Note: On iOS because of #111 boolean values are not overwritten. You have to explicitly define the param in the subsection. | 3.0.0 | |
scope | ||||
state | The plugin always uses a state. If you don't provide one we generate it. | |||
additionalParameters | Additional parameters for anything you might miss, like none , response_mode . Just create a key value pair. |
Platform Web
parameter | default | required | description | since |
---|---|---|---|---|
windowOptions | e.g. width=500,height=600,left=0,top=0 | |||
windowTarget | _blank | |||
windowReplace | 3.0.0 |
Platform Android
parameter | default | required | description | since |
---|---|---|---|---|
customHandlerClass | Provide a class name implementing com.byteowls.capacitor.oauth2.handler.OAuth2CustomHandler | |||
handleResultOnNewIntent | false | Alternative to handle the activity result. The onNewIntent method is only call if the App was killed while logging in. | ||
handleResultOnActivityResult | true |
Platform iOS
parameter | default | required | description | since |
---|---|---|---|---|
customHandlerClass | Provide a class name implementing ByteowlsCapacitorOauth2.OAuth2CustomHandler | |||
siwaUseScope | SiWA default scope is name email if you want to use the configured one set this param true | 2.1.0 |
refreshToken()
parameter | default | required | description | since |
---|---|---|---|---|
appId | yes | aka clientId, serviceId, ... | ||
accessTokenEndpoint | yes | |||
refreshToken | yes | |||
scope |
Error Codes
authenticate()
- ERR_PARAM_NO_APP_ID ... The appId / clientId is missing. (web, android, ios)
- ERR_PARAM_NO_AUTHORIZATION_BASE_URL ... The authorization base url is missing. (web, android, ios)
- ERR_PARAM_NO_RESPONSE_TYPE ... The response type is missing. (web, android, ios)
- ERR_PARAM_NO_REDIRECT_URL ... The redirect url is missing. (web, android, ios)
- ERR_STATES_NOT_MATCH ... The state included in the authorization code request does not match the one in the redirect. Security risk! (web, android, ios)
- ERR_AUTHORIZATION_FAILED ... The authorization failed.
- ERR_NO_ACCESS_TOKEN ... No access_token found. (web, android)
- ERR_NO_AUTHORIZATION_CODE ... No authorization code was returned in the redirect response. (web, android, ios)
- USER_CANCELLED ... The user cancelled the login flow. (web, android, ios)
- ERR_CUSTOM_HANDLER_LOGIN ... Login through custom handler class failed. See logs and check your code. (android, ios)
- ERR_CUSTOM_HANDLER_LOGOUT ... Logout through custom handler class failed. See logs and check your code. (android, ios)
- ERR_ANDROID_NO_BROWSER ... No suitable browser could be found! (Android)
- ERR_ANDROID_RESULT_NULL ... The auth result is null. The intent in the ActivityResult is null. This might be a valid state but make sure you configured Android part correctly! See Platform Android
- ERR_GENERAL ... A unspecific error. Check the logs to see want exactly happened. (web, android, ios)
refreshToken()
- ERR_PARAM_NO_APP_ID ... The appId / clientId is missing. (android, ios)
- ERR_PARAM_NO_ACCESS_TOKEN_ENDPOINT ... The access token endpoint url is missing. It is only needed on refresh, on authenticate it is optional. (android, ios)
- ERR_PARAM_NO_REFRESH_TOKEN ... The refresh token is missing. (android, ios)
- ERR_NO_ACCESS_TOKEN ... No access_token found. (web, android)
- ERR_GENERAL ... A unspecific error. Check the logs to see want exactly happened. (android, ios)
Platform: Web/PWA
This implementation just opens a browser window to let users enter their credentials.
As there is no provider SDK used to accomplish OAuth, no additional javascript files must be loaded and so there is no performanceimpact using this plugin in a web application.
Register plugin
On Web/PWA the plugin is registered automatically by Capacitor.
Platform: Android
Prerequisite: Capacitor Android Docs
Register plugin
On Android the plugin is registered automatically by Capacitor.
Android Default Config
Skip this, if you use a OAuth2CustomHandler
. See below.
android/app/src/main/res/AndroidManifest.xml
The AndroidManifest.xml
in your Capacitor Android project already contains
<data> </data>
Find the following line in your AndroidManifest.xml
<data>
and change it to
<data>
Note: Actually any value for android:host
will do. It does not has to be oauth
.
This will fix an issues within the oauth workflow when the application is shown twice.See Issue #15 for details what happens.
android/app/src/main/res/values/strings.xml
In your strings.xml
change the custom_url_scheme
string to your actual scheme value. Do NOT include ://oauth/redirect
or other endpoint urls here!
com.example.yourapp
android/app/build.gradle
android.defaultConfig.manifestPlaceholders = [ // change to the 'custom_url_scheme' value in your strings.xml. They need to be the same. e.g. "appAuthRedirectScheme": "com.example.yourapp"]
Troubleshooting
- If your
appAuthRedirectScheme
does not get recognized because you are using a library that replaces it(e.g.: onesignal-cordova-plugin), you will have to add it to yourbuildTypes
like the following:
android.buildTypes.debug.manifestPlaceholders = [ 'appAuthRedirectScheme': '<@string/custom_url_scheme from string.xml>' // e.g. com.companyname.appname]android.buildTypes.release.manifestPlaceholders = [ 'appAuthRedirectScheme': '<@string/custom_url_scheme from string.xml>' // e.g. com.companyname.appname]
"ERR_ANDROID_RESULT_NULL": See Issue #52 for details.I cannot reproduce this behaviour. Moreover, there might be situation this state is valid. In other cases e.g. in the linked issue a configuration tweak fixed it.
To prevent some logout issues on certain OAuth2 providers (like Salesforce for example), you should provide the
id_token
parameter on thelogout(...)
function.This ensures that not only the cookies are deleted, but also the logout link is called from the OAuth2 provider.Also, it uses the system browser that the plugin uses (and not the user's default browser) to call the logout URL.This additionally ensures that the cookies are deleted in the correct browser.
Custom OAuth Handler
Some OAuth provider (Facebook) force developers to use their SDK on Android.
This plugin should be as generic as possible so I don't want to include provider specific dependencies.
Therefore, I created a mechanism which let developers integrate custom SDK features in this plugin.Simply configure a full qualified classname in the option property android.customHandlerClass
.This class has to implement com.byteowls.capacitor.oauth2.handler.OAuth2CustomHandler
.
See a full working example below!
Platform: iOS
Register plugin
On iOS the plugin is registered automatically by Capacitor.
iOS Default Config
Skip this, if you use a OAuth2CustomHandler
. See below.
Open ios/App/App/Info.plist
in XCode (Context menu -> Open as -> Source) and add the value of redirectUrl
from your config without :/
like that
CFBundleURLTypesCFBundleURLSchemescom.companyname.appname
Custom OAuth Handler
Some OAuth provider (e.g., Facebook) force developers to use their SDK on iOS.
This plugin should be as generic as possible, so I don't want to include provider specific dependencies.
Therefore, I created a mechanism which let developers integrate custom SDK features in this plugin.Simply configure the class name in the option property ios.customHandlerClass
.This class has to implement ByteowlsCapacitorOauth2.OAuth2CustomHandler
.
See a full working example below!
Platform: Electron
- No timeline.
Where to store access tokens?
You can use the capacitor-secure-storage plugin for this.
This plugin stores data in secure locations for natives devices.
- For Android, it will store data in a AndroidKeyStore and a SharedPreferences.
- For iOS, it will store data in a SwiftKeychainWrapper.
List of Providers
These are some of the providers that can be configured with this plugin. I'm happy to add others ot the list, if you let me know.
Name | Example (config,...) | Notes |
---|---|---|
see below | ||
see below | ||
Azure | see below | |
Apple | see below | ios only |
Examples
Apple
iOS 13+
Minimum config
appleLogin() { OAuth2Client.authenticate({ appId: "xxxxxxxxx", authorizationBaseUrl: "https://appleid.apple.com/auth/authorize", });}
The plugin requires authorizationBaseUrl
as it triggers the native support and because it is needed for other platforms anyway. Those platforms are not supported yet.
appId
is required as well for internal, generic reasons and any not blank value is fine.
It is also possible to control the scope although Apple only supports email
and/or fullName
. Add siwaUseScope: true
to the ios section.Then you can use scope: "fullName"
, scope: "email"
or both but the latter is the default one if siwaUseScope
is not set or false.
appleLogin() { OAuth2Client.authenticate({ appId: "xxxxxxxxx", authorizationBaseUrl: "https://appleid.apple.com/auth/authorize", ios: { siwaUseScope: true, scope: "fullName" } });}
As "Signin with Apple" is only supported since iOS 13 you should show the according button only in that case.
In Angular do sth like
import {Component, OnInit} from '@angular/core';import {Device, DeviceInfo} from "@capacitor/device";import {OAuth2Client} from "@byteowls/capacitor-oauth2";@Component({ templateUrl: './siwa.component.html'})export class SiwaComponent implements OnInit { ios: boolean; siwaSupported: boolean; deviceInfo: DeviceInfo; async ngOnInit() { this.deviceInfo = await Device.getInfo(); this.ios = this.deviceInfo.platform === "ios"; if (this.ios) { const majorVersion: number = +this.deviceInfo.osVersion.split(".")[0]; this.siwaSupported = majorVersion >= 13; } }}
And show the button only if siwaSupported
is true
.
The response contains these fields:
"id""given_name""family_name""email""real_user_status""state""id_token""code"
iOS <12
not supported
PWA
not supported
Android
not supported
Azure Active Directory / Azure AD B2C
It's important to use the urls you see in the Azure portal for the specific platform.
Note: Don't be confused by the fact that the Azure portal shows "Azure Active Directory" and "Azure AD B2C" services.They share the same core features and therefore the plugin should work either way.
PWA
import {OAuth2AuthenticateOptions, OAuth2Client} from "@byteowls/capacitor-oauth2";export class AuthService { getAzureB2cOAuth2Options(): OAuth2AuthenticateOptions { return { appId: environment.oauthAppId.azureBc2.appId, authorizationBaseUrl: `https://login.microsoftonline.com/${environment.oauthAppId.azureBc2.tenantId}/oauth2/v2.0/authorize`, scope: "https://graph.microsoft.com/User.Read", // See Azure Portal -> API permission accessTokenEndpoint: `https://login.microsoftonline.com/${environment.oauthAppId.azureBc2.tenantId}/oauth2/v2.0/token`, resourceUrl: "https://graph.microsoft.com/v1.0/me/", responseType: "code", pkceEnabled: true, logsEnabled: true, web: { redirectUrl: environment.redirectUrl, windowOptions: "height=600,left=0,top=0", }, android: { redirectUrl: "msauth://{package-name}/{url-encoded-signature-hash}" // See Azure Portal -> Authentication -> Android Configuration "Redirect URI" }, ios: { pkceEnabled: true, // workaround for bug #111 redirectUrl: "msauth.{package-name}://auth" } }; }}
Custom Scopes
If you need to use custom scopes configured in "API permissions" and created in "Expose an API" in Azure Portal you might needto remove the resourceUrl
parameter if your scopes are not included in the response. I can not give a clear advise on those Azure specifics.Try to experiment with the config until Azure includes everything you need in the response.
A configuration with custom scopes might look like this:
import {OAuth2Client} from "@byteowls/capacitor-oauth2"; getAzureB2cOAuth2Options(): OAuth2AuthenticateOptions { return { appId: environment.oauthAppId.azureBc2.appId, authorizationBaseUrl: `https://login.microsoftonline.com/${environment.oauthAppId.azureBc2.tenantId}/oauth2/v2.0/authorize`, scope: "api://uuid-created-by-azure/scope.name1 api://uuid-created-by-azure/scope.name2", // See Azure Portal -> API permission / Expose an API accessTokenEndpoint: `https://login.microsoftonline.com/${environment.oauthAppId.azureBc2.tenantId}/oauth2/v2.0/token`, // no resourceURl! responseType: "code", pkceEnabled: true, logsEnabled: true, web: { redirectUrl: environment.redirectUrl, windowOptions: "height=600,left=0,top=0", }, android: { redirectUrl: "msauth://{package-name}/{url-encoded-signature-hash}" // See Azure Portal -> Authentication -> Android Configuration "Redirect URI" }, ios: { pkceEnabled: true, // workaround for bug #111 redirectUrl: "msauth.{package-name}://auth" } }; }}
Prior configs
Other configs that works in prior versions
import {OAuth2Client} from "@byteowls/capacitor-oauth2";azureLogin() { OAuth2Client.authenticate({ appId: "xxxxxxxxx", authorizationBaseUrl: "https://tenantb2c.b2clogin.com/tfp/tenantb2c.onmicrosoft.com/B2C_1_SignUpAndSignIn/oauth2/v2.0/authorize", accessTokenEndpoint: "", scope: "openid offline_access https://tenantb2c.onmicrosoft.com/capacitor-api/demo.read", responseType: "token", web: { redirectUrl: "https://localhost:8100/auth" }, android: { pkceEnabled: true, responseType: "code", redirectUrl: "com.tenant.app://oauth/auth", // Use the value from Azure config. Platform "Android" accessTokenEndpoint: "https://tenantb2c.b2clogin.com/tfp/tenantb2c.onmicrosoft.com/B2C_1_SignUpAndSignIn/oauth2/v2.0/token", handleResultOnNewIntent: true, handleResultOnActivityResult: true }, ios: { pkceEnabled: true, responseType: "code", redirectUrl: "msauth.BUNDLE_ID://oauth", // Use the value from Azure config. Platform "iOS/Mac" accessTokenEndpoint: "https://tenantb2c.b2clogin.com/tfp/tenantb2c.onmicrosoft.com/B2C_1_SignUpAndSignIn/oauth2/v2.0/token", } });}
import {OAuth2Client} from "@byteowls/capacitor-oauth2";azureLogin() { OAuth2Client.authenticate({ appId: 'XXXXXXXXXX-XXXXXXXXXX-XXXXXXXXX', authorizationBaseUrl: 'https://TENANT.b2clogin.com/tfp/TENANT.onmicrosoft.com/B2C_1_policy-signin-signup-web/oauth2/v2.0/authorize', accessTokenEndpoint: '', scope: 'https://XXXXXXX.onmicrosoft.com/TestApi4/demo.read', responseType: 'token', web: { redirectUrl: 'https://localhost:8100/' }, android: { pkceEnabled: true, responseType: 'code', redirectUrl: 'com.company.project://oauth/redirect', accessTokenEndpoint: 'https://TENANT.b2clogin.com/TENANT.onmicrosoft.com/B2C_1_policy-signin-signup-web', handleResultOnNewIntent: true, handleResultOnActivityResult: true }, ios: { pkceEnabled: true, responseType: 'code', redirectUrl: 'com.company.project://oauth', accessTokenEndpoint: 'https://TENANT.b2clogin.com/TENANT.onmicrosoft.com/B2C_1_policy-signin-signup-web', } });}
Android
If you have only Azure B2C as identity provider you have to add a new intent-filter
to your main activity in AndroidManifest.xml
.
<data></data>
If you have multiple identity providers or your logins always ends in a USER_CANCELLED
error like in #178you have to create an additional Activity in AndroidManifest.xml
.
These are both activities! Make sure to replace com.company.project.MainActivity
with your real qualified class path!
<data> </data> <data> </data> <data> </data>
Values for android/app/src/main/res/values/string.xml
. Replace the example values!
Your Project's Name/string> com.company.project foo com.company.project msauth /your-signature-hash
See Android Default Config
iOS
Open Info.plist
in XCode by clicking right on that file -> Open as -> Source Code. Note: XCode does not "like" files opened and changed externally.
CFBundleURLTypesCFBundleURLSchemesmsauth.com.yourcompany.yourproject
Important:
- Do not enter
://
as part of your redirect url - Make sure the
msauth.
prefix is present
Troubleshooting
In case of problems please read #91and #96
See this example repo by @loonix.
PWA
import {OAuth2Client} from "@byteowls/capacitor-oauth2";googleLogin() { OAuth2Client.authenticate({ authorizationBaseUrl: "https://accounts.google.com/o/oauth2/auth", accessTokenEndpoint: "https://www.googleapis.com/oauth2/v4/token", scope: "email profile", resourceUrl: "https://www.googleapis.com/userinfo/v2/me", web: { appId: environment.oauthAppId.google.web, responseType: "token", // implicit flow accessTokenEndpoint: "", // clear the tokenEndpoint as we know that implicit flow gets the accessToken from the authorizationRequest redirectUrl: "https://localhost:4200", windowOptions: "height=600,left=0,top=0" }, android: { appId: environment.oauthAppId.google.android, responseType: "code", // if you configured a android app in google dev console the value must be "code" redirectUrl: "com.companyname.appname:/" // package name from google dev console }, ios: { appId: environment.oauthAppId.google.ios, responseType: "code", // if you configured a ios app in google dev console the value must be "code" redirectUrl: "com.companyname.appname:/" // Bundle ID from google dev console } }).then(resourceUrlResponse => { // do sth e.g. check with your backend }).catch(reason => { console.error("Google OAuth rejected", reason); }); }
Android
See Android Default Config
iOS
See iOS Default Config
PWA
import {OAuth2Client} from "@byteowls/capacitor-oauth2";facebookLogin() { let fbApiVersion = "2.11"; OAuth2Client.authenticate({ appId: "YOUR_FACEBOOK_APP_ID", authorizationBaseUrl: "https://www.facebook.com/v" + fbApiVersion + "/dialog/oauth", resourceUrl: "https://graph.facebook.com/v" + fbApiVersion + "/me", web: { responseType: "token", redirectUrl: "https://localhost:4200", windowOptions: "height=600,left=0,top=0" }, android: { customHandlerClass: "com.companyname.appname.YourAndroidFacebookOAuth2Handler", }, ios: { customHandlerClass: "App.YourIOsFacebookOAuth2Handler", } }).then(resourceUrlResponse => { // do sth e.g. check with your backend }).catch(reason => { console.error("FB OAuth rejected", reason); }); }
Android and iOS
Since October 2018 Strict Mode for Redirect Urls is always on.
>Use Strict Mode for Redirect URIs
>Only allow redirects that use the Facebook SDK or that exactly match the Valid OAuth Redirect URIs. Strongly recommended.
Before that it was able to use fb:/authorize
in a Android or iOS app and get the accessToken.
Unfortunately now we have to use the SDK for Facebook Login.
I don't want to have a dependency to facebook for users, who don't need Facebook OAuth.
To address this problem I created a integration with custom code in your app customHandlerClass
Android
See https://developers.facebook.com/docs/facebook-login/android/ for more background on how to configure Facebook in your Android app.
Add
implementation 'com.facebook.android:facebook-login:4.36.0'
toandroid/app/build.gradle
as dependency.Add to
string.xml
fb
- Add to
AndroidManifest.xml
<data> </data>
- Create a custom handler class
package com.companyname.appname;import android.app.Activity;import com.byteowls.capacitor.oauth2.handler.AccessTokenCallback;import com.byteowls.capacitor.oauth2.handler.OAuth2CustomHandler;import com.companyname.appname.MainActivity;import com.facebook.AccessToken;import com.facebook.FacebookCallback;import com.facebook.FacebookException;import com.facebook.login.DefaultAudience;import com.facebook.login.LoginBehavior;import com.facebook.login.LoginManager;import com.facebook.login.LoginResult;import com.getcapacitor.PluginCall;import java.util.Collections;public class YourAndroidFacebookOAuth2Handler implements OAuth2CustomHandler { @Override public void getAccessToken(Activity activity, PluginCall pluginCall, final AccessTokenCallback callback) { AccessToken accessToken = AccessToken.getCurrentAccessToken(); if (AccessToken.isCurrentAccessTokenActive()) { callback.onSuccess(accessToken.getToken()); } else { LoginManager l = LoginManager.getInstance(); l.logInWithReadPermissions(activity, Collections.singletonList("public_profile")); l.setLoginBehavior(LoginBehavior.WEB_ONLY); l.setDefaultAudience(DefaultAudience.NONE); LoginManager.getInstance().registerCallback(((MainActivity) activity).getCallbackManager(), new FacebookCallback() { @Override public void onSuccess(LoginResult loginResult) { callback.onSuccess(loginResult.getAccessToken().getToken()); } @Override public void onCancel() { callback.onCancel(); } @Override public void onError(FacebookException error) { callback.onCancel(); } }); } } @Override public boolean logout(Activity activity, PluginCall pluginCall) { LoginManager.getInstance().logOut(); return true; }}
- Change your MainActivity like
public class MainActivity extends BridgeActivity { private CallbackManager callbackManager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize Facebook SDK FacebookSdk.sdkInitialize(this.getApplicationContext()); callbackManager = CallbackManager.Factory.create(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (callbackManager.onActivityResult(requestCode, resultCode, data)) { return; } } public CallbackManager getCallbackManager() { return callbackManager; }}
iOS
See https://developers.facebook.com/docs/swift/getting-started and https://developers.facebook.com/docs/swift/login
- Add Facebook pods to
ios/App/Podfile
and runpod install
afterwards
platform :ios, '13.0'use_frameworks!# workaround to avoid Xcode caching of Pods that requires# Product -> Clean Build Folder after new Cordova plugins installed# Requires CocoaPods 1.6 or newerinstall! 'cocoapods', :disable_input_output_paths => truedef capacitor_pods pod 'Capacitor', :path => '../../node_modules/@capacitor/ios' pod 'CapacitorCordova', :path => '../../node_modules/@capacitor/ios' pod 'ByteowlsCapacitorOauth2', :path => '../../node_modules/@byteowls/capacitor-oauth2' # core plugins pod 'CapacitorApp', :path => '../../node_modules/@capacitor/app' pod 'CapacitorDevice', :path => '../../node_modules/@capacitor/device' pod 'CapacitorKeyboard', :path => '../../node_modules/@capacitor/keyboard' pod 'CapacitorSplashScreen', :path => '../../node_modules/@capacitor/splash-screen' pod 'CapacitorStatusBar', :path => '../../node_modules/@capacitor/status-bar'endtarget 'App' do capacitor_pods # Add your Pods here pod 'FacebookCore' pod 'FacebookLogin'end
- Add some Facebook configs to your
Info.plist
CFBundleURLTypes CFBundleURLSchemes fb{your-app-id} FacebookAppID{your-app-id}FacebookDisplayName{your-app-name}LSApplicationQueriesSchemes fbapi fb-messenger-share-api fbauth2 fbshareextension
- Create a custom handler class
import Foundationimport FacebookCoreimport FacebookLoginimport Capacitorimport ByteowlsCapacitorOauth2@objc class YourIOsFacebookOAuth2Handler: NSObject, OAuth2CustomHandler { required override init() { } func getAccessToken(viewController: UIViewController, call: CAPPluginCall, success: @escaping (String) -> Void, cancelled: @escaping () -> Void, failure: @escaping (Error) -> Void) { if let accessToken = AccessToken.current { success(accessToken.tokenString) } else { DispatchQueue.main.async { let loginManager = LoginManager() // I only need the most basic permissions but others are available loginManager.logIn(permissions: [ .publicProfile ], viewController: viewController) { result in switch result { case .success(_, _, let accessToken): success(accessToken.tokenString) case .failed(let error): failure(error) case .cancelled: cancelled() } } } } } func logout(viewController: UIViewController, call: CAPPluginCall) -> Bool { let loginManager = LoginManager() loginManager.logOut() return true }}
This handler will be automatically discovered up by the plugin and handles the login using the Facebook SDK.See https://developers.facebook.com/docs/swift/login/#custom-login-button for details.
- The users that have redirect problem after success grant add the following code to
ios/App/App/AppDelegate.swift
.This code correctly delegate the FB redirect url to be managed by Facebook SDK.
import UIKitimport FacebookCoreimport FacebookLoginimport Capacitor@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // other methods func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // Called when the app was launched with a url. Feel free to add additional processing here, // but if you want the App API to support tracking app url opens, make sure to keep this call if let scheme = url.scheme, let host = url.host { let appId: String = Settings.appID! if scheme == "fb\(appId)" && host == "authorize" { return ApplicationDelegate.shared.application(app, open: url, options: options) } } return CAPBridge.handleOpenUrl(url, options) } // other methods}
Contribute
See Contribution Guidelines.
Changelog
See CHANGELOG.
License
MIT. See LICENSE.
BYTEOWLS Software & Consulting
This plugin is powered by .
If you need extended support for this project like critical changes or releases ahead of schedule. Feel free to contact us for a consulting offer.
Disclaimer
We have no business relation to Ionic.
FAQs
What problem does SNYK solve? ›
Snyk helps you to fix vulnerabilities, by upgrading the direct dependencies to a vulnerability-free version, or by patching the vulnerability. After Snyk scans your Projects, scan results allow you to resolve those issues in your code, with the help of clear suggestions and explanations.
What is SNYK open source and SNYK code? ›Snyk Open Source allows you to find and fix vulnerabilities in the open source libraries used by your applications. It also allows you to find and address licensing issues in (or caused by) these open source libraries. Snyk Open Source is available in many common languages and platforms.
What files can Snyk scan? ›...
Files that Snyk uses to autodetect the project type include, but are not limited to, the following:
- yarn. lock.
- package-lock. json.
- package. json.
- Gemfile. lock.
- pom. xml.
- build. gradle.
- build. sbt.
- Pipfile.
The advantages of the Snyk open-source vulnerability scanner include: Early detection of open-source code vulnerabilities, before web applications or websites have been compromised.
What language is Snyk written in? ›Snyk Code currently supports the following programming languages: C# C/C++ (Beta) Go.
How do you check open source code vulnerabilities? ›Open source vulnerability scanners, often used as part of Software Composition Analysis (SCA) tools, are used to detect open source components used in software projects, and check if they contain unpatched security vulnerabilities, and help organizations remediate them.
How do I find open source code? ›Finding open-source code & programs
The largest repository for open source code projects in the life sciences is currently GitHub. GitHub also has a spin-off environment called GitLab . GitHub allows browsing by topic. Browsing by "biology" or "medicine" can be helpful for discovering projects in the life sciences.
What is the activation process of Snyk Code? First, you need to enable the Snyk Code option in your Snyk Org Settings via the Web UI. If you intend on using the IDE, CLI, or API Environments, this is the only step you need to do in order to start working with Snyk Code.
Does Snyk upload my Code? ›By default, Snyk does not access your source code with this exception: for CLI scans using the --unmanaged option, Snyk accesses your source code files to convert them to file signatures (hashes) and store the file signatures and file names.
How does Snyk scan work? ›The recurring scans simply test for new vulnerabilities using a snapshot of your application dependencies at the time the application was imported. To detect changes in your application, such as updated dependencies, re-import your container image in Snyk.
How does Snyk test work? ›
The snyk test command scans your project, tests dependencies for vulnerabilities, and reports how many vulnerabilities are found. The command returns a non-zero exit code which causes a build to fail when run inside of CI environments (depending on how the CI tool is configured).
Does Snyk scan all branches? ›Today Snyk monitors the default branch. So if a repo is set to point at `develop` by default then Snyk would do pull requests against `develop`.
What is the Snyk tool used for? ›Snyk is a platform allowing you to scan, prioritize, and fix security vulnerabilities in your own code, open source dependencies, container images, and Infrastructure as Code (IaC) configurations.
Is SNYK open source free? ›Snyk has always offered individual developers free access to our core tools and vulnerability database.
Does Google use Snyk? ›Snyk Cloud scans the infrastructure configuration in your Google Cloud projects and detects misconfigurations that can lead to vulnerabilities. You can onboard a Google Cloud account to Snyk using the following methods: Snyk Web UI
Who are Snyk competitors? ›- Mend (formerly WhiteSource) (91)4.3 out of 5.
- GitLab. (684)4.5 out of 5.
- Veracode Application Security Platform. (21)3.7 out of 5.
- Wiz. (340)4.7 out of 5.
- GitHub. (1,951)4.7 out of 5.
- Lacework. (180)4.4 out of 5.
- Checkmarx. (31)4.2 out of 5.
- Black Duck Software Composition Analysis.
By default, Snyk scans with Python 2. You can adjust the version of Python that Snyk uses to scan dependencies in both the CLI and Git integration.
Can you steal code from open source? ›The most obvious reason to not copy and paste code from open source projects is licensing. Don't be confused: Even though open source code is free, it still has licensing guidelines that dictate what you can and cannot do with it. And while some open source licenses are permissive, others are more restrictive.
Is open source code easier to hack? ›Open source software makes its code available for review, which increases the likelihood that security vulnerabilities are found and corrected quickly. Closed source software may be secure as well, but you have to trust the developers and company who made it.
What is SNYK code? ›Snyk Code is developer-first - embedding SAST as part of the development process, enabling developers to build software securely during the coding stage, and not trying to find and fix problems after the code is compiled.
What is Snyk vulnerability? ›
Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code.
How do I enable code security in Snyk? ›If you are using the Snyk IDE, CLI, or API Environments, use the Snyk Web UI to enable the Snyk Code option. Then, continue to test your code with Snyk Code in your selected Environment.
How do I report vulnerability to Snyk? ›If you believe you have found a security vulnerability on Snyk, we encourage you to let us know right away by emailing us at security@snyk.io. We will investigate all legitimate reports and do our best to quickly fix the problem. Before reporting though, review this page including our responsible disclosure policy.
Is Snyk code good? ›Snyk is the #1 ranked solution in top DevSecOps tools, #2 ranked solution in Container Security Solutions, #2 ranked solution in top Software Composition Analysis (SCA) tools, and #7 ranked solution in application security solutions. PeerSpot users give Snyk an average rating of 8.0 out of 10.
Is Snyk static or dynamic? ›With Snyk for software composition analysis (SCA) and static application security testing (SAST) and StackHawk for dynamic application security testing (DAST), developers are equipped with the information and context they need to find and fix vulnerabilities quickly.
What companies use Snyk? ›Snyk is used by 1,500 customers worldwide today, including industry leaders such as Asurion, Google, Intuit, MongoDB, New Relic, Revolut and Salesforce. Snyk is recognized on the Forbes Cloud 100 2021, the 2021 CNBC Disruptor 50 and was named a Visionary in the 2021 Gartner Magic Quadrant for AST.
How do hackers use vulnerability scanners? ›Vulnerability scanners often have many thousands of automated tests at their disposal, and by probing and gathering information about your systems, can identify security holes which could be used by hackers to steal sensitive information, gain unauthorized access to systems, or to cause general disruption to your ...
What is the difference between SonarQube and Snyk? ›Snyk belongs to "Dependency Monitoring" category of the tech stack, while SonarQube can be primarily classified under "Code Review". SonarQube is an open source tool with 3.79K GitHub stars and 1.06K GitHub forks. Here's a link to SonarQube's open source repository on GitHub.
What are the main features of Snyk? ›- API.
- Application Security.
- Asset Discovery.
- Asset Tagging.
- Container Scanning.
- Continuous Integration.
- Dashboard.
- Debugging.
Snyk CLI brings functionality of Snyk into your development workflow. You can run the CLI locally, or in your CI/CD pipeline to scan your projects for security issues, including security vulnerabilities and license issues.
What is the limit of Snyk scan? ›
The default is 2000 but some specific endpoints have lower limits.
How do I scan Docker images with Snyk? ›Sign into Docker Hub. From the Docker Desktop menu, select Sign in/ Create Docker ID. Alternatively, open a terminal and run the command docker login . (Optional) You can create a Snyk account for scans, or use the additional monthly free scans provided by Snyk with your Docker Hub account.
What is the purpose of Snyk? ›What is Snyk? Snyk is a platform allowing you to scan, prioritize, and fix security vulnerabilities in your own code, open source dependencies, container images, and Infrastructure as Code (IaC) configurations.
What is benefit of Snyk? ›Snyk Code provides a curated overview on every issue of the vulnerability - this includes how it is created, what the risk is, what the possible mitigation strategies are, and other bite-size, educational content. This allows developers to improve their security knowledge and write secure code in real-time.
Why do we use Snyk? ›Snyk (pronounced sneak) is a developer security platform for securing code, dependencies, containers, and infrastructure as code. It scans your code, reads through it, and tells you if you have any vulnerabilities in your code.
What is good about Snyk? ›Great open source analysis and AST tool for developers in Application security. The ease of use and service provided by the Snyk team is pretty much unparalleled.
What data does Snyk collect? ›Snyk accesses and stores the names and version numbers of your dependencies. Snyk stores the names of associated licenses, including copyright and attribution information.
What is Snyk vulnerabilities? ›Snyk is a developer security platform. Integrating directly into development tools, workflows, and automation pipelines, Snyk makes it easy for teams to find, prioritize, and fix security vulnerabilities in code, dependencies, containers, and infrastructure as code.
What tools does Snyk support? ›Snyk supports: JavaScript, Java (Gradle, Maven), . NET, Python, Golang, Swift, Objective-C (CocoaPods), Scala, Ruby, PHP, Bazel, Terraform, CloudFormation, Azure Resource Manager, Kubernetes, and Dockerfiles.
Is Snyk code free? ›Snyk functionality is available with several pricing plans: Free: For individual developers and small teams looking to secure while they build. Limited tests. Team: For dev teams looking to build security into their development process with shared visibility into projects.
How reliable is Snyk? ›
Snyk is the #1 ranked solution in top DevSecOps tools, #2 ranked solution in Container Security Solutions, #2 ranked solution in top Software Composition Analysis (SCA) tools, and #8 ranked solution in application security solutions. PeerSpot users give Snyk an average rating of 8.0 out of 10.
How does Snyk handle data? ›We store a hash of each user's email address in order to track unique contributors, without breaching your privacy.