LDAP: Not authorized because not authenticated - ruby-on-rails

I have following login credential
EMAIL=xxxx#gmail.com and PASSWORD=test1234
and above credential is correct.
But while login, I am getting following error
LDAP: LDAP dn lookup: cn=xxxx#gmail.com
LDAP: LDAP search for login: cn=xxxx#gmail.com
LDAP: LDAP search yielded 0 matches
LDAP: Authorizing user cn=xxxx#gmail.com,ou=people,dc=test,dc=com
LDAP: Not authorized because not authenticated.
Completed 401 Unauthorized in 9ms
This is my configuration
For ldap.yml
authorizations: &AUTHORIZATIONS
allow_unauthenticated_bind: false
group_base: ou=groups,dc=test,dc=com
## Requires config.ldap_check_group_membership in devise.rb be true
# Can have multiple values, must match all to be authorized
required_groups:
# If only a group name is given, membership will be checked against "uniqueMember"
- cn=admins,ou=groups,dc=test,dc=com
- cn=users,ou=groups,dc=test,dc=com
# If an array is given, the first element will be the attribute to check against, the second the group name
- ["moreMembers", "cn=users,ou=groups,dc=test,dc=com"]
## Requires config.ldap_check_attributes in devise.rb to be true
## Can have multiple attributes and values, must match all to be authorized
require_attribute:
objectClass: inetOrgPerson
authorizationRole: postsAdmin
## Environment
development:
host: localhost
port: 389
attribute: cn
base: ou=people,dc=test,dc=com
admin_user: cn=admin,dc=test,dc=com
admin_password: admin_password
ssl: false
# <<: *AUTHORIZATIONS
and for device.rb
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> LDAP Configuration
# config.ldap_logger = true
config.ldap_create_user = true
# config.ldap_update_password = true
config.ldap_config = "#{Rails.root}/config/ldap.yml"
config.ldap_check_group_membership = true
# 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 = true
config.mailer_sender = 'please-change-me-at-config-initializers-devise#example.com'
require 'devise/orm/active_record'
config.case_insensitive_keys = [:email]
config.strip_whitespace_keys = [:email]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true
config.expire_all_remember_me_on_sign_out = true
config.password_length = 8..72
config.reset_password_within = 6.hours
config.sign_out_via = :delete
end
What wrong in above code? Please help me.

Related

Rails reset password email is not triggering

I know this was repeated question that was posted by may other people. I have tired of tried with different solution, but noting works for me. I have integrated Devise with my application. For reset password I am using default Devise methods. So when I try to reset my password, the Devise::Mailer#reset_password_instructions: processed outbound mail is executing from console but I didn't receive email from the application.
This is the email set configured with the application config/initializers/setup_mailer.rb
ActionMailer::Base.smtp_settings = {
:address => "smpt.gmail.com",
:port => "587",
:domain => "ipaddress",
:user_name => "*****",
:password => "*****",
:authentication => "plain",
:enable_starttls_auto => true
}
Output from console
Devise::Mailer#reset_password_instructions: processed outbound mail in 10.4ms
Sent mail to sethunagakarthi.m#irco.com (4.3ms)
Date: Fri, 27 Apr 2018 11:11:34 +0530
From: PyraMIDtool#irco.com
Reply-To: PyraMIDtool#irco.com
To: sethunagakarthi.m#irco.com
Message-ID: <5ae2b80e7e502_34142b2a9a15f8fc349e3#iradmin-OptiPlex-3040.mail>
Subject: Reset password instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Hello sethunagakarthi.m#irco.com!</p>
<p>Someone has requested a link to change your password. You can do this through the link below.</p>
<p>Change my password</p>
<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>
Redirected to http://localhost:3000/users/sign_in
Completed 302 Found in 322ms (ActiveRecord: 285.2ms)
devise.rb
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
# Devise will use the `secret_key_base` as its `secret_key`
# by default. You can change it below and use your own secret key.
# config.secret_key = '94b46ce945cf69c1b34d34da55436d8020a2f43490728cc999076ff34e963a446e8513e2c353c6eb50c2963aeaa2560b1f292171f0bacba88070c104c2551815'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'PyraMIDtool#irco.com'
# Configure the class responsible to send e-mails.
config.mailer = 'Devise::Mailer'
# Configure the parent class responsible to send e-mails.
# config.parent_mailer = 'ActionMailer::Base'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [:corp_id]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [:email]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [:email]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If 401 status code should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# When false, Devise will not attempt to reload routes on eager load.
# This can reduce the time taken to boot the app but if your application
# requires the Devise mappings to be loaded during boot time the application
# won't boot properly.
# config.reload_routes = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 11. If
# using other algorithms, it sets how many times you want the password to be hashed.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# algorithm), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 11
# Set up a pepper to generate the hashed password.
# config.pepper = 'd937edcd8ba852daed548479e1a6ac22d6c7aefebacc316e0236e2362421b1258dc40d36a1766fda4f9db96bc9ea4b53cc43d6178b1b3f2b6e089588f724811d'
# Send a notification to the original email when the user's email is changed.
# config.send_email_changed_notification = false
# Send a notification email when the user's password is changed.
# config.send_password_change_notification = false
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [:email]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# Invalidates all the remember me tokens when the user signs out.
config.expire_all_remember_me_on_sign_out = true
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 6..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
config.email_regexp = /\A[^#\s]+#[^#\s]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [:email]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = true
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
config.reset_password_keys = [:email]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# When set to false, does not sign a user in automatically after their password is
# reset. Defaults to true, so a user is signed in automatically after a reset.
# config.sign_in_after_reset_password = true
# ==> Configuration for :encryptable
# Allow you to use another hashing or encryption algorithm besides bcrypt (default).
# You can use :sha1, :sha512 or algorithms from others authentication tools as
# :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
# for default behavior) and :restful_authentication_sha1 (then you should set
# stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
config.scoped_views = true
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using OmniAuth, Devise cannot automatically set OmniAuth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end
This is my environment/development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# SMTP setting for email
config.action_mailer.delivery_method = :smtp
# SMTP settings for gmail
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:user_name => "*******",
:password => "*******",
:authentication => "plain",
:enable_starttls_auto => true
}
ENV["APPLICATION_URL"] = "http://localhost:3000"
ENV["IP_ADDRESSS"] = "10.200.102.74"
ENV["USER_NAME"] = "*****"
ENV["PASSWORD"] = "*****"
ENV["JENKINS_USERNAME"] = "******"
ENV["JENKINS_PASSWORD"] = "******"
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
I would be grateful to you if some help me to escape from this problem.
Can you try this? Put it in your environments/development.rb file
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: "smtp.gmail.com",
port: 587,
domain: "gmail.com",
authentication: "plain",
enable_starttls_auto: true,
user_name: username#gmail.com,
password: yourPass
}
Just change the following line in your development.rb
config.action_mailer.raise_delivery_errors = true
Now you are able to see the errors for mailer.

rails devise ldap_authentication cannot find user

I am trying to use thise gem according base documentation (https://github.com/cschiewek/devise_ldap_authenticatable)
this is my devise.rb config
# ==> LDAP Configuration
config.ldap_logger = true
config.ldap_create_user = true
config.ldap_config = "#{Rails.root}/config/ldap.yml"
and this is my ldap.yml
authorizations: &AUTHORIZATIONS
allow_unauthenticated_bind: true
group_base: ou=groups,dc=test,dc=com
## Requires config.ldap_check_group_membership in devise.rb be true
# Can have multiple values, must match all to be authorized
required_groups:
# If only a group name is given, membership will be checked against "uniqueMember"
- cn=admins,ou=groups,dc=test,dc=com
- cn=users,ou=groups,dc=test,dc=com
# If an array is given, the first element will be the attribute to check against, the second the group name
- ["moreMembers", "cn=users,ou=groups,dc=test,dc=com"]
## Requires config.ldap_check_attributes in devise.rb to be true
## Can have multiple attributes and values, must match all to be authorized
require_attribute:
objectClass: inetOrgPerson
authorizationRole: postsAdmin
## Environment
development:
host: myACtiveDirectory.server
port: 389
attribute: userPrincipalName
base: dc=mycompanydomain,dc=com
admin_user: cn=admin,dc=test,dc=com
admin_password: admin_password
ssl: false
# <<: *AUTHORIZATIONS
when I try to login, what I want to achieve is login with email and pass and if user is not present in local DB, create record.
In logs I see that LDAP cannot find user according userPrincipalName and it is always twice (is it trying twice before it fails?)
LDAP: LDAP dn lookup: userPrincipalName=mirob#mycompanydomain.com
LDAP: LDAP search for login: userPrincipalName=mirob#mycompanydomain.com
LDAP: LDAP search yielded 0 matches
LDAP: Authorizing user userPrincipalName=mirob#mycompanydomain.com,dc=mycompanydomain,dc=com
LDAP: Not authorized because not authenticated.
LDAP: LDAP dn lookup: userPrincipalName=mirob#mycompanydomain.com
LDAP: LDAP search for login: userPrincipalName=mirob#mycompanydomain.com
LDAP: LDAP search yielded 0 matches
LDAP: Authorizing user userPrincipalName=mirob#mycompanydomain.com,dc=mycompanydomain,dc=com
LDAP: Not authorized because not authenticated.
When I use script from this question to test (I changed sAMAccountName to principal name and I dont merge username with domain) I can login to LDAP so connection is working
Ldap is not working with Devise
any idea what is wrong with my devise ldap setup?
EDIT:
ok I found that ldap_authenticable is searching for DN what in my case (Active Directory setup) is CN=Complete Name,CN=Users,CN=mydomain,CN=com
The question is how can I search for email instead of Complete Name as I cant update AD for all users to put email into name field?
ok I found this answer and it helped me
Correct configuration for devise_ldap_authenticatable
I just needed to add this line to devise.rb and I can simple authenticate according to userPrincipalName
config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| login}

Devise not authenticating with LDAP

I'm using Devise 3.5.2 for authentication with the devise_ldap_authenticable gem on Rails 4.2.4. I've moved from the released 0.8.5 gem to the github master level (0.8.6).
From what I can tell, the LDAP plugin authentication code is not running. It's not writing any log messages.
I previously got regular database authentication to work for this application. I'm now trying to get LDAP authentication to work.
For example:
Started POST "/users/sign_in" for ::1 at 2015-11-23 16:05:14 -0500
ActiveRecord::SchemaMigration Load (87.6ms) SELECT schema_migrations.* FROM schema_migrations
Processing by Devise::SessionsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Mos...w==", "user"=>{"login"=>"leonsp", "password"=>"...", "remember_me"=>"0"}}
Completed 401 Unauthorized in 95ms (ActiveRecord: 0.0ms)
There should be LDAP log messages in there.
My user model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
#
# :database_authenticable is not enabled
devise :ldap_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :zxcvbnable
attr_accessible :email, :userid, :shortuserid, :login # etc...
# Virtual attribute for authenticating by either userid or email
# This is in addition to a real persisted field like 'userid'
attr_accessor :login
# ...
def self.find_for_database_authentication(warden_conditions)
Rails.logger.debug "Finding for database authentication"
conditions = warden_conditions.dup
login = conditions.delete(:login).try(:downcase)
if login.present?
Rails.logger.debug "Finding by login #{login}"
where(conditions.to_hash).find_by([
"lower(userid) = :value OR lower(shortuserid) = :value OR lower(email) = :value", { value: login }
])
else
Rails.logger.debug "Finding by conditions #{login}"
find_by(conditions.to_hash)
end
end
def self.find_for_ldap_authentication(warden_conditions)
Rails.logger.debug "Finding for ldap authentication"
conditions = warden_conditions.dup
login = conditions.delete(:login).try(:downcase)
if login.present?
Rails.logger.debug "Finding by login #{login}"
if login.include? "#"
conditions[:email] = login
super conditions
else
conditions[:userid] = login
super conditions
end
else
Rails.logger.debug "No login. Using default behaviour"
super
end
end
# ...
Here's the initializer for Devise. I added the monkeypatch at the front while debugging:
module Devise
module Strategies
class LdapAuthenticatable < Authenticatable
def authenticate!
Rails.logger.debug "=== Starting LDAP Authentication ==="
super
Rails.logger.debug "=== Done LDAP Authentication ==="
end
end
end
end
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# TODO: https://github.com/cschiewek/devise_ldap_authenticatable/issues/153
# ==> 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 = false
# config.ldap_use_admin_to_bind = false
# config.ldap_ad_group_check = false
config.ldap_logger = true
config.ldap_create_user = true
config.ldap_update_password = true
config.ldap_use_admin_to_bind = true
config.ldap_auth_username_builder = proc do |attribute, login, ldap|
username_string = "#{attribute}=#{login},#{ldap.base}"
Rails.logger.debug "Generated username as #{username_string}"
username_string
end
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [:login, :email, :userid]
# ...
I can successfully connect to the LDAP server on the machine using ldapsearch:
ldapsearch -x -W -D "cn=admin,dc=my_domain,dc=com" -H ldap://my_hostname.my_domain.com "(cn=leonsp)"
Here's the corresponding configuration the ldap.yml:
## Authorizations
# Uncomment out the merging for each environment that you'd like to include.
# You can also just copy and paste the tree (do not include the "authorizations") to each
# environment if you need something different per environment.
authorizations: &AUTHORIZATIONS
allow_unauthenticated_bind: false
group_base: ou=groups,dc=my_domain,dc=com
## Requires config.ldap_check_group_membership in devise.rb be true
# Can have multiple values, must match all to be authorized
required_groups:
## Requires config.ldap_check_attributes in devise.rb to be true
## Can have multiple attributes and values, must match all to be authorized
require_attribute:
objectClass: inetOrgPerson
## Environment
development:
host: ldap://my_hostname.my_domain.com
port: 389
attribute: cn
base: dc=my_domain,dc=com
admin_user: cn=admin,dc=my_domain,dc=com
admin_password: ...
ssl: none
# <<: *AUTHORIZATIONS
Am I correct in assuming that the LDAP plugin code for Devise is not running?
Why isn't it running?
Why aren't any of my debug statements being reached?
What additional methods can I monkeypatch with debug statements to debug the issue?
What other diagnostics can I collect?
Edit: I'm tracing the execution using the byebug debugger. So far I can tell that :ldap_authenticable shows up on the list of strategies during sign in, but doesn't seem to result in any :ldap_authenticable-specific code execution.
The main issue was that I had included optional parameters in config.authentication_keys. This made Devise::Strategies#parse_authentication_key_values fail silently. Only mandatory parameters should be included in authentication_keys.
Other issues related to the application being designed to allow users to log in with either their username or their email address. To allow for users to log in using either, I had to:
Override login_with in the User model
Override self.find_for_ldap_authentication in the User model
Rename the fake attr_accessor :login to attr_accessor :username in order to better distinguish it from the different meaning of :login in the gem
One last issue: Don't include protocol (e.g. ldaps://) in the host attributes of ldap.yml
For those coming to this thread still, I was able to get it to work by dropping down to gem version 0.8.4.

Setting Up Sendgrid and Devise Hosted on a VPS Not Heroku

I have browsed a lot of devise/sendgrid setup on stackoverflow. They are all geared toward the heroku platform.
I have this in my environment.rb (hard coded for now)
ActionMailer::Base.smtp_settings = {
:user_name => 'username',
:password => 'password',
:domain => 'localhost:3000',
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:enable_starttls_auto => true
}
here is a part of my development.rb file
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {:address => "localhost", :port => 587}
config.action_mailer.default_url_options = { :host => 'localhost' }
config.action_mailer.perform_deliveries = true
config.action_mailer.default :charset => "utf-8"
I am just trying to get this to work in my development right now. I have devise sign up and login in or set up on my rails application.
I am trying to set up email confirmation and mainly password recovery emails. When I click for password recover emails I am getting this
Sent mail to firstlevelservice#gmail.com (1114.3ms)
Date: Sun, 15 Sep 2013 21:33:39 -0400
From: mail-to-send#from.com
Reply-To: mail-to-send#from.com
To: firstlevelservice#gmail.com
Message-ID: <52365ff371eca_23863fc416f25a5c865dd#Judys-MacBook-Air.local.mail>
Subject: Reset password instructions
Mime-Version: 1.0
Content-Type: text/html;
charset=UTF-8
Content-Transfer-Encoding: 7bit
<p>Hello firstlevelservice#gmail.com!</p>
<p>Someone has requested a link to change your password. You can do this through the link below.</p>
<p>Change my password</p>
<p>If you didn't request this, please ignore this email.</p>
<p>Your password won't change until you access the link above and create a new one.</p>
Redirected to http://localhost:3000/students/sign_in
Completed 302 Found in 1232ms (ActiveRecord: 5.9ms)
in my shell but the problem is I am not getting the email?
here is my devise.rb in my initializers folder if this help
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "mail-to-send#from.com"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "98e88df3de451cbf43f596fc0770a5b77e7224d2369a2d66096cba063776ed81401b04053721e435f9faabdc49096a8ce36a678dcb0e385e9993d803943cd105"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) # exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^#]+#[^#]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
end
In sendgrid I do see an email got sent.... but I am just not receive these emails in my inbox, the test email is mine.

Rails Devise LDAP Error: NoMethodError in Devise::SessionsController#create

My team has setup my ruby on rails app to work with devise ldap. Whenever a user logs in for the first time, it creates a new entry in the Users model and works completely fine. But whenever a user that already exist in the Users database tries to login it gives the following error:
NoMethodError in Devise::SessionsController#create
undefined method `to' for nil:NilClass
From looking at the server console, it seems like it is failing on this SQL statement:
SELECT `users`.* FROM `users` WHERE `users`.`username` = 'jDoe' LIMIT 1
I think the server is getting no results from that query.
But whenever I run that same sql statement in the ruby console, it gives the correct result (the record of the user attempting to login)
Here are some of my devise configs. I am new to devise and ruby (and I also didn't install the devise) so let me know if you need other config files to debug this problem.
initializers/devise.rb
Devise.setup do |config|
config.ldap_create_user = true
config.ldap_update_password = false
config.mailer_sender = "****"
require 'devise/orm/active_record'
config.authentication_keys = [ :username ]
config.case_insensitive_keys = [ :email ]
config.strip_whitespace_keys = [ :email ]
config.skip_session_storage = [:http_auth]
config.stretches = Rails.env.test? ? 1 : 10
config.reconfirmable = true
config.password_length = 8..128
config.sign_out_via = :delete
end
ldap.yml
authorizations: &AUTHORIZATIONS
group_base: ou=groups,dc=test,dc=com
required_groups:
- cn=admins,ou=groups,dc=test,dc=com
- cn=users,ou=groups,dc=test,dc=com
- ["moreMembers", "cn=users,ou=groups,dc=test,dc=com"]
require_attribute:
objectClass: inetOrgPerson
authorizationRole: postsAdmin
development:
host: ****
port: 636
attribute: uid
base: ou=People,dc=***,dc=com
admin_user: cn=admin,dc=test,dc=com
admin_password: admin_password
ssl: true
test:
host: localhost
port: 3389
attribute: cn
base: ou=people,dc=test,dc=com
admin_user: cn=admin,dc=test,dc=com
admin_password: admin_password
ssl: simple_tls
production:
host: localhost
port: 636
attribute: cn
base: ou=people,dc=test,dc=com
admin_user: cn=admin,dc=test,dc=com
admin_password: admin_password
ssl: start_tls
user.rb
class User < ActiveRecord::Base
devise :ldap_authenticatable, :rememberable, :trackable
attr_accessible :name, :cell, :email, :pref, :type, :username, :password, :password_confirmation, :remember_me
end
My problem happened because I had 2 tables that inherited from User (Client, and Runner) and they both tried to authenticate with the same ldap. When I took out the single table inheritance everything worked fine.

Resources