I am trying to add custom authorization in dropwizard but not able to successed.
I have a custom authentication added for dropwizard by binding it to authFactory
so based on your answers I wrote up a test and I believe I can tell you what's the issue here.
The Authfactory you are using to provide Authentication tokens is not a request Filter. based on the documentation of jersey, this is the execution order of a request:
https://jersey.java.net/documentation/latest/filters-and-interceptors.html#d0e9976
The issue is the following:
ALL request filter will always be executed before your binding is executed. At the time of the request, jersey doesn't even know if it needs to bind anything to your method at all. Why should it create anything, a filter might reject the request before it gets to execution.
So in short, annotating your resource method with @Auth simply adds an injection binder to your jersey environment. You can read about custom injection here:
https://jersey.java.net/documentation/latest/ioc.html
This obviously works correctly and is quite handy, however not what you want. What you want is to reject a request before it passed through any filter. For this you MUST write a request filter. Annotate it with the correct priority and everything should be working fine.
You could have a think about extracting your auth logic into a common class (Which you already did) and then register the same class with a RequestFilter and your Authenticator, therefore keeping the Auth provider, while still having request filtering based on Authentication.
run(...) {
myAuthStuff = create()
jersey.register(MyAuthRequstFilter(myAuthStuff));
jersey.register(MyAuthInjectionBinder(myAuthStuff));
}
Add a cache and you won't have to worry about calling the same thing twice.
I believe dropwizard did not intend this to work with filters. It appears their intention was to inject the auth context into a resource method and do authentication etc in there. Not my preferred solution, but it could work.
So to sum stuff up:
What you want to do is not supported by dropwizard out of the box. The solution is to extend their solution into a request filter.
Hope that helps,
Artur