-
Notifications
You must be signed in to change notification settings - Fork 0
Adding User Authentication via Kitura Credentials
You can add user authentication to your Kitura app via Kitura-Credentials by using an existing Credentials plugin implementation or by implementing your own Credentials plugin.
To integrate Kitura-Credentials with your Kitura app, first setup Kitura:
import Kitura
let router = Router()
Next, instantiate the Credentials framework:
import Credentials
let credentials = Credentials()
Then, configure the Credentials plugin you want to use and then register it with the Credentials framework. The following example configures a Credentials plugin for OAuth2 Authorization Code flow for Facebook login. You can find a list of available Credentials plugins here.
The Kitura-CredentialsFacebook plugin supports Facebook OAuth2 login for both Authorization Code flow and token flow. This guide assumes that you have registered your app with Facebook and have enabled Facebook Login in your app and is attempting to use the OAuth2 Authorization Code flow to authenticate users against Facebook.
To use the Kitura-CredentialsFacebook OAuth2 Authorization Code flow, first set up the session:
// previous steps omitted for brevity
import KituraSession
// using in-memory session in this example; can also use other session stores
let session = Session(secret: "session_secret")
// configure Kitura router to use session
router.all(middleware: session)
Then, configure the plugin:
import CredentialsFacebook
let fbCredentials = CredentialsFacebook(clientId: "<your-app-id>", clientSecret: "<your-app-secret>", callbackUrl: “<your-app-domain>/login/facebook/callback”)
Next, register the plugin with the Credentials framework:
credentials.register(plugin: fbCredentials)
Lastly, set up endpoints on your server for handling user authentication:
// Endpoint for starting the OAuth2 login flow
router.get(“/login/facebook”, handler: credentials.authenticate(credentialsType: fbCredentials.name)
// Endpoint for Facebook callback; handles exchange of authorization code for access token
router.get(“/login/facebook/callback”, handler: credentials.authenticate(credentialsType: fbCredentials.name))
With these endpoints, you can redirect users to /login/facebook
to begin the login process. Note: Make sure to whitelist <your-app-domain>/login/facebook/callback
in your Facebook app’s developer settings in order to allow Facebook to redirect users back to your callback.
That’s the basic setup for OAuth2 Facebook login. Please refer to Kitura-CredentialsFacebook for more usage and configurations.