1. 程式人生 > >Shiro認證及授權說明備忘

Shiro認證及授權說明備忘

protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

   UsernamePasswordToken upToken = (UsernamePasswordToken) token;
   String username = upToken.getUsername();

// Null username is invalid
if (username == null) {
thrownew AccountException("Null usernames are not allowed by this realm.");

   }

   Connection conn = null;
   SimpleAuthenticationInfo info = null;
try {
       conn = dataSource.getConnection();

       String password = null;
       String salt = null;
switch (saltStyle) {
case NO_SALT:
           password = getPasswordForUser(conn, username)[0];
break;
case CRYPT:
// TODO: separate password and hash from getPasswordForUser[0]

thrownew ConfigurationException("Not implemented yet");
//break;
case COLUMN:
           String[] queryResults = getPasswordForUser(conn, username);
           password = queryResults[0];
           salt = queryResults[1];
break;
case EXTERNAL:
           password = getPasswordForUser(conn, username)[0];
           salt = getSaltForUser(username);

       }

if (password == null) {
thrownew UnknownAccountException("No account found for user [" + username + "]");
       }

       info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());

if (salt != null) {
           info.setCredentialsSalt(ByteSource.Util.bytes(salt));
       }

   } catch (SQLException e) {
final String message = "There was a SQL error while authenticating user [" + username + "]";
if (log.isErrorEnabled()) {
           log.error(message, e);
       }

// Rethrow any SQL errors as an authentication exception
thrownew AuthenticationException(message, e);
   } finally {
       JdbcUtils.closeConnection(conn);
   }

return info;
}

private String[] getPasswordForUser(Connection conn, String username) throws SQLException {

   String[] result;
boolean returningSeparatedSalt = false;
switch (saltStyle) {
case NO_SALT:
case CRYPT:
case EXTERNAL:
       result = new String[1];
break;
default:
       result = new String[2];
       returningSeparatedSalt = true;
   }

   PreparedStatement ps = null;
   ResultSet rs = null;
try {
       ps = conn.prepareStatement(authenticationQuery);
       ps.setString(1, username);

// Execute query
       rs = ps.executeQuery();

// Loop over results - although we are only expecting one result, since usernames should be unique
boolean foundResult = false;
while (rs.next()) {

// Check to ensure only one row is processed
if (foundResult) {
thrownew AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
           }

           result[0] = rs.getString(1);
if (returningSeparatedSalt) {
               result[1] = rs.getString(2);
           }

           foundResult = true;
       }
   } finally {
       JdbcUtils.closeResultSet(rs);
       JdbcUtils.closeStatement(ps);
   }

return result;
}