Sunday 21 July 2013

Zend Framework 2: Bcrypt adapter for Zend Authentication component

ZF2 provides us with a class for using bcrypt algorithm for hashing and verifying passwords.

I want to try it with zend authentication component. I'd like to use bcrypt algorithm with dbTable authentication adapter.

Unfortunately, ZF2 has no built-in auth adapter for this.

Ok, let's make our own auth adapter based on DbTable auth adapter.

The logic is:
- fetch all rows from table where identity column value is equal to value of identity field from login form(it could be login name, email, etc)
- check if entered password is valid using bcrypt->verify() method

Implementation:

1. Create class that extends DbTable auth adapter

// define namespace for the class
namespace SomeModule\Auth\Adapter;

class BcryptDbAdapter extends DbTable
{
}

2. It is necessary to redefine two methods in our new class.
First method: authenticateCreateSelect() - method that creates a Zend\Db\Sql\Select object for fetching data from database
Second method: authenticateQuerySelect() - method that fetches data from database using Zend\Db\Sql\Select object from previous method.

Our class will look like below:

namespace SomeModule\Auth\Adapter;

use Zend\Authentication\Adapter\DbTable;
use Zend\Db\Sql;
use Zend\Db\Sql\Predicate\Operator as SqlOp;

class BcryptDbAdapter extends DbTable
{
    protected function authenticateCreateSelect()
    {
        // get select
        $dbSelect = clone $this->getDbSelect();
        $dbSelect->from($this->tableName)
            ->columns(array('*'))
            ->where(new SqlOp($this->identityColumn, '=', $this->identity));

        return $dbSelect;
    }

    protected function authenticateQuerySelect(Sql\Select $dbSelect)
    {
        $sql = new Sql\Sql($this->zendDb);
        $statement = $sql->prepareStatementForSqlObject($dbSelect);

        try {
            $result = $statement->execute();
            $resultIdentities = array();

            // create object ob Bcrypt class
            $bcrypt = new \Zend\Crypt\Password\Bcrypt();

            // iterate result, most cross platform way
            foreach ($result as $row) {
                if ($bcrypt->verify($this->credential, $row[$this->credentialColumn])) {
                    $row['zend_auth_credential_match'] = 1;
                    $resultIdentities[] = $row;
                }
            }

        } catch (\Exception $e) {
            throw new Exception\RuntimeException(
                'The supplied parameters to DbTable failed to '
                    . 'produce a valid sql statement, please check table and column names '
                    . 'for validity.', 0, $e
            );
        }

        return $resultIdentities;
    }
}
3. How to use example.

- Add required namespaces to controller:
use SomeModule\Auth\Adapter\BcryptDbAdapter as AuthAdapter;
use Zend\Authentication\AuthenticationService;

- Authenticate user in login action:

$data = $request->getPost();

$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');

$authAdapter = new AuthAdapter($dbAdapter);

$authAdapter
  ->setTableName('users')
  ->setIdentityColumn('email')
  ->setCredentialColumn('password');

$authAdapter
  ->setIdentity(addslashes($data['email']))
  ->setCredential($data['password']);

// attempt authentication
$result = $authAdapter->authenticate();

if (!$result->isValid()) {
  // Authentication failed
} else {
  $auth = new AuthenticationService();
  $storage = $auth->getStorage();

  $storage->write($authAdapter->getResultRowObject(
    null,
    'password'
  ));
}

Source code is available on GitHub

50 comments:

  1. Now a day Web site is very important to promote our business in easy way.
    Website Development in Bangalore | Website Development Bangalore

    ReplyDelete
  2. Thanks. It's awesome ,it is realy helpful

    Searchinfomedia

    ReplyDelete
  3. Web Developing field becoming huge growth because of increase the demand of websites.
    Web Designing Companies India | Web Development Companies

    ReplyDelete
  4. Frame work is very necessary thing for website designing to make a extra looking to websites.
    Web Design Company | Web Development Companies

    ReplyDelete
  5. Thanks for the sharing of such information. we will pass it on to our readers. This is a great reading. Thanking you.
    web design company in delhi

    ReplyDelete
  6. Implementation of the right solutions and effective designing techniques of your website will help the website in gaining a top search engine position and thus ” boost ” its sales.
    Web Designing Company Bangalore | Magento Services India

    ReplyDelete
  7. Cool! Glad that you shared this codes. It will be useful information. Keep posting.


    Racks and UPS

    ReplyDelete
  8. Your blog post about zend framework is much valuable with interesting posts. Good Work.
    Web Design Services India | Web Design Companies Bangalore

    ReplyDelete
  9. By the help of Search Engine Optimization techniques we could make the good performance to website and improve the position on search engines.

    Web Design Companies Bangalore | SEO Specialist Bangalore

    ReplyDelete
  10. This is an informative blog by which I have got that info which I really wanted to get.
    website designers hyderabad Pakistan

    ReplyDelete
  11. Its a nice blog i keep visiting this blog everyday thank you so much for sharing ...


    Web Development Company in Lucknow

    ReplyDelete
  12. Webzin Infotech has a mission to provide you with the best of web design and development services . We aim at helping you create the optimum website which will offer your rival and competition websites the competition they need.
    seo company india

    ReplyDelete
  13. Zend Frame work is a good segment to make the attractive frame and structure to the websites.
    Web Design Companies | Responsive Design Companies

    ReplyDelete
  14. As long as you own or have the rights to use the design, whether it's an existing HTML design for your site, an existing CMS theme design, or PDF/PSD/AI document, even a jpeg image, then we can be your design implementation team and help you develop that design into a full Magento theme.

    Website Developer in Bangalore | Website Development Company in Bangalore

    ReplyDelete
  15. I have research some fantastic things here. Definitely value community public bookmark submitting for coming back to. I query how much attempt you put to make the kind of amazing useful web page.

    website development companies Bangalore | website designing Bangalore

    ReplyDelete
  16. Thanks for sharing the information. It is very useful for my future. keep sharing.
    Signature:
    Jugar juegos de frozen en línea gratis, los nuevos de princesa de Disney juegos frozen - la princesa encantadora y linda. Divertirse frozen!

    ReplyDelete
  17. Great post,Thanks for providing us this great knowledge,Keep it up.
    A good blog.
    Signature:
    The place to play all unblocked games online. Here you can find every blocked games such as: unblockedgames , unblocked games happy , unblocked games 77 , Garry's Mod Free

    ReplyDelete
  18. Nice Post..Its the best post for me..am reach the best message using your post..Keep sharing...Web Design Bangalore | Web Development Bangalore

    ReplyDelete
  19. Very useful information for web development thank you for sharing this useful article,your blog used to improve our knowledge thank you for sharing...
    Web Development Company Bangalore|Web Design Company Bangalore

    ReplyDelete
  20. Cool Runnings Found your site from a friends Facebook link, Heavy Weights | Rookie of the Year it seems that you have growing fanbase and I now understand why Super informative article, thanks a million. Best Action Movies

    ReplyDelete
  21. I think the content covered in the blog is quiet impressive and brilliantly conveyed. Good job and great efforts. Keep it up.
    Web development Company in India Company | Web development Company Bangalore
    Web Development Company in Bangalore | Responsive Web development I think the content covered in the blog is quiet impressive and brilliantly conveyed. Good job and great efforts. Keep it up.
    Web development Company in India Company | Web development Company Bangalore
    Web Development Company in Bangalore | Responsive Web development

    ReplyDelete
  22. Thank you for sharing such an informative news with us. Keep on sharing Contents like this. You can also share this content on various sites like the Automation Associates LLC site.

    ReplyDelete
  23. Come back again for more interesting stuff like this post scorehero.net

    ReplyDelete
  24. Hello, just wanted to say, I loved this article. It was practical.

    live slow die whenever

    ReplyDelete
  25. I am looking for my memories through the stories, the narrative of people. I feel it is difficult but I will try.
    instagram online viewer

    ReplyDelete
  26. This comment has been removed by the author.

    ReplyDelete
  27. To rank your website on a SEO in Bangalore search engine is very important but a high rank can only bring you customers if you have right keywords . If you know what keywords will work for you then it is awesome , If not Dont Worry at all , our super SEO team will do the proper analysis and then sit with you to decide which keywords will be the best for your business.

    ReplyDelete
  28. Informative and impressive. Keep Updating
    ssd festplatte

    ReplyDelete

  29. The website is looking bit flashy and it catches the visitors eyes. A design is pretty simple .
    jobbörse südwestfalen

    ReplyDelete
  30. This comment has been removed by the author.

    ReplyDelete
  31. Another major advantage of hiring a complete agency is that they will be having a team working together with people having extra skill sets like designers, developers, advertisers, SEO experts, social media geeks, etc.
    Digital Marketing Company in Bangalore | SEO Services in Bangalore

    ReplyDelete
  32. Bagi bettor yang mencoba memainkan permainan capsa susun online, maka setiap pemain nanti wajib untuk membuat susunan kartu
    asikqq
    dewaqq
    sumoqq
    interqq
    pionpoker
    bandar ceme terpercaya
    hobiqq
    paito warna terlengkap
    bocoran sgp

    ReplyDelete
  33. Best Web Design Company In India, Bangalore & Delhi

    https://www.nextwebi.com

    ReplyDelete

  34. I really appreciate this post and I like this very much. I am waiting for new post here and Please keep it up in future.. Web Development Sydney. Visit us https://www.designpluz.com.au

    ReplyDelete
  35. This comment has been removed by the author.

    ReplyDelete
  36. Dabrande is the one-stop and top-leading digital marketing company in Ludhiana, punjab. we offer quality and cost-effective SEO, SMO, PPC, website designing, social media marketing, email marketing services and more to boost sales, traffic, branding and revenue. if you are still searching for the best digital marketing and website designing company in Ludhiana, punjab, feel free to get in touch with Dabrande.

    The company offers the creative, robust, mobile-friendly, user-friendly ecommerce website. Our website design services are delivered with an intention to boost, user-engagement and high rate of conversions and lead generation. With Dabrande SEO Company in Punjab, you can boost ranking to get your website visibile at top in Google SERPs.

    mobile app development company in punjab
    digital marketing company in Punjab
    SEO company in punjab
    logo designing company in Ludhiana
    website design company in punjab
    website designers in punjab
    web development company in punjab
    social media marketers in Punjab
    social media marketing company in Punjab

    ReplyDelete
  37. Tecocraft is one of the leading companies for a website development company in Surat Gujarat. At Tecocraft, highly experienced, skilled, and tech-savvy web developers build customer focusing web developing services with the latest web technology, from small start-ups to large enterprise-level companies.

    website development company in Surat Gujarat

    Thanks & Regards
    Tecocraft Infusion Pvt Ltd

    ReplyDelete
  38. Very Informative Blog. An interesting and amazing post. Thanks for sharing this wonderful informative article here
    digital marketing services
    best web development company

    ReplyDelete
  39. I am very happy with your article.

    ReplyDelete
  40. Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today! https://just99marketing.com/wordpress-web-design

    ReplyDelete