Devise LDAP Authenticatable not binding properly? - ruby-on-rails

For some reason, authenticating with Devise on my page doesn't seem to work, resulting in an Unauthorized 401 error. Going through the steps in net/ldap seem to bind just fine. I'm not sure where the problem lies.
Output from the server:
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"â", "authenticity_token"=>"0uaLJJKobrDkn1mGDRP/RM6gIec+Wi7oykgWYuutsvk=", "user"=>{"login"=><login>, "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Sign in"}
Completed 401 Unauthorized in 14ms
From ldap.yml:
development:
host: <hostname>
port: 389
attribute: sAMAccountName
base: <base>
admin_user: <admin user>
admin_password: <admin pass>
ssl: false
# <<: *AUTHORIZATIONS
From devise.rb:
config.ldap_use_admin_to_bind = true
config.authentication_keys = [ :login ]
From testing on irb:
$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'net/ldap'
=> true
irb(main):003:0> ldap = Net::LDAP.new
=> #<Net::LDAP:0x141d19 #host="127.0.0.1", #auth={:method=>:anonymous}, #encryption=nil, #base="dc=com", #port=389, #verbose=false, #open_connection=nil>
irb(main):004:0> ldap.host = <hostname>
=> <hostname>
irb(main):005:0> ldap.port = 389
=> 389
irb(main):006:0> ldap.base = <base>
=> <base>
irb(main):007:0> ldap.auth <admin user>, <admin pass>
=> {:method=>:simple, :username=><admin user>, :password=><admin pass>}
irb(main):008:0> dn = ldap.search( :filter => Net::LDAP::Filter.eq('sAMAccountName', <login>)).first.dn
=> <login dn information>
irb(main):009:0> ldap.auth dn, <password>
=> {:method=>:simple, :username=><login dn information>, :password=><password>}
irb(main):010:0> ldap.bind
=> true
As you can see, the bind works fine through normal net/ldap testing, but it doesn't seem to work when I go through the actual Rails site for some reason, even if I replicate what the Devise module should be doing.

The authentication key is not :login but :username. it might fix your problem

In case anyone else is having this issue, this question gave me the fix I needed.

Related

Devise LDAP can't find user, but logs in fine

So when I authorize a user with the devise_ldap_authenticatable gem, I get the following logged information:
LDAP: LDAP dn lookup: sAMAccountName=john.smith
LDAP: LDAP search for login: sAMAccountName=john.smith
LDAP: LDAP search yielded 0 matches
LDAP: Authorizing user lt\john.smith
As I understand it, the search fails to return a user, which I would like to find so I could set other attributes based off of LDAP fields (mainly department).
I've checked that this search should work with the following rake task:
desc "LDAP Test"
task ldap: :environment do
ldap = Net::LDAP.new :host => ENV['LDAP_IP'],
:port => ENV['LDAP_PORT'],
:encryption => :simple_tls,
:base => ENV['LDAP_BASE'],
:auth => {
:method => :simple,
:username => ENV['LDAP_LOGIN'],
:password => ENV['LDAP_PASSWORD']
}
if ldap.bind
ldap.search(:base => ENV['LDAP_BASE'], :filter => Net::LDAP::Filter.eq("sAMAccountName", "john.smith"), :attributes => ["sAMAccountName", "department"], :return_result => false) do |entry|
entry.each do |attr, values|
puts "#{attr}: #{values.first}"
end
end
else
puts "Connection failed! Code: #{ldap.get_operation_result.code}, message: #{ldap.get_operation_result.message}"
end
end
Which returns:
dn: CN=John Smith,OU=Temporary Staff,OU=Users,DC=lt,DC=local
department: Bioinformatics
samaccountname: Johh.Smith
Does anyone know why the login search could be failing? My config files are as follows:
devise.rb:
# ==> LDAP Configuration
config.ldap_logger = true
config.ldap_create_user = true
config.ldap_update_password = false
# config.ldap_config = "#{Rails.root}/config/ldap.yml"
config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "lt\\#{login}"}
# config.ldap_check_group_membership = false
# config.ldap_check_attributes = false
config.ldap_use_admin_to_bind = true
ldap.yml:
development:
host: <%= ENV['LDAP_IP'] %>
port: <%= ENV['LDAP_PORT'] %>
attribute: sAMAccountName
base: <%= ENV['LDAP_BASE'] %>
admin_user: <%= ENV['LDAP_LOGIN'] %>
admin_password: <%= ENV['LDAP_PASSWORD'] %>
ssl: true
# <<: *AUTHORIZATIONS
I would use a packet sniffer like Wireshark to see the difference between the LDAP requests in the rake task vs. devise. The UnboundID LDAP SDK for Java also ships with a tool called LDAPDebugger that you can use as a proxy between your app and Active Directory to decode the traffic.
I hope this helps.

Using ldap to connect to ad with devise ruby on rails

Question I am having issues connecting to my Microsoft Active Directory using the devise_ldap_authentication. For some reason I keep getting LDAP search yielded 0 matches when using it with devise and I am 100% certain I am using the correct credentials, so I wrote a test class using 'net/ldap' to see if I could yeild a correct match and presto it works with my test class but, I still can't authenticate with devise_ldap_auth. Any help would be greatly appreciated or help with setting up my config/ldap.yml to match my test class.
Here is my config/ldap.yml
#Environment
development:
host: myldap.mydomain.com
port: 389
attribute: sAMAccountname
base: dc=mydomain, dc=com
admin_user: cn=admin,dc=mydomain,dc=com
admin_password: password
#ssl: false
Here is my devise.rb
Devise.setup do |config|
# ==> LDAP Configuration
config.ldap_logger = true
# config.ldap_create_user = false
# config.ldap_update_password = true
config.ldap_config = "#{Rails.root}/config/ldap.yml"
# config.ldap_check_group_membership = false
# config.ldap_check_group_membership_without_admin = false
config.ldap_check_attributes = true
#config.ldap_use_admin_to_bind = true
# config.ldap_ad_group_check = false
this is what I get back when using ldap with devise.
D, [2016-06-24T07:01:30.558440 #42760] DEBUG -- : LDAP: LDAP dn lookup: sAMAccountName=snow
D, [2016-06-24T07:01:30.558507 #42760] DEBUG -- : LDAP: LDAP dn lookup: sAMAccountName=snow
D, [2016-06-24T07:01:30.558549 #42760] DEBUG -- : LDAP: LDAP search for login: sAMAccountName=snow
D, [2016-06-24T07:01:30.558579 #42760] DEBUG -- : LDAP: LDAP search for login: sAMAccountName=snow
D, [2016-06-24T07:01:30.594029 #42760] DEBUG -- : LDAP: LDAP search yielded 0 matches
D, [2016-06-24T07:01:30.594099 #42760] DEBUG -- : LDAP: LDAP search yielded 0 matches
D, [2016-06-24T07:01:30.594146 #42760] DEBUG -- : LDAP: Authorizing user sAMAccountName=snow,dc=mydomain, dc=com
D, [2016-06-24T07:01:30.594180 #42760] DEBUG -- : LDAP: Authorizing user sAMAccountName=snow,dc=mydomain, dc=com
D, [2016-06-24T07:01:30.611308 #42760] DEBUG -- : LDAP: Not authorized because not authenticated.
D, [2016-06-24T07:01:30.611377 #42760] DEBUG -- : LDAP: Not authorized because not authenticated.
Here is my test class that works to authenticate with ldap on my microsoft AD
require 'net/ldap' # gem install ruby-net-ldap
module Test
class PutAd
SERVER = 'myldap.mydomain.com'
PORT = 389
BASE = 'DC=mydomain,DC=com'
DOMAIN = 'mydomain.com'
ATTR_SV = {
:login => :samaccountname,
:first_name => :givenname,
:last_name => :sn,
:email => :mail
}
def self.authenticate(login, pass)
return nil if login.empty? or pass.empty?
conn = Net::LDAP.new :host => SERVER,
:port => PORT,
:base => BASE,
:auth => { :username => "#{login}##{DOMAIN}",
:password => pass,
:method => :simple }
if conn.bind and user = conn.search(:filter => "sAMAccountName=#{login}").first
return self.new(user)
else
return nil
end
rescue Net::LDAP::LdapError => e
return nil
end
end
end
^This will return my account information if it matches if not it will return nil.
Turns out my company has a different way of authorizing a user. I added the advanced flag to my devise ldap install, and set this accordingly and presto it worked.
==> Advanced LDAP Configuration
config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "#{login}#mydomain.com"}

Gmail not sending with env variables in Rails 4 project, but env variables are displayed in console

I am working on a tutorial about ActiveRecords and needed to configure ActionMailer.
I have Environmental Variables configured in ~/.bashrc and this system has been working reliably.
I configured everything in the development.rb
development.rb
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { :host => "localhost:3000" }
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
user_name: ENV[ "GMAIL_USERNAME" ],
password: ENV[ "GMAIL_PASSWORD"],
authentication: "plain",
enable_starttls_auto: true
}
My contact_form.rb model is:
class ContactForm < MailForm::Base
attribute :name, :validate => true
attribute :email, :validate => /\A([\w\.%\+\-]+)#([\w\-]+\.)+([\w]{2,})\z/i
attribute :message, :validate => true
# Declare the e-mail headers
def headers
{
:subject => 'ArcadeNomad - Contact Request',
:to => ENV[ "OWNER_EMAIL" ],
:from => ENV[ "OWNER_EMAIL" ]
}
end
end
When I test everything in rails console i get:
Machine:dev_arcadenomad_com Account$ rails c --sandbox
Loading development environment in sandbox (Rails 4.2.1)
Any modifications you make will be rolled back on exit
>> contact = ContactForm.new(:name => 'Name', :email => 'SomeMail#domain.tld', :message => 'I love ArcadeNomad!')
=> #<ContactForm:0x007fde0d6d38a8 #name="Name", #email="SomeMail#domain.tld", #message="I love ArcadeNomad!">
>> contact.valid?
=> true
>> contact.deliver
Rendered /Users/MyAccount/.rvm/gems/ruby-2.2.1#learn-active-records/gems/mail_form-1.5.1/lib/mail_form/views/mail_form/contact.erb (8.1ms)
MailForm::Notifier#contact: processed outbound mail in 239.6ms
Sent mail to mymail#gmail.com (6.9ms)
Date: Sat, 27 Jun 2015 17:32:01 +0200
From: mymail#gmail.com
To: mymail#gmail.com
Message-ID: <LongString#machine.domain.tl.mail>
Subject: ArcadeNomad - Contact Request
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<h4 style="text-decoration:underline">ArcadeNomad - Contact Request</h4>
<p><b>Name:</b>
Name</p>
<p><b>Email:</b>
SomeMail#domain.tld</p>
<p><b>Message:</b>
I love ArcadeNomad!</p>
=> true
But no mail is delivered.
If I hardcode my credentials into development.rb everything works.
When I test for ENV[ "GMAIL_USERNAME" ] in rails console my mail credentials are displayed correctly.
What am I missing?

POST-request changed to GET-request after SSL-redirect

i want to Login as a user in my Rails-application. Everything works fine without SSL. When SSL is activated on staging/production there is an SSL-redirect that change my POST-request in a GET-request. So instead of calling the CREATE-method the SHOW-method in my Session-Controller is called. Here are the logs:
Started POST "/authentication_customer_user_sessions" for *********** at 2014-07-30 10:42:30 +0200
Processing by Authentication::CustomerUserSessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authentication_customer_user_session"=>{"redirect_path"=>"user_index_path", "login"=>"user", "password"=>"[FILTERED]", "remember_me"=>"0"}, "account"=>{"signup"=>"with_signup"}, "commit"=>"signin"}
Redirected to https://staging.myserver.de/authentication_customer_user_sessions
Completed 302 Found in 5ms
Started GET "/authentication_customer_user_sessions" for *********** at 2014-07-30 10:42:30 +0200
AbstractController::ActionNotFound (The action 'show' could not be found for Authentication::CustomerUserSessionsController):
In my Authentication::CustomerUserSession-Controller i activate SSL with
private
def ssl_required?
return false if request.local? || RAILS_ENV == 'test' || RAILS_ENV == 'development'
true
end
So what can i do in my Rails-App to avoid this problem without deactivating SSL for this controller? Thanks for any help!
I'm using authlogic for authentication.
Ok i solved my problem. The solution was to force https in the login-form. This is my code-snippet:
<%= form_for Authentication::CustomerUserSession.new, :as => :authentication_customer_user_session, :url => authentication_customer_user_sessions_url(:protocol => 'https') do |f| %>
Or just a bit more generic:
<%= form_for Authentication::CustomerUserSession.new, :as => :authentication_customer_user_session, :url => authentication_customer_user_sessions_url(:protocol => (Rails.env.production? || Rails.env.staging?) ? 'https' : 'http') do |f| %>

Rails 3 mailer not working and not logging any errors

I have tried all kinds of configurations but still I can't send an email in my development environment from rails.
I installed mailutils to try this from the command line and it worked, I received the email (in spam of course): echo test | mail -s Subject user#example.com
Here's my config:
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = true # still no logs about emails
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true # I can't believe I have to add this option. Does it even exist? I found it on google.
config.action_mailer.smtp_settings = {
:enable_starttls_auto => true,
:address => "smtp.gmail.com",
:port => 587,
:domain => "gmail.com",
:authentication => :login,
:user_name => "some_user#gmail.com",
:password => "abc123",
}
And here's the code in the mailer:
class UserMailer < ActionMailer::Base
default :from => "root#ubuntu"
def test_email
Rails.logger.debug 'test_email'
mail(:to => 'user#example.com', :subject => "testing rails")
end
end
The controller:
class PagesController < ApplicationController
def home
UserMailer.test_email
end
end
development.log:
[2012-03-01 18:26:45.859] DEBUG [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] test_email
[2012-03-01 18:26:45.888] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered user_mailer/test_email (1.6ms)
[2012-03-01 18:26:45.898] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Rendered pages/home.html.erb within layouts/application (1.1ms)
[2012-03-01 18:26:46.815] INFO [bb44dee806d73eb60ab3ae16297f5c02] [127.0.0.1] [GET] [http://myapp:3000/] Completed 200 OK in 455ms (Views: 112.4ms)
I also tried using the console:
root#ubuntu:/srv/www/myapp# rails c
Loading development environment (Rails 3.2.1)
irb(main):001:0> UserMailer.test_email
=> #<Mail::Message:32110400, Multipart: false, Headers: <To: user#example.com>, <Subject: testing rails>, <Mime-Version: 1.0>, <Content-Type: text/html>>
UserMailer.test_email
Just creates a Mail::Message object. To actually send an email you need to do
UserMailer.test_email.deliver
(or starting with rails 4.2 deliver_now / deliver_later)
Regarding logging errors:
Just figured out by tinkering that a bang method counterpart exists for deliver, which throws an exception. Can be pretty useful to check if you just misspelled your username or password, or you just have some misconfigured settings.
UserMailer.test_email.deliver!
An updated answer for Rails 4.2 would be:
UserMailer.test_email.deliver_now!
The exclamatory mark is to raise an exception if there are any errors.
If you suspect it's your settings, try taking out the :domain. It worked for me a while ago.( Net::SMTPAuthenticationError in rails 3.1.0.rc5 when connecting to gmail )
But I don't see a :body option in the mail function. Perhaps that's the issue. Try sending it from rails console and see what happens. http://api.rubyonrails.org/classes/ActionMailer/Base.html#method-i-mail

Resources