Java Reference
In-Depth Information
Another great use case for request filters is implementing custom authentication protocols.
For example, OAuth 2.0 has a token protocol that is transmitted through the Authorization
HTTP header. Here's what an implementation of that might look like:
import
import javax.ws.rs.container.ContainerRequestFilter
javax.ws.rs.container.ContainerRequestFilter ;
import
import javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext ;
import
import javax.ws.rs.NotAuthorizedException
javax.ws.rs.NotAuthorizedException ;
@Provider
@PreMatching
public
public class
class BearerTokenFilter
BearerTokenFilter implements
implements ContainerRequestFilter {
public
public void
throws IOException {
String authHeader = request . getHeaderString ( HttpHeaders . AUTHORIZATION );
iif ( authHeader == null
void filter ( ContainerRequestContext ctx ) throws
new NotAuthorizedException ( "Bearer" );
String token = parseToken ( authHeader );
iif ( verifyToken ( token ) == false
null ) throw
throw new
false ) {
throw
throw new
new NotAuthorizedException ( "Bearer error=\"invalid_token\"" );
}
}
private
private String parseToken ( String header ) {...}
private
private boolean
boolean verifyToken ( String token ) {...}
}
In this example, if there is no Authorization header or it is invalid, the request is aborted
with a NotAuthorizedException . The client receives a 401 response with a WWW-
Authenticate header set to the value passed into the constructor of NotAuthorizedExcep-
tion . If you want to avoid exception mapping, then you can use the Container-
RequestContext.abortWith() method instead. Generally, however, I prefer to throw ex-
ceptions.
Server Response Filters
Response filters are implementations of the ContainerResponseFilter interface:
package
package javax . ws . rs . container ;
public
public interface
interface ContainerResponseFilter
ContainerResponseFilter {
public
public void
void filter ( ContainerRequestContext requestContext ,
ContainerResponseContext responseContext )
throws
throws IOException ;
}
Search WWH ::




Custom Search