Introduction
OAuth allows users to authenticate with third-party services like TikTok without sharing their credentials. In this guide, we’ll walk through the steps of integrating TikTok’s Login Kit into a Rails app using direct API calls, offering full control over each stage of the process.
Prerequisites
- TikTok Developer Account: Register on the TikTok Developer Portal to create an application. This account is necessary to obtain your Client Key (Client ID) and Client Secret.
- Rails Setup: This guide assumes you have a Rails application already set up. You can create a new app by running
rails new MyApp
if needed.
Step 1: Set Up TikTok Application (Sandbox and Production)
TikTok provides two environments:
- Sandbox: Use this for testing and development.
- Production: Use this for live applications.
To configure both:
- Go to the TikTok Developer Portal.
- Register your application. Once registered, you’ll be provided with a Client Key and Client Secret for both sandbox and production environments.
- Add separate Redirect URIs for sandbox and production:
- Sandbox URI: Set this to your local development callback, e.g.,
http://localhost:3000/oauth/callback
. - Production URI: Set this to your live domain callback, e.g.,
https://yourdomain.com/oauth/callback
.
- Sandbox URI: Set this to your local development callback, e.g.,
TikTok restricts redirect URIs to HTTPS (except for localhost
), and they must be absolute URLs (e.g., https://yourdomain.com/oauth/callback
). Configure up to 10 URIs if needed.
Step 2: Configure Environment Variables
In your Rails app, use environment variables to store TikTok credentials securely. You’ll need to differentiate between sandbox and production:
# .env
TIKTOK_CLIENT_KEY=your__client_key
TIKTOK_CLIENT_SECRET=your__client_secret
TIKTOK_REDIRECT_UR=http://localhost:3000/oauth/callback
Use the appropriate values based on the environment.
Step 3: Add OAuth Routes
In config/routes.rb
, define routes to handle the TikTok OAuth flow:
get 'oauth', to: 'tiktok#oauth_request'
get 'oauth/callback', to: 'tiktok#oauth_callback'
Step 4: Create TikTok Controller
In app/controllers/tiktok_controller.rb
, create actions to handle the OAuth request and callback:
- Generate a CSRF
state
token for security. - Redirect to TikTok’s authorization URL.
- Handle the callback and exchange the authorization code for an access token.
Here’s the controller setup:
class TiktokController < ApplicationController
require 'net/http'
require 'json'
# Redirect user to TikTok for authorization
def oauth_request
# Generate a CSRF token and save it in the session
session[:oauth_state] = SecureRandom.hex(24)
# Set TikTok OAuth URL and parameters
tiktok_auth_url = "https://www.tiktok.com/v2/auth/authorize?" + {
client_key: ENV['TIKTOK_CLIENT_KEY_SANDBOX'], # Change to PRODUCTION keys if in production
response_type: 'code',
scope: 'user.info.basic,video.upload',
redirect_uri: ENV['TIKTOK_REDIRECT_URI_SANDBOX'], # Change to PRODUCTION redirect URI if in production
state: session[:oauth_state]
}.to_query
# Redirect user to TikTok’s authorization page
redirect_to tiktok_auth_url
end
# Handle TikTok’s callback with authorization code
def oauth_callback
# Validate state parameter to prevent CSRF attacks
if params[:state] != session[:oauth_state]
redirect_to root_path, alert: "CSRF detected, state does not match."
return
end
# Exchange authorization code for an access token
token_response = exchange_code_for_token(params[:code])
if token_response['access_token']
# Successfully obtained access token
# Save or use the access token as needed
render json: { access_token: token_response['access_token'] }
else
# Handle error
redirect_to root_path, alert: "Failed to obtain access token."
end
end
private
# Exchange authorization code for access token
def exchange_code_for_token(code)
uri = URI('https://open-api.tiktok.com/oauth/access_token/')
response = Net::HTTP.post_form(uri, {
client_key: ENV['TIKTOK_CLIENT_KEY_SANDBOX'], # Use production if necessary
client_secret: ENV['TIKTOK_CLIENT_SECRET_SANDBOX'], # Use production if necessary
code: code,
grant_type: 'authorization_code',
redirect_uri: ENV['TIKTOK_REDIRECT_URI_SANDBOX'] # Use production URI if necessary
})
JSON.parse(response.body
end
end
Step 5: Add a Login Button
In your view, create a link to initiate the OAuth flow. This link will start the TikTok authentication process:
<%= link_to "Continue with TikTok", oauth_path, class: "btn btn-primary" %>
Step 6: Testing the OAuth Flow
- Switch to the sandbox environment by ensuring your environment variables are set to the sandbox credentials.
- Click the “Continue with TikTok” button to initiate the flow.
- Authorize the app on TikTok’s login page.
- Retrieve the access token in the callback to verify the process.
To move to production, simply change the environment variables to use production keys.
Resources
- TikTok Developer Portal: TikTok for Developers – Register your application and manage app credentials.
- OAuth Documentation: TikTok OAuth Guide – Official documentation for TikTok’s Login Kit.
- OAuth Security Guide: OWASP OAuth Security – General security practices for handling OAuth flows.
Conclusion
This guide provides an in-depth approach to integrating TikTok OAuth in Rails without using gems, allowing you to maintain full control over the OAuth process. By setting up sandbox and production environments, you can safely test and deploy TikTok Login functionality in your Rails application.