Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Handling SecurityProvider Responses in AeroGear-Controller

Handling SecurityProvider Responses within AeroGear-Controller

This gist is a follow up a previous gist that investigated using CDI events for handling SecurityProvider responses.

Background

In short, a route can be configured so that only users belonging to certain groups can access the target endpoint. For example:

route()
       .from("/delorean").roles("admin")
       .on(RequestMethod.GET)
       .to(Home.class).anotherPage();

The SecurityProvider implementation's isRouteAllow(route) will be called for the above route. This method currently throws an exception to indicate if access is denied.

Suggestion

The suggestion here is that an instance of SecurityResult should be returned. So, a SecurityProvider implementation could look like something like this:

public class AeroGearSecurityProvider implements SecurityProvider {

    @Inject
    private AeroGearUser user;

    @Override
    public SecurityResult isRouteAllowed(Route route) {

        if (!user.hasRoles(route.getRoles())) {
            return SecurityResult.unauthorized();
        }
        return SecurityResult.success();
    }
}

The above will return a 401 status code to the caller with a content type of "application/json", which is the default if not specified.
Here are a few more examples of static methods on SecurityResult:

SecurityResult.unauthorized();
SecurityResult.unauthorized("{customErrorCode: 12345}");
SecurityResult.unauthorized("<error-code>12345</error-code>", "text/xml");
SecurityResult.forbidden();
SecurityResult.forbidden("{customErrorCode: 12345}");
SecurityResult.forbidden("<error-code>12345</error-code>", "text/xml");
SecurityResult.denied(402, "just because I feel like it");

When specifying a content type that is not "application/json", this result will be that the body/message provided will be forwarded to an explicit error view, or to the default error view, depending on whether the user has any error routes configued.
To specify an error route for a security exception use something lite this:

route()
       .on(AeroGearSecurityException.class)
       .to(Error.class).security();

Questions

  • Should it really be AeroGear-Controller that determines if a response should be returned to the caller, or if it should forward to a view?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment