Rectangle 27 88

I disagree with your conclusion that the connect-auth plugin is the wa...

I guess the reason that you haven't found many good libraries is that using a library for authentication is mostly over engineered.

What you are looking for is just a session-binder :) A session with:

if login and user == xxx and pwd == xxx 
   then store an authenticated=true into the session 
if logout destroy session

I'm using also connect but I do not use connect-auth for two reasons:

(It's complete. Just execute it for testing but if you want to use it in production, make sure to use https) (And to be REST-Principle-Compliant you should use a POST-Request instead of a GET-Request b/c you change a state :)

var connect = require('connect');
var urlparser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlparser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this example with your Database, Auth-File or other things
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // This user is not authorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are not authorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);

I wrote this statement over a year ago and have currently no active node projects. So there are may be API-Changes in Express. Please add a comment if I should change anything.

Why does connect-auth break the onion/layers pattern? is it because it doesn't use next()? Could it?

Yes. It must use next() because thats the idea behind connect. Connect has a layer-architecture / form of code structure. And every layer has the power to stop the request execution by not calling next(). If we are talking about authentication: An authentication layer will check if the user has the correct permissions. If everything is fine the layer calls next(). If not this auth-layer generates an error and will not call next().

man, this is exactly what I was looking for. connect-auth was giving me a bit of indigestion. I just logged into my app for the first time. thanks so much.

This still doesn't help to answer how to connect to a database backend (preferably with encrypted passwords). I appreciate your comment that this one library is over-engineered, but surely there is one that isn't. Also, if I wanted to write my own auth system I would have used Struts in Java. just like the OP, I want to know which plugins will do that for me in 1 line of code.

great answer Nivoc. Doesn't work with latest versions of connect tho. I had to change... cookieDecoder() --> cookieParser() and bodyDecoder() --> bodyParser() and remove the next() call from helloWorldContent function as i was getting an error 'Can't set headers after they are sent'

user authentication libraries for node.js? - Stack Overflow

authentication node.js serverside-javascript
Rectangle 27 88

I disagree with your conclusion that the connect-auth plugin is the wa...

I guess the reason that you haven't found many good libraries is that using a library for authentication is mostly over engineered.

What you are looking for is just a session-binder :) A session with:

if login and user == xxx and pwd == xxx 
   then store an authenticated=true into the session 
if logout destroy session

I'm using also connect but I do not use connect-auth for two reasons:

(It's complete. Just execute it for testing but if you want to use it in production, make sure to use https) (And to be REST-Principle-Compliant you should use a POST-Request instead of a GET-Request b/c you change a state :)

var connect = require('connect');
var urlparser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlparser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this example with your Database, Auth-File or other things
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // This user is not authorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are not authorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);

I wrote this statement over a year ago and have currently no active node projects. So there are may be API-Changes in Express. Please add a comment if I should change anything.

Why does connect-auth break the onion/layers pattern? is it because it doesn't use next()? Could it?

Yes. It must use next() because thats the idea behind connect. Connect has a layer-architecture / form of code structure. And every layer has the power to stop the request execution by not calling next(). If we are talking about authentication: An authentication layer will check if the user has the correct permissions. If everything is fine the layer calls next(). If not this auth-layer generates an error and will not call next().

man, this is exactly what I was looking for. connect-auth was giving me a bit of indigestion. I just logged into my app for the first time. thanks so much.

This still doesn't help to answer how to connect to a database backend (preferably with encrypted passwords). I appreciate your comment that this one library is over-engineered, but surely there is one that isn't. Also, if I wanted to write my own auth system I would have used Struts in Java. just like the OP, I want to know which plugins will do that for me in 1 line of code.

great answer Nivoc. Doesn't work with latest versions of connect tho. I had to change... cookieDecoder() --> cookieParser() and bodyDecoder() --> bodyParser() and remove the next() call from helloWorldContent function as i was getting an error 'Can't set headers after they are sent'

user authentication libraries for node.js? - Stack Overflow

authentication node.js serverside-javascript
Rectangle 27 6

A very simple authentication with connect

I wouldn't use/fork Connect-Auth. This plugin of connect breaks the onion ring idea/architecture of connect and makes (IMHO) your code unreadable/brings unnecessary complexity.

Authentification is too simple for a library. (If you a talking about a simple user login)

I'm using a self written auth. You can find a simplified version below. It also depends on session-cookies but it can easily be replaced with persistant cookies.

var connect = require('connect');
var urlpaser = require('url');

var authCheck = function (req, res, next) {
    url = req.urlp = urlpaser.parse(req.url, true);

    // ####
    // Logout
    if ( url.pathname == "/logout" ) {
      req.session.destroy();
    }

    // ####
    // Is User already validated?
    if (req.session && req.session.auth == true) {
      next(); // stop here and pass to the next onion ring of connect
      return;
    }

    // ########
    // Auth - Replace this simple if with you Database or File or Whatever...
    // If Database, you need a Async callback...
    if ( url.pathname == "/login" && 
         url.query.name == "max" && 
         url.query.pwd == "herewego"  ) {
      req.session.auth = true;
      next();
      return;
    }

    // ####
    // User is not unauthorized. Stop talking to him.
    res.writeHead(403);
    res.end('Sorry you are unauthorized.\n\nFor a login use: /login?name=max&pwd=herewego');
    return;
}

var helloWorldContent = function (req, res, next) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('authorized. Walk around :) or use /logout to leave\n\nYou are currently at '+req.urlp.pathname);
}

var server = connect.createServer(
      connect.logger({ format: ':method :url' }),
      connect.cookieParser(),
      connect.session({ secret: 'foobar' }),
      connect.bodyParser(),
      authCheck,
      helloWorldContent
);

server.listen(3000);

Thanks! Can you elaborate on what you mean by connect-auth breaking the onion ring arch?

Yes. I explained it at > here already. (Follow the link to the article "Basics of connect")

authentication - Persistant Login with connect-auth - Stack Overflow

authentication node.js
Rectangle 27 18

That is probably because your script is running under some other user than the one you are trying to connect with (myuser here). In this case, peer authentication will fail. Your solution with HOST: "localhost" works because you are not using peer auth anymore. However, it is slower than HOST: "" because instead of using unix sockets, you use TCP connections. From django docs:

If youre using PostgreSQL, by default (empty HOST), the connection to the database is done through UNIX domain sockets (local lines in pg_hba.conf). If you want to connect through TCP sockets, set HOST to localhost or 127.0.0.1 (host lines in pg_hba.conf). On Windows, you should always define HOST, as UNIX domain sockets are not available.

If you want to keep using sockets, correct settings in pg_hba.conf are needed. The most simple is:

local   all         all                               trust

while commenting out all other local lines in the config. Note that reloading postgres is needed for this change to take effect.

But if multi-user production machine is in question, you might want to use something more secure like md5 (see here for explanation of various authentication methods).

Django connection to PostgreSQL: "Peer authentication failed" - Stack ...

django postgresql
Rectangle 27 1

I don't think this looks right, because I don't think you should ever store passwords in your database. Especially when you ask such questions on Stackoverflow(I don't even recommend myself to store passwords inside my database, although I did a lot of research on this topic, but I still don't consider myself a security expert). I always recommend people to use OpenID(or Facebook Connect) instead. It is very simple to implement, secure. Most users already have an OpenID like for example Google openID or Yahoo! openID. I have a demo available at my hosting provider(simple) at location http://westerveld.name/php-openid/. When you implement OpenID you don't need to worry about authentication at all. I have this code available at github. You could just simply clone code and get started => https://github.com/alfredwesterveld/php-openid

But If you really want to store passwords yourself I would advice you to look into phpass. It supports the most secure hashing method OpenBSD-style Blowfish-based bcrypt which is Moore's law proof. I made a simple library wrapping phpass also available at github, although I don't advice you to use this => https://github.com/alfredwesterveld/php-auth

-1 for the "never store pwds in a db" (OpenID is a confusing failure), +1 for phpass (secure password generation), so it's a wash.

lol eykanal you succeeded at stackoverflow, because stackoverflow requires openID. I don't understand that people find it difficult to login with openID. It is simple as hell. Please check out my demo at westerveld.name/php-openid and login with for example google or myopenID. It is so easy...

OpenID is a failure from the point of view of the consumer, not the developer. It's no surprise that a developer-oriented site like SO uses it with little problem, but for consumers it solves a problem they never had, and confuses the hell out of them while doing so. That post describes the problems quite nicely.

This is kind of off subject - I haven't provided any password hashing (which is what i'm going to do) and I said that a few times in my post. The point was to see if I was vulnerable else where such as MYSQL injection and such. Thanks for the input though.

@Howdy tipped on how to hash correctly and how to prevent SQL-injections. I think I was pretty on topic. Also I gave you advice how to do it better, safer.. :$

mysql - Registration Security PHP - Stack Overflow

php mysql security error-handling registration
Rectangle 27 1

The simple answer is: don't connect an iOS app directly to the database. Think about it: you'd be embedding a username and password somewhere in the app's code, which some nefarious user will find a way to extract and exploit.

Much better way to do it: create a simple API on your website, then pass requests from mobile users through the API. Then your server handles all database connections, authentication of users, and so on, and you haven't put your database credentials in the hands of lots of unknown individuals.

php - Website to IOS App - Stack Overflow

php mysql ios sqlite web
Rectangle 27 0

I will post a fast hack to achieve a simple AD authentication with the Yii2 advance template, which will take a username/password and authenticate this combination against a MS Active Directory domain controller. In addition, it checks a given group membership from the user, for which reason only users with this group can log in.

  • The user (particular the username) have to exist in the current user table (check out the Authorization Guide to build the rbac structure). We assume further that the username from our database is the same username you want to authenticate against the AD.
  • You have set up correctly an Adldap2 wrapper for Yii2 (like alexeevdv/yii2-adldap) or load Adladp2 as a vendor module. Benefit from the wrapper: You can configure the adldap2 class in your components section of the application configuration and then you can use the wrapper as a Yii2 component.
  • Your PHP-Environment use the LDAP-Extension (e.g. run something like apt-get install php5-ldap on debian distributions).
  • You have some admin credentials to connect to the domain controller with the permission to query the AD in the way you want.

So, lets start with the basic set-up.

'components' => [
    'ldap' => [
        'class' => 'alexeevdv\adldap\Adldap',
        'options' => [
            'account_suffix' => '@stackoverflow.com',
            'domain_controllers' => ['dc1.stackoverflow.com', 'dc2.stackoverflow.com'],
            'base_dn' => 'dc=stackoverflow,dc=com',
            'admin_username' => 'someusername',
            'admin_password' => 'somepassword',
            'use_ssl' => true,
            'port' => '636'
        ],
    ],
],

I want to switch easily between ldap and local authentication. Configure some local params to have globally accessible application parameters (e.g. config/params-local.php).

return [
    'adminEmail' => 'admin@example.com',
    'authOverLdap' => true,
    'ldapGroup' => 'someldapgroup',
];

Edit your LoginForm.php, especially the validatePassword function (e.g. common/models/LoginForm.php).

/**
 * Validates the password.
 * This method serves as the inline validation for password.
 * If the authOverLdap attribute is set in the params config,
 * user and password will be authenticated over ldap
 *
 * @param string $attribute the attribute currently being validated
 * @param array $params the additional name-value pairs given in the rule
 */
public function validatePassword($attribute, $params)
{
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        // to switch between the auth-methods
        $authOverLdap = \Yii::$app->params['authOverLdap'];
        if ($authOverLdap) {
            if (!$user || !$user->validateCredentialsOverLdap($user->username, $this->password)) {
                $this->addError($attribute, 'Some error text.');
            }
        } else {
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Some error text.');
            }
        }
    }
}

Add the validateCredentialsOverLdap function in the user model which handles the LDAP auth (e.g. /common/models/User.php).

/**
 * Validates a user/password combination over ldap
 *
 * @param string $username username to validate over ldap
 * @param string $password password to validate over ldap
 * @return boolean if the provided credentials are correct and the user is a member of **ldapGroup**
 */
public function validateCredentialsOverLdap($username, $password)
{
    $authSuccess = false;
    // checking the supplied credentials against the ldap (e.g. Active Directory)
    // first step: the user must have a valid account
    // second step: the user must be in a special group
    $authOk = \Yii::$app->ldap->authenticate($username, $password);
    if ($authOk) {
        $adUser = \Yii::$app->ldap->users()->find($username);
        // the user must be in special group (set in Yii params)
        if($adUser->inGroup(\Yii::$app->params['ldapGroup'])) {
            $authSuccess = true;
        }
    }

    return $authSuccess;
}
  • Don't copy&paste these snippets! You have to know what are you doing!
  • This shall show you an example and give you a hint to achieve AD authentication with the wrapper and the Yii2 Framework.
  • I run this code in a walled garden intranet!
  • Use ever, ever the secure layers like SSL to communicate over LDAP! You dont know who is sniffing the traffic in your problably safe network. You dealing with User credentials. This can be a massive fuck up, especially in Single Sign On Environments! Don't be silly.

Yii2 ldap identity set up after authentication - Stack Overflow

authentication ldap yii2 yii2-advanced-app yii2-user
Rectangle 27 0

You might use omniauth gem to provide one application to manage its users through the second one (like a Facebook connect, for example). This app's sign in action would just be a redirect to the second one's sign in page. In this case, however, you would have 2 different user tables, which might need synchronization, but for just a simple authentication that could work.

With this approach you can't. And if your applications store other custom data about users more than email and password you should have 2 separate tables for them.

Then is there any other solution for the same where I can use my existing single user table?

devise - A common user model , controller ,authentication and ability ...

ruby-on-rails devise cancan cas