Dear fellow developers,

I am building a small web framework based on Jax-rs (Resteasy) and undertow (with undertow-servlet) and I am having interrogations about authenticating requests...
First of all, I know I shouldn't re-invent the wheel and build another framework from scratch, but I am doing it purely for educational purposes (my education!)

The setup is very simple: an embedded servlet container (undertow), bootstrapping one single jax-rs servlet (resteasy), with little glue around all of this et voilà! The user (person using the framework) only has to focus on his jax-rs resources.

The servlet api already specifies how authentication should be done, and undertow implements it and I am not here to question that. 
However, what I want to achieve is to delegate all the authentication logic to the Jax-rs layer.
I see two advantages in this:
- The user has full control over the login / user management system, without having to tweak the servlet deployment... He can decide to do logins against a DB, a remote web service etc... all programatically.
- Use the Jax-rs "DynamicFeature" feature.. to control what resources have to be secured. To illustrate it, here is a code sample of how I intend to use the DynamicFeature:

@Provider
public class AuthenticationNeededFeature implements DynamicFeature {

  @Inject
  private AuthenticationFilter authenticationFilter;
  
  @Override
  public void configure(ResourceInfo resourceInfo, FeatureContext context) {

    /* If resource is not public then we add the authentication filter */
    if (!resourceInfo.getResourceMethod().isAnnotationPresent(Public.class)) {
      context.register(authenticationFilter);
    }
  }
}

This simply checks if the targeted resource method has the annotation Public on it (custom annotation). If not, the resource must then be authenticated and a ContainerRequestFilter is registered, to apply the authentication logic.

The user can do anything he wants to authenticate the request inside the filter:
- Look in a custom Authorization header for a bearer token
- Validate the token against a db or a cache
- Play with cookies

And more importantly, the securityContext, can be set here, as the Request object is available.
The user can manufacture a securityContext containing the current user's principal and roles (after a successful authentication of the request) and therefore enable the role based access control in the resources (@RolesAllowed).

I had a little try with adding a ServletExtension into the deployment, with a custom AuthenticationMechanism, but I couldn't achieve what is described above, as it is really jax-rs specific.

I haven't seen a lot of people on the internet doing what I have described above... that's why I am not that confident! I am indeed bypassing all the security layer already available in Undertow. I feel I am missing the elephant in the room...

What do you think about that approach?

Thank you all in advance.

Best regards,
Antoine