OAuth2 Login

Edit on Github
Open in Playground View Demo

Introduction

This sample showcases how to use amp-access to allow an OAuth2-based login flow on your AMP pages, such as Google, Facebook and GitHub sign-in.

amp-access requires the definition of 3 endpoints as documented here. This sample allows an user to login and logout using an OAuth2-based flow. Logout is implemented by configuring a second endpoint in the login property sign-out, find more here.

<script id="amp-access" type="application/json">
{
    "authorization": "https://ampbyexample.com/oauth/status?_=RANDOM",
    "noPingback": "true",
    "login": {
      "facebook-sign-in": "https://ampbyexample.com/oauth/login/facebook",
      "google-sign-in": "https://ampbyexample.com/oauth/login/google",
      "github-sign-in": "https://ampbyexample.com/oauth/login/github",
      "sign-out": "https://ampbyexample.com/oauth/logout"
    },
    "authorizationFallbackResponse": {
        "error": true,
        "loggedIn": false
    }
}
</script>

We use amp-access to integrate an OAuth2-based login and to show and hide the login button depending on whether the user is logged in. on="tap:amp-access.login-google-sign-in" specifies which action should be taken when clicking on the login button: login defines the property inside the amp-access json configuration, while google-sign-in defines the endpoint.

Example

Please login to view content

<div amp-access="NOT loggedIn"
  role="button"
  tabindex="0"
  amp-access-hide>
  <h3 class="m1">Please login to view content</h3>
  <button on="tap:amp-access.login-google-sign-in"
    class="ampstart-btn m2 caps">Google Login</button>
  <button on="tap:amp-access.login-facebook-sign-in"
    class="ampstart-btn m2 caps">Facebook Login</button>
  <button on="tap:amp-access.login-github-sign-in"
    class="ampstart-btn m2 caps">GitHub Login</button>
</div>

When logged in, we use amp-access-template to display information returned from the authorization endpoint, in this case the user's name.

Example

<div class="p2"
  amp-access="loggedIn"
  amp-access-hide>
  <template amp-access-template
    type="amp-mustache">
    <p>Hello {{name}}! You are logged in.</p>
  </template>
</div>

We specify the logout via a login endpoint to be able to use the return URL environment variable.

Example

<button amp-access="loggedIn"
  amp-access-hide
  tabindex="0"
  on="tap:amp-access.login-sign-out"
  class="ampstart-btn m2 caps">Logout</button>