# Integrating LINE Login with your web app

LINE Login v2.1 supports the OpenID Connect (opens new window) protocol and allows you to retrieve user information with ID tokens. In this guide, we explain how to build it into your web app.

You can follow along using a sample app if you don’t have an existing app that you can update to support LINE Login. To learn more, see Getting started with LINE Login.

Note
  • If you are integrating LINE Login v2.0 with your web app, see Integrating LINE Login (v2.0) with your web app.
  • We strongly recommend building your LINE Login integration with a LINE SDK if it's available for your development environment. We don't recommend using the procedure described in this page for native apps. For more information on using a LINE SDK, see Integrating with native apps.

# Login flow

The LINE Login process for web apps (web login) is based on the OAuth 2.0 authorization code grant flow (opens new window) and the OpenID Connect (opens new window) protocol.

An overview of the web login flow is shown below.

Web apps must implement any part of the login flow that is relevant to them in the flowchart.

Web login flow

# Create a channel

Create a LINE Login channel and configure it for use with a web app.

# Setting a callback URL

After the user has been authenticated and authorized your web app, the authorization code and state are sent to the callback URL.

Set a callback URL from the LINE Login tab of your channel settings in the LINE Developers Console.

You can set more than one callback URL per channel.

Redirect settings

# Requesting permission to access the user's email address

LINE Login v2.1 allows you to obtain the email address of any user who has logged in to your app using LINE Login.

To obtain a user's email address with a web app, you must first apply for permission to do so in the LINE Developers Console.

  1. On the Basic settings tab, under OpenID Connect, click Apply.

    Requesting permission to access the user's email address

  2. Agree to the terms and upload a screenshot of the screen that explains that you're collecting the user's email address and what you're using it for.

    Once your application form has been accepted, "Applied" is displayed under Email address permission.

# Authenticating users and making authorization requests

Initiate the process of authenticating the user with the LINE Platform and authorizing your app. When the user clicks a LINE Login button, redirect them to an authorization URL with the required query parameters, as shown in the example below.

https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=1234567890&redirect_uri=https%3A%2F%2Fexample.com%2Fauth&state=12345abcde&scope=profile%20openid&nonce=09876xyz

You can pass these query parameters to the authorization URL.

Parameters Type Required? Description
response_type String Required code
client_id String Required LINE Login Channel ID. You can find this in the LINE Developers Console.
redirect_uri String Required Callback URL registered with the LINE Developers Console
state String Required A unique alphanumeric string used to prevent cross-site request forgery (opens new window). ** Your web app should generate a random value for each login session. ** This cannot be a URL-encoded string.
scope String Required Permissions requested from the user. For more information, see Scopes.
nonce String Optional A string used to prevent replay attacks (opens new window). This value is returned in an ID token.
prompt String Optional consent。 Used to force the consent screen to be displayed even if the user has already granted all requested permissions.
max_age Number Optional The allowable elapsed time in seconds since the last time the user was authenticated. Corresponds to the max_age parameter defined in the "Authentication Request" section of OpenID Connect Core 1.0 (opens new window).
ui_locales String Optional Display language for LINE Login screens. Specify as one or more RFC 5646 (BCP 47) (opens new window) language tags, separated by spaces, in order of preference. Corresponds to the ui_locales parameter defined in the "Authentication Request" section of OpenID Connect Core 1.0 (opens new window).
bot_prompt String Optional Displays an option to add a LINE Official Account as a friend during login. Set to either normal or aggressive. For more information, see Add a LINE Official Account as a friend when logged in (bot link).
Tip
  • Follow the LINE Login button design guidelines when adding a LINE Login button to your web app.
  • You can also link directly to an authorization URL without showing a LINE Login button.
  • The user's authentication credentials aren't sent to your web app.

# Scopes

You can specify the following scopes with the scope parameter. To specify multiple scopes, separate them using a URL-encoded whitespace character (%20).

Scope Profile information Display name in ID token Profile image URL in ID token Email address in ID token
profile - - -
profile%20openid -
profile%20openid%20email ✓ (see note)
openid - -
openid%20email - ✓ (see note)

Note: Before you can specify the email scope and ask the user for permission to obtain their email address, you must first submit an application requesting access to users' email addresses.

Requesting scopes not listed above

# User authentication

User authentication is handled directly by the LINE Platform

Web apps that support LINE Login don't have to implement the authentication process themselves.

Users can log in through one of the following authentication methods once they have been redirected to an authorization URL.

Authentication method Description
Auto login Log in without user operation. The LINE Login screen or the confirmation screen is not displayed
Log in with email address Log in by entering an email address and password on the LINE Login screen
Log in with QR code Log in by scanning a QR code displayed on the LINE Login screen using the QR code reader on the LINE app for smartphones
Single Sign On (SSO) Login Log in by clicking the login button on the confirmation screen showing "Log in with the following account"
SSO takes precedence over auto login

SSO takes precedence in an environment where both auto login and SSO are enabled. For more information, see LINE Login shows the "Login with the following account" screen. in FAQ.

Login notification

After you log in, a login notification is sent from the LINE Official Account. For more information about login notifications, see the help topics [I got a login notification from the LINE official account] (https://help.line.me/line/android/pc?lang=en&contentId=20008522) and I got a notification about a detected login (opens new window).

Authentication method chosen by the user

You can examine the ID token to determine which authentication method was selected by the user. To learn more about ID tokens, see the "Response" section of Getting an access token.

# Auto login

Login is enabled without user operation. The LINE Login screen or the confirmation screen isn't displayed.

Users are automatically logged in when they visit an authorization URL from one of the following browsers while logged in to LINE's smartphone app.

  • LINE's in-app browser
  • External browser initially used for LINE Login
Auto login doesn't work on the LINE app for PC or Mac

For more information on environments that can use auto login, see How does auto login work? in the FAQ.

# Log in with email address or QR code

A user can login with one of these authentication methods.

  • Log in with email address
  • Log in with QR code (displayed only on LINE app for PC or Mac)

Login dialog

These login methods can be used when accessing the authorization URL in an external browser for the first time without logging in to the LINE app for smartphones.

# Single Sign On (SSO) Login

The user can log in only by clicking the login button.

Confirmation Screen

SSO is available when the user visits an authorization URL in an external browser that they used to log in to LINE before.

SSO is a function that uses cookies

Once you run LINE Login from your web application, the cookie is saved under the domain name access.line.me. As long as the cookie is valid, the SSO screen is displayed for login in the same browser.

# User authorization

User authorization is handled directly by the LINE Platform

Web apps that support LINE Login don't have to implement the authorization process themselves.

Developers specify the information they'd like to access in the scope parameter, and users are asked to authorize those requests.

Note that users may access your web app without granting it some or all of the requested permissions. When building your web app, you should account for the possibility that the user may not grant the permissions you specified in the authorization URL.

Example Consent Screen

Consent screen

The consent screen may not always be shown
  • If the permissions specified in the scope parameter are profile and/or openid and the user has already granted all the permissions, the consent screen is not displayed.
  • If the permissions include email, a consent screen is not displayed for a certain period unless the user's email address changes.

# Receiving the authorization code or error response with a web app

The user is redirected to the callback URL once they have completed the authentication and authorization process.

If the user has granted access to your app, an authorization code is returned.

If the user has not granted access to your app, an error response is returned.

# Receiving the authorization code

Once the user has been authenticated and has completed the authorization step, they are redirected to the callback URL with these query parameters.

Parameter Type Description
code String Authorization code used to get an access token. Valid for 10 minutes. This authorization code can only be used once.
state String A unique alphanumeric string used to prevent cross-site request forgery (opens new window). Verify that this matches the value of the state parameter given to the authorization URL.
friendship_status_changed Boolean true if the friendship status between the user and the LINE Official Account linked to the channel has changed when the user logs in. Otherwise, the value is false.
Note: This parameter is only returned if you specify the bot_prompt query parameter when authenticating users and making authorization requests and the user was given the option to add your LINE Official Account as a friend when they logged in. For more information, see Add a LINE Official Account as a friend when logged in (bot links).

Example URL of the redirect target:

https://example.com/callback?code=abcd1234&state=0987poi&friendship_status_changed=true

# Receiving an error response

If the user declines to grant the permissions requested by your app, they are redirected to the callback URL with these query parameters:

Parameter Type Required Description
error String Required Error code.
error_description String Optional A description of the error.
state String Optional The state parameter included in the authorization URL. You can use this value to determine which process was denied.

Example URL of the redirect target:

https://example.com/callback?error=access_denied&error_description=The+resource+owner+denied+the+request.&state=0987poi

# Getting an access token with a web app

You can obtain an access token if the state parameter that you receive along with the authorization code from the LINE Platform matches the state parameter that you specified when authenticating the user and making an authorization request.

Example request:

curl -v -X POST https://api.line.me/oauth2/v2.1/token \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'grant_type=authorization_code' \
-d 'code=xxx' \
-d 'redirect_uri=xxx' \
-d 'client_id=xxx' \
-d 'client_secret=xxx'

# Response

The LINE Platform validates the request and returns an access token and other data as shown in the table below.

Note

New or changed LINE Login functions may cause changes in the structure of the payload JSON object. These changes may include added properties, variations in property order, and added/removed white space and line breaks. Design your backend so that it can handle payload data objects with unexpected structures.

Property Type Description
access_token String Access token. Valid for 30 days.
expires_in Number Amount of time in seconds until the access token expires.
id_token String JSON Web Token (JWT) (opens new window) that includes information about the user. This field is returned only if openid is specified in the scope. For more information, see Verify ID token.
refresh_token String Token used to get a new access token. Valid up until 90 days after the access token issued.
scope String Permissions granted by the user. However, the email scope isn't returned as a value of the scope property even if the permission has been granted.
token_type String Bearer

Example response:

{
    "access_token": "bNl4YEFPI/hjFWhTqexp4MuEw5YPs...",
    "expires_in": 2592000,
    "id_token": "eyJhbGciOiJIUzI1NiJ9...",
    "refresh_token": "Aa1FdeggRhTnPNNpxr8p",
    "scope": "profile",
    "token_type": "Bearer"
}

To learn more, see Issuing access tokens in the LINE Login v2.1 API reference.

# Getting profile information and email addresses from ID tokens

The LINE Platform issues ID tokens compliant with the OpenID Connect (opens new window) specification, allowing you to securely obtain user profile information and email addresses from the LINE Platform. Verify an ID token through one of these methods before using the information it contains.

# Use a LINE Login API endpoint

To verify the ID token that you receive along with an access token and obtain the corresponding user's profile information and email address, you can simply send the ID token to our dedicated API endpoint.

Example request:

curl -v -X POST 'https://api.line.me/oauth2/v2.1/verify' \
 -d 'id_token=eyJraWQiOiIxNmUwNGQ0ZTU2NzgzYTc5MmRjYjQ2ODRkOD...'

Example response:

{
    "iss": "https://access.line.me",
    "sub": "U1234567890abcdef1234567890abcdef",
    "aud": "1234567890",
    "exp": 1504169092,
    "iat": 1504263657,
    "nonce": "0987654asdf",
    "amr": [
        "pwd",
        "linesso",
        "lineqr"
    ],
    "name": "Taro Line",
    "picture": "https://sample_line.me/aBcdefg123456",
    "email": "taro.line@example.com"
}

For more information, see Verify ID token in the LINE Login API reference.

# Write code to validate ID tokens

You can use any JWT library (opens new window) or write your own code from scratch to validate ID tokens and obtain user profile information and email addresses.

# ID tokens

ID tokens are JSON web tokens (JWT) with information about the user. The ID token consists of a header, payload, and signature separated by period (.) characters. Each part is a base64url-encoded value. For more information, see the JWT (opens new window) specification.

This is an example of a decoded header value. In this example, the header declares that the encoded object uses the HMAC SHA-256 algorithm. LINE Login only uses HMAC SHA-256.

{
  "typ": "JWT",
  "alg": "HS256"
}
# Payload

The user's information is found in the payload section.

Property Type Description
iss String https://access.line.me. URL where the ID token is generated.
sub String User ID for which the ID token is generated
aud String Channel ID
exp Number The expiry date of the token in UNIX time.
iat Number Time when the ID token was generated in UNIX time.
auth_time Number Time when the user was authenticated in UNIX time. Not included if the max_age parameter wasn't specified in the authorization request.
nonce String The nonce value specified in the authorization URL. Not included if the nonce value was not specified in the authorization request.
amr Array of strings List of authentication methods used by the user. It includes one of the values below. For more information on each of these authentication methods, see User authentication.
  • pwd: Log in with email and password
  • lineautologin: LINE automatic login (including through LINE SDK)
  • lineqr: Log in with QR code
  • linesso: Log in with single sign-on
name String User's display name. Not included if the profile scope was not specified in the authorization request.
picture String User's profile image URL. Not included if the profile scope was not specified in the authorization request.
email String User's email address. Not included if the email scope was not specified in the authorization request.

This is an example of a decoded payload section.

{
    "iss": "https://access.line.me",
    "sub": "U1234567890abcdef1234567890abcdef ",
    "aud": "1234567890",
    "exp": 1504169092,
    "iat": 1504263657,
    "nonce": "0987654asdf",
    "amr": ["pwd"],
    "name": "Taro Line",
    "picture": "https://sample_line.me/aBcdefg123456"
}
# Signature

The signature is used to verify the validity of the response. The signature is a base64url-encoded hash computed using the HMAC SHA-256 algorithm with the base64url-encoded header + "." + payload as the value and the channel secret as a key. To ensure the security of your app, you should always verify the signature of the token.

# Decoding and validating ID tokens

To decode and validate ID tokens, you can either use a JWT library or follow the instructions below.

# Use a JWT library

You can use the publicly available JWT libraries (opens new window) to decode and verify your ID tokens. The following is an example of how to decode an ID token using a library for Python®.

import jwt

decoded_id_token = jwt.decode(id_token,
                              channel_secret,
                              audience=channel_id,
                              issuer='https://access.line.me',
                              algorithms=['HS256'])

# check nonce (Optional. But strongly recommended)
nonce = '_stored_in_session_'
expected_nonce = decoded_id_token.get('nonce')
if nonce != decoded_id_token.get('nonce'):
    raise RuntimeError('invalid nonce')
# Decode and validate ID token
  1. Split the header, payload, and signature sections using the period (.) character.
  2. Base64-URL decode each section
  3. Compute the hash using the base64url-encoded header + "." + payload as the value and the channel secret as a key. Verify that the value is the same as the decoded signature.
  4. Confirm that the ID token was sent from LINE by checking that the value of iss is https://access.line.me.
  5. Confirm that the ID token is for your channel by checking that aud matches your channel ID.
  6. To confirm the validity of the ID token, confirm that the exp value is greater than the UNIX timestamp at the time of verification.
  7. To prevent replay attacks, confirm that the value of nonce is the same as the nonce value specified in the authorization request. Store the nonce value with the user session. Although this step is optional, we strongly recommend including the nonce value.

The following is an example using Python 3.

import base64
import hashlib
import hmac
import json
import time


def base64url_decode(target):
    rem = len(target) % 4
    if rem > 0:
        target += '=' * (4 - rem)

    return base64.urlsafe_b64decode(target)


def check_signature(key, target, signature):
    calc_signature = hmac.new(
        key.encode('utf-8'),
        target.encode('utf-8'),
        hashlib.sha256
    ).digest()

    return hmac.compare_digest(signature, calc_signature)


def decode_id_token(id_token, channel_id, channel_secret, nonce=None):
    # step 1
    header, payload, signature = id_token.split('.')

    # step 2
    header_decoded = base64url_decode(header)
    payload_decoded = base64url_decode(payload)
    signature_decoded = base64url_decode(signature)

    # step 3
    valid_signature = check_signature(channel_secret,
                                      header + '.' + payload,
                                      signature_decoded)
    if not valid_signature:
        raise RuntimeError('invalid signature')

    payload_json = json.loads(payload_decoded.decode('utf-8'))

    # step 4
    if payload_json.get('iss') != 'https://access.line.me':
        raise RuntimeError('invalid iss')

    # step 5
    if payload_json.get('aud') != channel_id:
        raise RuntimeError('invalid aud')

    # step 6
    if int(time.time()) > payload_json.get('exp'):
        raise RuntimeError('invalid exp')

    # step 7 (Optional. But strongly recommended)
    if nonce is not None:
        if payload_json.get('nonce') != nonce:
            raise RuntimeError('invalid nonce')

    return payload_json

# Next steps

Once you have an access token, you can use it to do the following: