Skip to content

Instantly share code, notes, and snippets.

@mpakus
Created October 31, 2021 09:32
Show Gist options
  • Save mpakus/a00ce32b04e9150b1346d0f54c80a718 to your computer and use it in GitHub Desktop.
Save mpakus/a00ce32b04e9150b1346d0f54c80a718 to your computer and use it in GitHub Desktop.
Shortest way to get Linkedin authorized access token
require 'sinatra'
require "sinatra/reloader" if development?
require 'http'
require 'json'
# https://www.linkedin.com/developers/apps
class Settings
CLIENT_ID = '...'
CLIENT_SECRET = '...'
ACCESS_TOKEN = '...'
URL = 'http://your-app-url'
end
get '/' do
url = Settings::URL + '/auth'
scope = 'r_liteprofile r_emailaddress'
redirect "https://www.linkedin.com/oauth/v2/authorization?client_id=#{Settings::CLIENT_ID}&state=#{SecureRandom.uuid}&scope=#{scope}&redirect_uri=#{url}&response_type=code"
end
get '/auth' do
uri = 'https://www.linkedin.com/oauth/v2/accessToken'
request = {
form: {
grant_type: 'authorization_code',
code: params[:code],
client_id: Settings::CLIENT_ID,
client_secret: Settings::CLIENT_SECRET,
redirect_uri: Settings::URL + '/auth'
}
}
response = HTTP.post(uri, request)
p response.parse
end
get '/positions' do
response = HTTP
.auth("Bearer #{Settings::ACCESS_TOKEN}")
.get('https://api.linkedin.com/v2/me')
user = JSON.parse(response.body)
=begin
{
"localizedLastName" => "Ibragimov",
"profilePicture" => { "displayImage" => "urn:li:digitalmediaAsset:C5103AQFNr5ZVJMbOeA" },
"firstName" => {
"localized" => { "en_US" => "Renat" },
"preferredLocale" => { "country" => "US", "language" => "en" }
},
"lastName" => {
"localized" => { "en_US" => "Ibragimov" },
"preferredLocale" => { "country" => "US", "language" => "en" }
},
"id" => "zxzQnHQpnU",
"localizedFirstName" => "Renat"
}
=end
slim :positions, layout: false, locals: { user: user }
end
__END__
@@ positions
html
head
title MpaKus LinkedIn positions history
body
= user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment