Friday, 27 July 2012

Shiro 1.2 new PasswordService and PasswordMatcher

This becomes super simple and clean.

Here is the summary:

1. Signing-up code:
  // Using the new PasswordService instead
  PasswordService svc = new DefaultPasswordService();

  //e.g. during account signup or password reset:
  String encryptedPassword = svc.encryptPassword(password);
  logger.debug("encryptedPassword: " + encryptedPassword);

  // Salt is not needed to handel separately but encrypted all together within the "password"
  // Example password becomes $shiro1$SHA-256$500000$gTF/EC2mLKxlln2w1CMUAQ==$HvG+0Qe1RONAF41bUy11hjkgqdHrwwf/urEAXeYDt1w=
  User user = new User(username, encryptedPassword, null, email);
  userDao.createUser(user);

 2. INI configuration:
  passwordMatcher = org.apache.shiro.authc.credential.TempFixPasswordMatcher
  # since jdbcRealm is used, the stored password in String needs to be converted to char[]
  # algorithm related configuration comes in default
  passwordService = org.apache.shiro.authc.credential.DefaultPasswordService
  passwordMatcher.passwordService = $passwordService

  realmDS = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
  realmDS.serverName = localhost
  realmDS.user = root
  realmDS.databaseName = test

  jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
  jdbcRealm.credentialsMatcher = $passwordMatcher
  jdbcRealm.authenticationQuery = select password from user where username = ?
  jdbcRealm.dataSource = $realmDS

  securityManager.realm = $jdbcRealm

3. Matcher code
  public class TempFixPasswordMatcher extends PasswordMatcher {

      @Override
      protected Object getStoredPassword(AuthenticationInfo storedAccountInfo) {
          Object stored = super.getStoredPassword(storedAccountInfo);
          if (stored instanceof char[]) {
              return new String((char[])stored);
          }
          return stored;
      }
  }

  source1, source2


No comments: