Git Product home page Git Product logo

kitura-credentialsgoogle's Introduction

Kitura

APIDoc Build Status - Master macOS Linux Apache 2 Slack Status

Kitura-CredentialsGoogle

Plugin for the Kitura-Credentials framework that authenticates using the Google web login and a Google OAuth token.

Summary

Plugin for the Kitura-Credentials framework that authenticates using the Google web login with OAuth 2.0 and a Google OAuth token that was acquired by a mobile app or other client of the Kitura based backend.

Swift version

The latest version of Kitura-CredentialsGoogle requires Swift 4.0 or newer. You can download this version of the Swift binaries by following this link. Compatibility with other Swift versions is not guaranteed.

Usage

Add dependencies

Add the Kitura-CredentialsGoogle and Credentials packages to the dependencies within your application’s Package.swift file. Substitute "x.x.x" with the latest Kitura-CredentialsGoogle release and the latest Kitura-Credentials release.

.package(url: "https://github.com/KituraKommunity/Kitura-Credentials.git", from: "x.x.x")
.package(url: "https://github.com/KituraKommunity/Kitura-CredentialsGoogle.git", from: "x.x.x")

Add CredentialsGoogle and Credentials to your target's dependencies:

.target(name: "example", dependencies: ["CredentialsGoogle", "Credentials"]),

Import packages

import Credentials
import CredentialsGoogle

Example of Google web login

A complete sample can be found in Kitura-Sample.

First set up the session:

import KituraSession

router.all(middleware: Session(secret: "Very very secret..."))

Create an instance of CredentialsGoogle plugin and register it with Credentials framework:

import Credentials
import CredentialsGoogle

let credentials = Credentials()
let googleCredentials = CredentialsGoogle(clientId: googleClientId,
                                          clientSecret: googleClientSecret,
                                          callbackUrl: serverUrl + "/login/google/callback",
                                          options: options)
credentials.register(googleCredentials)

Where:

  • googleClientId is the Client ID from the credentials tab of your project in the Google Developer's console
  • googleClientSecret is the Client Secret from the credentials tab of your project in the Google Developer's console
  • options is an optional dictionary ([String:Any]) of Google authentication options whose keys are listed in CredentialsGoogleOptions

Note: The callbackUrl parameter above is used to tell the Google web login page where the user's browser should be redirected when the login is successful. It should be a URL handled by the server you are writing.

Specify where to redirect non-authenticated requests:

credentials.options["failureRedirect"] = "/login/google"

Connect credentials middleware to requests to /private:

router.all("/private", middleware: credentials)
router.get("/private/data", handler:
    { request, response, next in
        ...  
        next()
})

And call authenticate to login with Google and to handle the redirect (callback) from the Google login web page after a successful login:

router.get("/login/google",
           handler: credentials.authenticate(googleCredentials.name))

router.get("/login/google/callback",
           handler: credentials.authenticate(googleCredentials.name))

Example of authentication with a Google OAuth token

This example shows how to use CredentialsGoogleToken plugin to authenticate post requests, it shows both the server side and the client side of the request involved.

Server side

First create an instance of Credentials and an instance of CredentialsGoogleToken plugin:

import Credentials
import CredentialsGoogle

let credentials = Credentials()
let googleCredentials = CredentialsGoogleToken(options: options)

Where:

  • options is an optional dictionary ([String:Any]) of Google authentication options whose keys are listed in CredentialsGoogleOptions

Now register the plugin:

credentials.register(googleCredentials)

Connect credentials middleware to post requests:

router.post("/collection/:new", middleware: credentials)

If the authentication is successful, request.userProfile will contain user profile information received from Google:

router.post("/collection/:new") {request, response, next in
  ...
  let profile = request.userProfile
  let userId = profile.id
  let userName = profile.displayName
  ...
  next()
}

Client side

The client needs to put the Google access token in the request's access_token HTTP header field, and "GoogleToken" in the X-token-type field:

let urlRequest = NSMutableURLRequest(URL: NSURL(string: "http://\(serverUrl)/collection/\(name)"))
urlRequest.HTTPMethod = "POST"
urlRequest.HTTPBody = ...

urlRequest.addValue(googleAccessToken, forHTTPHeaderField: "id_token")
urlRequest.addValue("GoogleToken", forHTTPHeaderField: "X-token-type")     
Alamofire.request(urlRequest).responseJSON {response in
  ...
}

API documentation

For more information visit our API reference.

Community

We love to talk server-side Swift, and Kitura. Join our Slack to meet the team!

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.