# Integrating LINE Login with your web app

This page explains how to integrate LINE Login with your web app. If you don’t have an existing app and would like to try LINE Login on a sample app, go to Getting started with LINE Login.

Note
  • This guide describes how to integrate LINE Login v2.1 which supports the OpenID Connect protocol and allows you to retrieve user information with ID tokens. To integrate LINE Login v2 with your web app, see Integrating LINE Login v2.
  • We strongly recommend integrating LINE Login using a LINE SDK if your app's environment allows it. 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 (web login) is based on the OAuth 2.0 authorization code grant flow and the OpenID Connect protocol. Your application must be able to make requests server-side and receive data from the LINE Platform. This is an overview of the web login flow.

LINE Login auth flow

These are the steps involved in the web login process.

  1. Your app directs the user to the LINE Login authorization URL with the required query parameters.
  2. The LINE Login dialog is opened in a browser and the user logs in to be authenticated. After the LINE Platform validates the user’s credentials, the user must also agree to grant the requested permissions to your app.
  3. The LINE Platform redirects the user back to your app via redirect_uri with the authorization code and state in the query string.
  4. Your application requests an access token from the https://api.line.me/oauth2/v2.1/token endpoint with the authorization code.
  5. The LINE Platform validates your application’s request and returns an access token.

Once you have retrieved an access token, you can use it to call the Social API.

# Before you begin

To start integrating your app with LINE Login, make sure you have completed the following.

# Configuring your channel

# Setting redirection URLs

To specify where to redirect the user after login, set a callback URL from the LINE Login tab of your channel settings in the LINE Developers Console.

You can set multiple callback URLs.

Redirect settings

# Applying for email permission

To obtain the email address of a user who has logged in using LINE Login, you must first apply for permission in the LINE Developers Console.

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

    Applying for email permission

  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 app is accepted, "Applied" is displayed under "Email address permission".

# Making an authorization request

To authenticate the user and request permissions of your app, redirect the user to the authorization URL with the required query parameters, as shown in this example.

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 redirect the user using a LINE Login button or with a direct link.

You must include the required query parameters in the URL.

Parameter Type Required Description
response_type String Required code. This tells the LINE Platform to return an authorization code.
client_id String Required Channel ID. Unique identifier for your channel issued by LINE.
redirect_uri String Required Callback URL. URL that users are redirected to after authentication and authorization. Must match one of the callback URLs registered for your channel in the LINE Developers Console.
state String Required A unique alphanumeric string used to prevent cross-site request forgery. This value should be randomly generated by your application. Can't be a URL-encoded string.
scope String Required Permissions requested to the user. For more information, see scopes.
nonce String Optional A string used to prevent replay attacks. 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.
ui_locales String Optional Display language for LINE Login screens. Specify as one or more RFC 5646 (BCP 47) 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.
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).

# Scopes

Specify at least one scope in the scope parameter. These scopes can be specified. To specify multiple scopes, separate them using the 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
openid - -
openid%20email -

To obtain the email address of a user, you must first apply for permission.

An access token with the profile scope is required to get the friendship status between a user and a LINE Official Account.

Apply for other permissions

To apply for additional permissions (other than to obtain the user profile or email address), contact your sales representative or contact our Sales partners.

# Authentication process

After being redirected to the authorization URL, users can log in with any of these authentication methods. The authentication method selected by the user can be checked with an ID token. For ID tokens, see response for Get an access token.

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 and I got a notification about a detected login.

# Auto login

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

Auto login is performed automatically when you log in to the smartphone version of LINE and open the authorization URL with one of these browsers.

  • 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 can be used when accessing the authorization URL in an external browser that has been used for LINE Login in the past.

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.

# Authorization process

Once the user logs in, a consent screen is displayed to request the permissions specified in the scope parameters.

Users access your web app by selecting the items they agree to grant (Scope). Developers should consider the possibility that users may refuse to grant the permissions specified in the authorization URL when developing web apps.

Consent screen

The consent screen may not be displayed
  • 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 isn't displayed.
  • If the permissions include email, a consent screen isn't displayed for a certain period unless the user's email address changes.

# Receiving the authorization code

Once the user is authenticated and authorization is complete, the HTTP status code 302 and these query parameters are returned in the callback URL.

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 state parameter included in the authorization URL of original request. Your app should verify that this value matches the one in the original request.
friendship_status_changed Boolean true if the friendship status between the user and the LINE Official Account changes during login. Otherwise, the value is false. This parameter is only returned if the bot_prompt query parameter is specified when making an authorization request and the option to add your LINE Official Account as a friend when the user logged in is displayed. For more information, see Add a LINE Official Account as a friend when logged in (bot link).

This is an example response.

HTTP/1.1 302 Found
Location : https://client.example.org/cb?code=abcd1234&state=0987poi&friendship_status_changed=true

# Error response

If the user denies the permissions requested by your app, these parameters are returned in the callback URL query string.

Parameter Type Required Description
error String Required Error code.
error_description String Optional Details of the error.
state String Optional OAuth 2.0 state value. Required if the authorization Request included the state parameter.

This is an example of an error response.

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

If the user denies the permissions requested by your app, your app should handle the error appropriately.

# Getting an access token

To get an access token, make an HTTP POST request with the authorization code. Once you have an access token, you can use it to make API calls. The access token is issued at the following endpoint.

# Request

POST https://api.line.me/oauth2/v2.1/token
Request header Description
Content-Type application/x-www-form-urlencoded

# Request body

The information in the request body is in a form-urlencoded format.

Parameters Type Required Description
grant_type String Required authorization_code. Specifies the grant type.
code String Required Authorization code
redirect_uri String Required Callback URL
client_id String Required Channel ID. Found in the LINE Developers Console.
client_secret String Required Channel secret. Found in the LINE Developers Console.

# Example request

This an example of an HTTP POST request to get an access token.

curl -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) 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

This is an example JSON response.

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

# Getting profile information and email address based on ID token

The LINE Platform issues ID tokens compliant with the OpenID Connect specification, allowing you to securely obtain user profile information and email addresses from the LINE Platform. However, before using information contained in an ID token, verify the token with one of these methods:

# Use Social API endpoint

To validate an ID token received as part of an access token and get a user's profile information and email, you can send the ID token to our dedicated validation endpoint.

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

# Write code to validate ID token

You can use any JWT library 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 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 wasn't specified in the authorization request.
amr Array of strings List of authentication methods used by the user. For each authentication method, see Authentication process. One of:
  • 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 wasn't specified in the authorization request.
picture String User's profile image URL. Not included if the profile scope wasn't specified in the authorization request.
email String User's email address. Not included if the email scope wasn't 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 to decode and verify your ID tokens. This 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.

This 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

After getting an access token, use it to call the Social API to log out the user, manage access tokens, and get user profile information. For more information, see: