I am implementing LDAP authentication in laravel app. When I run this code I am getting an error.
I don't know whether it is correct or not. I am totally new to LDAP and I don't know how it works by seeing the documentation I have done till now.
Please help me out for setting the correct configuration settings for laravel-ldap.
Adldap \ Auth \ BindException (49)
Invalid credentials
protected function attemptLogin(Request $request)
{
$ldap = new Adldap;
$data = Adldap::users()->get();
dd($data);
}
the credential which I got from client
User Name: username
Password: password
IP:172.16.xx.xx
Port: 389
Attributes: CN=user.admin,CN=Users,DC=UATADSRV,DC=COM
my .env file
LDAP_HOSTS=172.16.xx.xx
LDAP_BASE_DN=CN=user.admin,CN=Users,DC=UATADSRV,DC=COM
LDAP_USER_ATTRIBUTE=samaccountname
LDAP_CONNECTION=default
LDAP_USERNAME=username
LDAP_PASSWORD=password
ldap.php
return [
'logging' => env('LDAP_LOGGING', false),
'connections' => [
'default' => [
'auto_connect' => env('LDAP_AUTO_CONNECT', true),
'connection' => Adldap\Connections\Ldap::class,
'settings' => [
'schema' => Adldap\Schemas\ActiveDirectory::class,
'account_prefix' => env('LDAP_ACCOUNT_PREFIX', ''),
'account_suffix' => env('LDAP_ACCOUNT_SUFFIX', ''),
'hosts' => explode(' ', env('LDAP_HOSTS', 'corp-dc1.corp.acme.org corp-dc2.corp.acme.org')),
'port' => env('LDAP_PORT', 389),
'timeout' => env('LDAP_TIMEOUT', 5),
'base_dn' => env('LDAP_BASE_DN', 'dc=corp,dc=acme,dc=org'),
'username' => env('LDAP_USERNAME'),
'password' => env('LDAP_PASSWORD'),
'follow_referrals' => false,
'use_ssl' => env('LDAP_USE_SSL', false),
'use_tls' => env('LDAP_USE_TLS', false),
],
],
],
];
ldap_auth.php
return [
'connection' => env('LDAP_CONNECTION', 'default'),
'provider' => Adldap\Laravel\Auth\DatabaseUserProvider::class,
'model' => App\User::class,
'rules' => [
Adldap\Laravel\Validation\Rules\DenyTrashed::class,
],
'scopes' => [
],
'identifiers' => [
'rules' => [
Adldap\Laravel\Validation\Rules\DenyTrashed::class,
],
'scopes' => [
],
'identifiers' => [
'ldap' => [
// 'locate_users_by' => 'userprincipalname',
'locate_users_by' => 'samaccountname',
'bind_users_by' => 'distinguishedname',
],
'database' => [
'guid_column' => 'objectguid',
'username_column' => 'username',
],
'windows' => [
'locate_users_by' => 'samaccountname',
'server_key' => 'AUTH_USER',
],
],
'passwords' => [
'sync' => env('LDAP_PASSWORD_SYNC', false),
'column' => 'password',
],
'login_fallback' => env('LDAP_LOGIN_FALLBACK', false),
'sync_attributes' => [
'email' => 'userprincipalname',
'username' => 'samaccountname',
'name' => 'cn',
],
'logging' => [
'enabled' => env('LDAP_LOGGING', true),
'events' => [
\Adldap\Laravel\Events\Importing::class => \Adldap\Laravel\Listeners\LogImport::class,
\Adldap\Laravel\Events\Synchronized::class => \Adldap\Laravel\Listeners\LogSynchronized::class,
\Adldap\Laravel\Events\Synchronizing::class => \Adldap\Laravel\Listeners\LogSynchronizing::class,
\Adldap\Laravel\Events\Authenticated::class => \Adldap\Laravel\Listeners\LogAuthenticated::class,
\Adldap\Laravel\Events\Authenticating::class => \Adldap\Laravel\Listeners\LogAuthentication::class,
\Adldap\Laravel\Events\AuthenticationFailed::class => \Adldap\Laravel\Listeners\LogAuthenticationFailure::class,
\Adldap\Laravel\Events\AuthenticationRejected::class => \Adldap\Laravel\Listeners\LogAuthenticationRejection::class,
\Adldap\Laravel\Events\AuthenticationSuccessful::class => \Adldap\Laravel\Listeners\LogAuthenticationSuccess::class,
\Adldap\Laravel\Events\DiscoveredWithCredentials::class => \Adldap\Laravel\Listeners\LogDiscovery::class,
\Adldap\Laravel\Events\AuthenticatedWithWindows::class => \Adldap\Laravel\Listeners\LogWindowsAuth::class,
\Adldap\Laravel\Events\AuthenticatedModelTrashed::class => \Adldap\Laravel\Listeners\LogTrashedModel::class,
],
],
];
Thank you
The LDAP server is saying that your provided credentials are wrong.
Are you sure, that your username and password is 100% correct? A space or any kind of invalid character?
CN=user.admin,CN=Users,DC=UATADSRV,DC=COM`
Also, is it working with ldap_bind() function?
Related
I'm install 2amigos/yii2-usuario:~1.5.1 on a yii2-basic-template, using https://yii2-usuario.readthedocs.io/en/latest/. However, it returns this error (Getting unknown property: Da\User\Module::isGuest yii2-usuario) in any view.
My config/console.php:
'components' => [
...
'authManager' => [
'class'=> 'yii\rbac\DbManager',
],
...
],
'controllerMap' => [
'migrate' => [
'class' => \yii\console\controllers\MigrateController::class,
'migrationPath' => [
'#app/migrations',
'#yii/rbac/migrations', // Just in case you forgot to run it on console (see next note)
],
'migrationNamespaces' => [
'Da\User\Migration',
],
],
],
My config/web.php:
'components' => [
...
'user' => [
'class' => Da\User\Module::class,
'classMap' => [
'User' => app\models\User::class,
],
],
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'view' => [
'theme' => [
'pathMap' => [
'#Da/User/resources/views' => '#app/views/user'
]
]
]
],
I managed to solve it with help.
Follow the line:
Remove : config/web.php
'user' => [
'identityClass' => 'app\models\Users',
'enableAutoLogin' => true,
'enableSession' => true,
],
'user-management' => [
'class' => 'webvimark\modules\UserManagement\UserManagementModule',
'on beforeAction'=>function(yii\base\ActionEvent $event) {
if ( $event->action->uniqueId == 'user-management/auth/login' ){
$event->action->controller->layout = 'loginLayout.php';
};
},
],
add into config/web.php:
'components' =>[ ...
'authManager' => [
'class' => 'yii\rbac\DbManager',
],
'view' => ['theme' => [ 'pathMap' => ['#Da/User/resources/views' => '#app/views/user']]] //If your view is modified.
]
'modules' => ['user' => [
'class' => \Da\User\Module::class,
'allowAccountDelete' => true,
'enableRegistration' => false,
'administratorPermissionName' => 'user-management']
...]
``
I am having the following problem, I need to create a custom logger for my application, the code is as follows:
config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['slack', 'logentries', 'custom'],
],
'logentries' => [
'driver' => 'monolog',
'level' => 'info',
'handler' => Monolog\Handler\SyslogUdpHandler::class,
'handler_with' => [
'host' => 'us.data.logs.insight.rapid7.com',
'port' => '14211',
],
],
'custom' => [
'driver' => 'custom',
'via' => App\Logging\MongoLogger::class,
'level' => 'debug',
'formatter' => 'default',
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => 'debug',
'days' => 7,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => 'critical',
],
'syslog' => [
'driver' => 'syslog',
'level' => 'debug',
],
'errorlog' => [
'driver' => 'errorlog',
'level' => 'debug',
],
],
AfterMiddleWare.php
$record = array(
'tipo' => 'debug',
'url' => Request::url(),
'message' => (string)'acesso_sistema',
'datahora' => \Carbon\Carbon::now(),
'session_id' => Session::getId(),
'level' => 'access_log',
'so' => BrowserDetect::platformName(),
'mobile' => BrowserDetect::isMobile(),
'tempo_execucao' => (!empty($context['tempo_execucao'])) ? $context['tempo_execucao'] : 0,
'dia_mes_ano' => date('d/m/Y'),
'usuario' => $this->getUsuario(),
'cliente' => Session::get('cliente'),
'ip_origem' => Request::ip()
);
if(empty($record['datetime'])) {
$record['datetime'] = $ts;
}
Log::debug(json_encode($record));
return $response;
And the custom logger
MongoLogger.php
<?php
namespace App\Logging;
use Monolog\Handler\MongoDBHandler;
use MongoDB\Client;
use Monolog\Logger;
class MongoLogger
{
/**
* Customize the given logger instance.
*
* #param \Illuminate\Log\Logger $logger
* #return void
*/
public function __invoke($config)
{
die(print_r($config));
$log = new Logger('debug');
try {
$log->pushHandler(new MongoDBHandler(new Client('mongodb://' . config('database.connections.mongodb.host') . ':' . config('database.connections.mongodb.port')), config('database.connections.mongodb.database'), 'logs', 'DEBUG'));
} catch (\MongoConnectionException $e) {
throw new \Exception('Cannot connect to Mongo - please check your server');
}
return $log;
}
}
I want the following to pass an additional parameter to the mongologger which would be the collection where I will insert the data;
For example
Log::debug(json_encode($record) , 'MYCOLLECTION'`
but I'm not able to pass this parameter, how can I do this?
thanks for helping
I want to protect my REST API by using an oauth2 authentication. I'm using bshaffer/oauth2-server-php in combination with zend 3.
I've the following config:
// autoload/oauth2.global.php
return [
'zf-oauth2' => [
'db' => [
'dsn' => sprintf(
'mysql:dbname=%s;host=%s',
false !== getenv('DB_NAME') ? getenv('DB_NAME') : '',
false !== getenv('DB_HOST') ? getenv('DB_HOST') : ''
),
'username' => false !== getenv('DB_USER') ? getenv('DB_USER') : '',
'password' => false !== getenv('DB_PASS') ? getenv('DB_PASS') : '',
],
'storage' => MyApp\OAuth2Module\Adapter\PdoAdapter::class,
'enforce_state' => true,
'allow_implicit' => true,
'access_lifetime' => 3600,
'api_problem_error_response' => false,
'options' => [
'use_jwt_access_tokens' => false,
'store_encrypted_token_string' => true,
'use_openid_connect' => false,
'id_lifetime' => 3600,
'www_realm' => 'Service',
'token_param_name' => 'access_token',
'token_bearer_header_name' => 'Bearer',
'require_exact_redirect_uri' => true,
'allow_public_clients' => true,
'allow_credentials_in_request_body' => true,
'always_issue_new_refresh_token' => false,
'refresh_token_lifetime' => 1209600,
],
],
];
And my auth route looks like this:
// autoload/router.global.php
return [
'router' => [
'routes' => [
'api' => [
'type' => Literal::class,
'options' => [
'route' => '/api',
],
'may_terminate' => false,
'child_routes' => [
'rest' => [
'type' => Literal::class,
'options' => [
'route' => '/rest',
],
'may_terminate' => false,
'child_routes' => [
'oauth' => [
'type' => Literal::class,
'options' => [
'route' => '/oauth',
'defaults' => [
'controller' => 'ZF\OAuth2\Controller\Auth',
'action' => 'token',
],
],
],
],
],
],
],
],
],
];
Everything works fine so far. I can post my client credentials to the oauth endpoint and get an access token.
But how can I protect the other endpoints? F.e. I make a GET request to /api/rest/myapp/GetList. The list of my entities should only be retrieved if the user also sends the authorization bearer with the request but I can't find a solution for this. Is it possible to set a parameter (something like "require_token") in the route config to "activate" this behavior? Or what is the correct way to protect my REST API?
There's no build-in system to make this. You will create a listener which's listens MvcEvent::Event_ROUTE and place it after router then check if there's a routematch. If there's one, check if it's protected route. If it's apply authentication logic.
I am trying to configure rbac with phpmanager in my project using the Yii2 advance app version. But \Yii::$app->user->can is not returning the expected.
I wrote the RbacController and executed sucessfully yii rbac/init
That updated common/components/items.php as shown
<?php
return [
'user' => [ 'type' => 1, 'children' => [ 'createX', ], ],
'createX' => [ 'type' => 2, 'description' => 'create a X',],
'admin' => [ 'type' => 1, 'children' => [ 'updateX', ], ],
'updateX => [ 'type' => 2, 'description' => 'update a X', ],
];
In SignupForm::signup, I added it:
$auth = Yii::$app->authManager;
$roleObj = $auth->getRole('user'); // this role is defined by the RBAC Controller's init action
$auth->assign($roleObj, $user->getId());
assignments.php
return [ 2 => [ 'user', ], ];
I think that 2 corresponds to the user id.
rules.php
return [];
common/main.php
...
'components' => [
...
'authManager' => [
'class' => 'yii\rbac\PhpManager',
'defaultRoles' => ['user','admin'],
'itemFile' => '#common/components/rbac/items.php',
'assignmentFile' => '#common/components/rbac/assignments.php',
'ruleFile' => '#common/components/rbac/rules.php'
],
],
...
When I got that role permissions, it prints:
Array ( [createX] => yii\rbac\Permission Object ( [type] => 2 [name] => createX [description] => create a X [ruleName] => [data] => [createdAt] => 1438601819 [updatedAt] => 1438601819 ) )
So I'm expecting that user doesn't have updating permission, but in the method XController::update
echo \Yii::$app->user->can('updateX');
// returns 1, just the same than \Yii::$app->user->can('createX') returning
Please some help
First items file should be:
<?php
return [
'user' => [ 'type' => 1, 'children' => [ 'createX', ], ],
'createX' => [ 'type' => 2, 'description' => [ 'create a X', ], ],
'admin' => [ 'type' => 1, 'children' => [ 'updateX', ], ],
'updateX' => [ 'type' => 2, 'description' => ['update a X', ], ],
];
You can verify if the code is fine with var_dump:
var_dump(\Yii::$app->authManager);
I am currently trying to install a Yii2 extension for implementing an OAuth2 server (https://github.com/Filsh/yii2-oauth2-server). However, I keep running on the error below:
Does anyone have an idea on how to install this extension. I followed the instructions given but there was no mention about that error.
Satya is right. You need to configure oauth2 module as described on repo's description:
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'options' => [
'token_param_name' => 'accessToken',
'access_lifetime' => 3600 * 24
],
'storageMap' => [
'user_credentials' => 'common\models\User'
],
'grantTypes' => [
'client_credentials' => [
'class' => 'OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials'
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
],
]
I've configured this extension successfully and created Yii2 Rest API template with OAuth2 server https://github.com/ikaras/yii2-oauth2-rest-template - feel free to use. Also this code has some demo data (examples of using) and support of scopes for controllers.
Add give 'oauth2' configuration in 'modules' section of config/main.php.
It may work
Use this configuration under your confin/main.php file under modules section.
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'token',
'tokenAccessLifetime' => '100800', // Expiry Time
'storageMap' => [
'user_credentials' => 'common\models\User', // This Should be your model name
],
'grantTypes' => [
'client_credentials' => [
'class' => 'OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false,
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true,
'refresh_token_lifetime' => '100800',
],
],
];
Found solution my-self on scope issue, maybe it will be useful for someone - marked with ** in config:
'modules' => [
'oauth2' => [
'class' => 'filsh\yii2\oauth2server\Module',
'tokenParamName' => 'accessToken',
'tokenAccessLifetime' => 3600 * 24,
'storageMap' => [
'client_credentials' => 'app\models\User',
'user_credentials' => 'app\models\User',
**'scope' => 'app\models\User',**
],
'grantTypes' => [
'client_credentials' => [
'class' => '\OAuth2\GrantType\ClientCredentials',
'allow_public_clients' => false,
'always_issue_new_refresh_token' => true
],
'user_credentials' => [
'class' => 'OAuth2\GrantType\UserCredentials',
],
'refresh_token' => [
'class' => 'OAuth2\GrantType\RefreshToken',
'always_issue_new_refresh_token' => true
]
]
]
],