How it works...

Contrary to the declarative approach (see the previous recipe in this chapter), here we are using code to validate the user. We've done it by implementing the IdentityStore interface.

For example, even though we've hardcoded the password, you can use the same piece of code to validate the password against a database, LDAP, an external endpoint, and many more:

        if (usernamePasswordCredential.getCaller().equals(Roles.ADMIN)
&&
usernamePasswordCredential.getPassword().compareTo("1234"))
{

return new CredentialValidationResult(
new CallerPrincipal(usernamePasswordCredential
.getCaller()),
new HashSet<>(asList(Roles.ADMIN)));
} else if (usernamePasswordCredential.getCaller()
.equals(Roles.USER)
&& usernamePasswordCredential.
getPassword().compareTo("1234"))
{

return new CredentialValidationResult(
new CallerPrincipal(usernamePasswordCredential
.getCaller()),
new HashSet<>(asList(Roles.USER)));
}

return INVALID_RESULT;

Authenticating using IdentityStore means just delegating using HttpAuthenticationMethod:

            Credential credential = 
httpMessageContext.getAuthParameters().getCredential();
if (!(credential instanceof UsernamePasswordCredential)) {
throw new IllegalStateException("Invalid mechanism");
}

return httpMessageContext.notifyContainerAboutLogin
(identityStore.validate(credential));

And then, OperationServlet will just try an authentication:

        String name = request.getParameter("name");
String password = request.getParameter("password");

Credential credential = new UsernamePasswordCredential(name,
new Password(password));

AuthenticationStatus status = securityContext.authenticate(
request, response,
withParams().credential(credential));

Based on this, we will define the flow of what will happen next:

        if (status.equals(AuthenticationStatus.SUCCESS)) {

if (request.isUserInRole(Roles.ADMIN)) {
userActivity.adminOperation();
response.getWriter().write("adminOperation
executed: true ");
} else if (request.isUserInRole(Roles.USER)) {
userActivity.userOperation();
response.getWriter().write("userOperation
executed: true ");
}

userActivity.everyoneCanDo();
response.getWriter().write("everyoneCanDo executed:

true ");

} else {
response.getWriter().write("Authentication failed ");
}

Pay attention! That is your code defining what each role will do.

..................Content has been hidden....................

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