Skip to content

Instantly share code, notes, and snippets.

@collinvandyck
Created September 10, 2012 03:42
Show Gist options
  • Select an option

  • Save collinvandyck/3688740 to your computer and use it in GitHub Desktop.

Select an option

Save collinvandyck/3688740 to your computer and use it in GitHub Desktop.
@Path("authenticate")
@Produces(MediaType.APPLICATION_JSON)
public class AuthResource {
private final UserDAO userDAO;
public AuthResource(UserDAO userDAO) {
this.userDAO = userDAO;
}
@GET
public User authenticate(@Context HttpContext context) {
final String apiKey = getApiKeyFromAuthorizationHeader(context);
final User user = userDAO.getUserByApiKey(apiKey);
return user;
}
private String getApiKeyFromAuthorizationHeader(HttpContext context) {
final String authorization = context.getRequest().getHeaderValue("Authorization");
if (Strings.isNullOrEmpty(authorization)) {
throw new WebApplicationException(Response.status(BAD_REQUEST).entity("Missing auth header").build());
}
final String[] pieces = authorization.split(" ");
if (pieces.length != 2) {
throw new WebApplicationException(Response.status(BAD_REQUEST).entity("Bad auth header").build());
}
if ("Basic".equals(pieces[0])) {
return new String(Base64.decodeBase64(pieces[1]), Charsets.UTF_8);
}
return pieces[1];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment