Setting up LoginModule

LoginModule is responsible for authenticating a user. We will be creating our own LoginModule named JaasLoginModule and then implementing the login method. Being a sample application, our login logic is quite trivial. The LoginModule interface has to be implemented for you to write your own custom login module.

Create a class, JaasLoginModule.java (which implements LoginModule), and implement all the methods. In this class, we will be focusing on two important methods. In the initialize method, we get all the necessary information, such as username/password/subject, that is stored as field variables to be used in our main login method:

// Gather information and then use this in the login method
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String,
?> sharedState, Map<String, ?> options) {
this.subject = subject;

NameCallback nameCallback = new NameCallback("Username:");
PasswordCallback passwordCallback = new PasswordCallback("Password:", false);
try {
callbackHandler.handle(new Callback[] { nameCallback, passwordCallback });
} catch (IOException e) {
e.printStackTrace();
} catch (UnsupportedCallbackException e) {
e.printStackTrace();
}
username = nameCallback.getName();
password = new String(passwordCallback.getPassword());
}

In the login method, we will log in using the values stored in the initialize method. In our case, if the hard-coded username/password is valid, set the principal in the subject:

// Code where actual login happens. Implement any logic as required by your application
// In our sample we are just doing a hard-coded comparison of username and password
@Override
public boolean login() throws LoginException {
if (username == null || (username.equalsIgnoreCase("")) ||
password == null || (password.equalsIgnoreCase(""))) {
throw new LoginException("Username and password is mandatory.");
} else if (username.equalsIgnoreCase("admin") &&
password.equalsIgnoreCase("password")) {
subject.getPrincipals().add(new JaasPrincipal(username));
return true;
} else if (username.equalsIgnoreCase("user") &&
password.equalsIgnoreCase("password")) {
subject.getPrincipals().add(new JaasPrincipal(username));
return true;
}
return false;
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.190.156.93