How it works...

Looking at UserServlet (which applies to the USER role), we first see the authentication step:

            securityContext.authenticate(
request, response, withParams().credential(new
CallerOnlyCredential(Roles.ADMIN)));

For example, we've used the role name as a username because if we look at the AuthenticationMechanism class (implementing HttpAuthenticationMechanism), we see it doing all the hard work of authenticating and assigning the right role to the user:

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

CallerOnlyCredential callerOnlyCredential =
(CallerOnlyCredential)
credential;

if (null == callerOnlyCredential.getCaller()) {
throw new AuthenticationException();
} else switch (callerOnlyCredential.getCaller()) {
case Roles.ADMIN:
return httpMessageContext.notifyContainerAboutLogin
(callerOnlyCredential.getCaller(), new HashSet<>
(asList(Roles.ADMIN)));
case Roles.USER:
return httpMessageContext.notifyContainerAboutLogin
(callerOnlyCredential.getCaller(), new HashSet<>
(asList(Roles.USER)));
default:
throw new AuthenticationException();
}

And back to our UserServlet, now that the user has the proper role assigned, it is just a matter of what they can and cannot do:

            userExecutor.run(() -> {
try {
userActivity.adminOperation();
response.getWriter().write("adminOperation
executed: true ");
} catch (Exception e) {
response.getWriter().write("adminOperation
executed: false ");
}

try {
userActivity.userOperation();
response.getWriter().write("userOperation
executed: true ");
} catch (Exception e) {
response.getWriter().write("userOperation
executed: false ");
}

});

And also, we try the tasks that everyone and no one can perform:

            try {
userActivity.everyoneCanDo();
response.getWriter().write("everyoneCanDo
executed: true ");
} catch (Exception e) {
response.getWriter().write("everyoneCanDo
executed: false ");
}

try {
userActivity.noneCanDo();
response.getWriter().write("noneCanDo
executed: true ");
} catch (Exception e) {
response.getWriter().write("noneCanDo
executed: false ");
}

The AdminServlet class goes through exactly the same steps using an AdminExecutor environment, so we will omit it for the sake of space.

To try out this code, just run it on a Java EE 8-compatible server using these URLs:

  • http://localhost:8080/ch05-declarative/AdminServlet
  • http://localhost:8080/ch05-declarative/UserServlet

The result example for AdminServlet will be like this:

Role "admin" access: true
Role "user" access: false
adminOperation executed: true
userOperation executed: false
everyoneCanDo executed: true
noneCanDo executed: false
..................Content has been hidden....................

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