Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Uso de nsILoginManager

Imagen:traduccion-pendiente.png Esta página está traduciéndose a partir del artículo Using_nsILoginManager, razón por la cual puede haber algunos errores sintácticos o partes sin traducir. Puedes colaborar continuando con la traducción


Working with the Login Manager

Extensions often need to securely store passwords to external sites, web applications, and so on. To do so securely, they can use nsILoginManager, which provides for secure storage of sensitive password information and nsILoginInfo, which provides a way of storing login information.

Getting nsILoginManager

To get a component implementing nsILoginManager, use the following:

var passwordManager = Components.classes["@mozilla.org/login-manager;1"]
                                .getService(Components.interfaces.nsILoginManager);

Most Login Manager functions take an nsILoginInfo object as a parameter. An nsILoginInfo object contains the following attributes: hostname, form submit URL, HTTP realm, username, username field, password, and password field. The hostname, username and password attributes are mandatory, while the other fields are set based on whether the login is for a web page form or an HTTP/FTP authentication site login. See the nsILoginInfo attribute definitions for more details. Defining an nsILoginInfo object is simple:

var nsLoginInfo = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
                                             Components.interfaces.nsILoginInfo,
                                             "init");
	  
var loginInfo = new nsLoginInfo(hostname, formSubmitURL, httprealm, username, password,
                                usernameField, passwordField);

Examples

Creating a login for a web page

 var formLoginInfo = new nsLoginInfo('https://www.example.com',
                       'https://login.example.com', null,
                       'joe', 'SeCrEt123', 'uname', 'pword');

This login would correspond to a HTML form such as:

 
  <form action="https://login.example.com/foo/authenticate.cgi">
  Please log in.
  Username: <input type="text"     name="uname">
  Password: <input type="password" name="pword">
  </form>
  

Creating a site authentication login

 var authLoginInfo = new nsLoginInfo('https://www.example.com',
                       null, 'ExampleCo Login',
                       'alice', 'SeCrEt321', null, null);

This would correspond to a login on https://www.example.com when the server sends a reply such as:

 HTTP/1.0 401 Authorization Required
 Server: Apache/1.3.27
 WWW-Authenticate: Basic realm="ExampleCo Login"

Creating a local extension login

 var extLoginInfo = new nsLoginInfo('chrome://firefoo',
                      'User Registration', null,
                      'bob', '123sEcReT', null, null);

The Login Manager treats this as if it was a web site login. You should use your extension's chrome:// URL to prevent conflicts with other extensions, and a realm string which briefly denotes the login's purpose.

Almacenar una contraseña

Para almacenar una contraseña en el Gestor de Accesos, primero necesitas crear un objeto nsILoginInfo como se define arriba. Entonces simplemente necesitas llamar al método nsILoginManager addLogin().

 myLoginManager.addLogin(loginInfo);

Nota: Esto provocará una excepción si tanto el parámetro <tt>httprealm</tt> como el parámetro <tt>formSubmitURL</tt> son NULL. Uno debe ser especificado cuando se almacena una contraseña. Los parámetros <tt>hostname</tt>, <tt>username</tt> y <tt>password</tt> también son obligatorios.

Retrieving a password

Retrieving a password from the Login Manager is slightly more difficult. In order to locate a password, the <tt>hostname</tt>, <tt>formSubmitURL</tt> and <tt>httprealm</tt> must match exactly what is stored for the password to be found. The only exception is that if the stored <tt>formSubmitURL</tt> is blank, in which case the <tt>formSubmitURL</tt> parameter is ignored. Note that the <tt>hostname</tt> and <tt>formSubmitURL</tt> arguments should not include the path from the full URL. The example below should serve as a starting point for matching form logins:

var hostname = 'https://www.example.com';
var formSubmitURL = 'https://www.example.com';  // not https://www.example.com/foo/auth.cgi
var httprealm = null;
var username = 'user';
var password;

try {
   // Get Login Manager 
   var myLoginManager = Components.classes["@mozilla.org/login-manager;1"]
                         .getService(Components.interfaces.nsILoginManager);
	  
   // Find users for the given parameters
   var logins = myLoginManager.findLogins({}, hostname, formSubmitURL, httprealm);
      
   // Find user from returned array of nsILoginInfo objects
   for (var i = 0; i < logins.length; i++) {
      if (logins[i].username == username) {
         password = logins[i].password;
         break;
      }
   }
}
catch(ex) {
   // This will only happen if there is no nsILoginManager component class
}

Note that the user will be prompted for their master password if they have chosen to set one to secure their passwords.

Removing a password

Removing a password is simple:

 myLoginManager.removeLogin(loginInfo);

When removing a password the specified nsILoginInfo object must exactly match what was stored or an exception will be thrown. This includes the password attribute. Here's an example on how to remove the password without actually knowing what the password is:

// example values
var hostname = 'https://www.example.com';
var formSubmitURL = 'https://www.example.com';
var httprealm = null;
var username = 'user';

try {
   // Get Login Manager 
   var passwordManager = Components.classes["@mozilla.org/login-manager;1"]
                         .getService(Components.interfaces.nsILoginManager);
 
   // Find users for this extension 
   var logins = passwordManager.findLogins({}, hostname, formSubmitURL, httprealm);
      
   for (var i = 0; i < logins.length; i++) {
      if (logins[i].username == username) {
         passwordManager.removeLogin(logins[i]);
         break;
      }
   }
}
catch(ex) {
   // This will only happen if there is no nsILoginManager component class
}

Changing stored login information

Changing a password is rather simple. Since all this does is make a removeLogin() call followed by an addLogin() call, it has the same caveats as both of them: namely that the <tt>oldLogin</tt> must match an existing login exactly (see above) and that the <tt>newLogin</tt> attributes must be set correctly.:

myLoginManager.modifyLogin(oldLogin, newLogin);

Depuración

La implementación del gestor de accesos tiene la capacidad de enviar mensajes de depuración a la Consola de Errores, lo que puede provocar algo de visibilidad en lo que se está haciendo. Para habilitar la depuración de accesos, véase https://wiki.mozilla.org/Firefox:Pass...ager_Debugging.

Soporte de versiones anteriores de Firefox

Si quieres implementar tu extensión para que soporte Firefox 3 y versiones anteriores será necesario implementar tanto el componente nsILoginManager como el componente nsIPasswordManager. Un método simple para hacer ésto se expone a continuación:

if ("@mozilla.org/passwordmanager;1" in Components.classes) {
   // El gestor de contraseñas existe así que no es Firefox 3 (puede ser Firefox 2, Netscape, SeaMonkey, etc).
   // Código del gestor de contraseñas
}
else if ("@mozilla.org/login-manager;1" in Components.classes) {
   // El gestor de accesos existe así que es Firefox 3
   // Código del gestor de accesos
}

Etiquetas y colaboradores del documento

 Colaboradores en esta página: Talisker, Mgjbot
 Última actualización por: Talisker,