001package de.deepamehta.core.service.accesscontrol; 002 003import de.deepamehta.core.util.JavaUtils; 004 005import org.codehaus.jettison.json.JSONObject; 006 007import com.sun.jersey.core.util.Base64; 008 009 010 011/** 012 * A pair of username and SHA256 encoded password. 013 */ 014public class Credentials { 015 016 // ------------------------------------------------------------------------------------------------------- Constants 017 018 private static final String ENCODED_PASSWORD_PREFIX = "-SHA256-"; 019 020 // ---------------------------------------------------------------------------------------------- Instance Variables 021 022 public String username; 023 public String password; // encoded 024 025 // ---------------------------------------------------------------------------------------------------- Constructors 026 027 /** 028 * @param password as plain text 029 */ 030 public Credentials(String username, String password) { 031 this.username = username; 032 this.password = encodePassword(password); 033 } 034 035 /** 036 * Note: invoked from JAX-RS message body reader (see Webservice's ObjectProvider.java). 037 * 038 * @param cred A JSON object with 2 properties: "username" and "password". 039 * The password is expected to be SHA256 encoded. 040 */ 041 public Credentials(JSONObject cred) { 042 try { 043 this.username = cred.getString("username"); 044 this.password = cred.getString("password"); 045 } catch (Exception e) { 046 throw new IllegalArgumentException("Illegal JSON argument " + cred, e); 047 } 048 } 049 050 public Credentials(String authHeader) { 051 authHeader = authHeader.substring("Basic ".length()); 052 String[] values = new String(Base64.base64Decode(authHeader)).split(":"); 053 // Note: values.length is 0 if neither a username nor a password is entered 054 // values.length is 1 if no password is entered 055 this.username = values.length > 0 ? values[0] : ""; 056 this.password = encodePassword(values.length > 1 ? values[1] : ""); 057 // Note: credentials obtained through Basic authorization are always plain text 058 } 059 060 // -------------------------------------------------------------------------------------------------- Public Methods 061 062 public String toString() { 063 return "username=\"" + username + "\", password=\""+ password + "\""; 064 } 065 066 // ------------------------------------------------------------------------------------------------- Private Methods 067 068 private String encodePassword(String password) { 069 return ENCODED_PASSWORD_PREFIX + JavaUtils.encodeSHA256(password); 070 } 071}