jwt java swing

Client Java JWT

Cet article est la suite de l’article Token JWT.

Dans cet article nous allons voir comment modifier notre précédente application Java et y ajouter la sécurisation avec un token JWT.

Nous allons premièrement ajouter un objet LoginJDialog qui sera notre fenêtre de connexion. Voici le contenue ne notre objet :

public class LoginJDialog extends JDialog implements ActionListener, PropertyChangeListener{
  private JLabel emailLabel;
  private JLabel passwordLabel;
  private JTextField emailField;
  private JPasswordField passwordField ;
  private JButton boutonLogin;
  private ConnectionRest connectionRest;
  private PropertyChangeSupport ptChSupport = new  PropertyChangeSupport(this);
						
  public LoginJDialog(JFrame mainFrame){
    super(mainFrame);	
    initialize();
    this.setVisible(true);
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(boutonLogin)) {
      try {	
        JSONObject jsonAuthentification = new JSONObject();
        jsonAuthentification.put("email",emailField.getText());
        jsonAuthentification.put("password",new String(passwordField.getPassword()));
        jsonAuthentification.put("app","MNA"); // Code de l'application (Ma Nouvelle Application)
        connectionRest = new ConnectionRest("POST");
        connectionRest.setObj(jsonAuthentification);
        connectionRest.setAction("auth");			                
        connectionRest.addPropertyChangeListener(this);
        connectionRest.start();
      } catch (JSONException e1) {
        e1.printStackTrace();
      }
    }
  }
	
  public void propertyChange(PropertyChangeEvent evt) {
    if(evt.getSource().equals(connectionRest)){
      if(((String)evt.getNewValue()).charAt(0)=='{'){
        System.err.println("Erreur : "+evt.getNewValue());
      }else {
        Param.getInstance().setToken((String)evt.getNewValue());
        ptChSupport.firePropertyChange("AuthorizationOk", null, evt.getNewValue());
        this.setVisible(false);
      }
    }
  }
	
  private void initialize() {
    try {
      UIManager.setLookAndFeel(new NimbusLookAndFeel());
      this.setSize(240, 150);
      this.setLocationRelativeTo(null);
      this.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
        }
      });
      this.setVisible(true);	
      this.setTitle("Connection");
			
      emailLabel = new JLabel("E-mail : ");
     passwordLabel = new JLabel("Password : ");

      emailField = new JTextField();
      passwordField = new JPasswordField();

      boutonLogin = new JButton("Connection");
      getContentPane().setLayout(new GridBagLayout());
			
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.insets = new Insets(4, 4, 4, 4);

      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.weightx = 0;
      getContentPane().add(emailLabel, gbc);

      gbc.gridx = 1;
      gbc.gridy = 0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.weightx = 1;
      getContentPane().add(emailField, gbc);

      gbc.gridx = 0;
      gbc.gridy = 1;
      gbc.fill = GridBagConstraints.NONE;
      gbc.weightx = 0;
      getContentPane().add(passwordLabel, gbc);
			
      gbc.gridx = 1;
      gbc.gridy = 1;
      gbc.weightx = 1;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      getContentPane().add(passwordField, gbc);

      gbc.gridx = 0;
      gbc.gridy = 2;
      gbc.weightx = 2;
      gbc.gridwidth = 2;
      getContentPane().add(boutonLogin, gbc);
		     
      boutonLogin.addActionListener(this);	
    } catch (Exception exc) {
      exc.printStackTrace();
    }
  }

  public void addPropertyChangeListener(PropertyChangeListener l){ptChSupport.addPropertyChangeListener(l);}
  public void removePropertyChangeListener(PropertyChangeListener l){ptChSupport.removePropertyChangeListener(l);}
}

Nous nous lancerons cette fenêtre de connexion depuis notre fenêtre principale RestJFrame en y ajoutant l’interface PropertyChangeListener et sa fonction propertyChange() et ces lignes dans la fonction initialize() :

public class RestJFrame extends JFrame implements ActionListener, PropertyChangeListener{

  private LoginJDialog loginJDialog = null;
  ...
  public void propertyChange(PropertyChangeEvent evt) {
    if(evt.getSource().equals(loginJDialog)&&evt.getPropertyName().equals("AuthorizationOk")){
      refresh();
    }
  }
  ...
  private void initialize() {
    ...
    loginJDialog = new LoginJDialog(this);
    loginJDialog.addPropertyChangeListener(this);
    ...
  }
  ...
}

Param.java :

package org.libreapps.rest;

public class Param {
    private String token;
    private static Param param;

    private Param() {
    }

    public static Param getInstance() {
        if (param == null) {
            param = new Param();
        }
        return param;
    }

    public void setToken(String token) { this.token = token; }

    public String getToken() { return token; }
}

Ensuite nous devons modifier ConnectionRest et y ajouter deux chaînes de caractères action et token avec leur seteur et modifierons la méthode get comme ce-ci :

public class ConnectionRest extends Thread{

  private String methode, action = "product";
  ...
  public String get(String pMethode) throws IOException, JSONException {
    String url = URL+action+"/";
    ...
     conn.setRequestMethod(pMethode);     
     if(Param.getInstance().getToken()!=null) {
       conn.setRequestProperty ("Authorization", "Bearer "+URLEncoder.encode(Param.getInstance().getToken(), "utf-8"));
     }
    ...
  }
  ...
  public void setAction(String action) {
    this.action = action;
  }
  ...
}

    Sources :

    http://blue-walrus.com/2015/01/simple-login-dialog-in-java-swing/
    https://eric.munier.me/jwt/