Skip to content

Instantly share code, notes, and snippets.

@0guzhan
Created November 19, 2017 21:42
Show Gist options
  • Save 0guzhan/60734a3df30690d72d0db0e1712824e4 to your computer and use it in GitHub Desktop.
Save 0guzhan/60734a3df30690d72d0db0e1712824e4 to your computer and use it in GitHub Desktop.
AuthenticateFilter for Dropwizard Restful Endpoint which simply checks authentication with filter HTTP Request
import org.apache.commons.lang3.StringUtils;
import com.google.inject.Singleton;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
@Authenticator
@Singleton
public class AuthenticateFilter implements ContainerRequestFilter {
private static final String PARAM_API_KEY = "apiKey";
private static final String PARAM_TOKEN = "token";
@Override
public void filter(ContainerRequestContext context) throws IOException {
final String apiKey = extractParam(context, PARAM_API_KEY);
if (StringUtils.isEmpty(apiKey)) {
context.abortWith(responseMissingParameter(PARAM_API_KEY));
}
final String token = extractParam(context, PARAM_TOKEN);
if (StringUtils.isEmpty(token)) {
context.abortWith(responseMissingParameter(PARAM_TOKEN));
}
if (!authenticate(apiKey, token)) {
context.abortWith(responseUnauthorized());
}
}
private String extractParam(ContainerRequestContext context, String param) {
final UriInfo uriInfo = context.getUriInfo();
final List<String> paramValues = uriInfo.getQueryParameters().get(param);
return paramValues != null && !paramValues.isEmpty() ? String.valueOf(paramValues.get(0)) : null;
}
private Response responseMissingParameter(String name) {
return Response.status(Response.Status.BAD_REQUEST)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("Parameter '" + name + "' is required.")
.build();
}
private boolean authenticate(String apiKey, String token) {
return new Random().nextBoolean();
}
private Response responseUnauthorized() {
return Response.status(Response.Status.UNAUTHORIZED)
.type(MediaType.TEXT_PLAIN_TYPE)
.entity("Unauthorized")
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment