Skip to content

Instantly share code, notes, and snippets.

@prschmid
Last active August 17, 2017 21:31
Show Gist options
  • Save prschmid/eba6a1f5f116c46c11d619150a0019fa to your computer and use it in GitHub Desktop.
Save prschmid/eba6a1f5f116c46c11d619150a0019fa to your computer and use it in GitHub Desktop.
Programmatically Logging in to a site with the Auth0 Lock Widget
# The site you want to log in to
SITE_URL = nil
# The username/password you want to log in with
USERNAME = nil
PASSWORD = nil
# All of these details are visible when you do a "login" and
# inspect the parameters POSTed when you click "login" on
# the Lock Widget. You'll want to do this in your favorite
# web browser while having the developer console open and
# inspecting the network traffic.
AUTH0_CLIENT_ID = nil
AUTH0_ACCOUNT_URL = nil
AUTH0_CONNECTION = nil
AUTH0_TENANT = nil
AUTH0_APP_LOGIN_REDIRECT_URL = nil
# Make an initial call to the page that has the
# state value that is used when POSTing to login
response = RestClient.get(SITE_URL)
state = /state: '([^']+)'/.match(response.body)[1]
# POST the username/password and attempt to log in
response = RestClient.post(
"#{AUTH0_ACCOUNT_URL}/usernamepassword/login",
payload={
client_id: AUTH0_CLIENT_ID,
connection: AUTH0_CONNECTION,
redirect_uri: AUTH0_APP_LOGIN_REDIRECT_URL,
response_type: "code",
scope: "openid email crud:all",
sso: true,
state: state,
tenant: AUTH0_TENANT,
username: USERNAME,
password: PASSWORD
},
headers={
cookies: response.cookies
}
)
# Extract the hidden form elements that we need to
# POST to the callback
form = Nokogiri::HTML(response.body)
payload = {}
form.css('input').each do |input|
if input.attributes['type'].value == 'hidden'
payload[input.attributes['name'].value] = input.attributes['value'].value
end
end
# Call the callback, and then redirect to where the
# callback says to go.
begin
RestClient.post(
"#{AUTH0_ACCOUNT_URL}/login/callback",
payload=payload,
headers={
cookies: response.cookies
}
)
rescue RestClient::MovedPermanently,
RestClient::Found,
RestClient::TemporaryRedirect => err
logged_in_response = RestClient.get(err.response.headers[:location], headers={cookies: err.response.cookies})
end
# The user is now logged in and logged_in_response now has all the
# appropriate cookies that can be then used in subsequent call the
# the site
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment